-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_test.go
More file actions
1110 lines (949 loc) · 31.6 KB
/
main_test.go
File metadata and controls
1110 lines (949 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
)
func TestTruncate(t *testing.T) {
tests := []struct {
name string
input string
maxLen int
expected string
}{
{"short string", "hello", 10, "hello"},
{"exact length", "hello", 5, "hello"},
{"needs truncation", "hello world", 8, "hello..."},
{"with newlines", "hello\nworld", 20, "hello world"},
{"multiple spaces", "hello world", 20, "hello world"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := truncate(tt.input, tt.maxLen)
if result != tt.expected {
t.Errorf("truncate(%q, %d) = %q, want %q", tt.input, tt.maxLen, result, tt.expected)
}
})
}
}
func TestPadRight(t *testing.T) {
tests := []struct {
name string
input string
length int
expected string
}{
{"short string", "hello", 10, "hello "},
{"exact length", "hello", 5, "hello"},
{"needs truncation", "hello world", 8, "hello wo"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := padRight(tt.input, tt.length)
if result != tt.expected {
t.Errorf("padRight(%q, %d) = %q, want %q", tt.input, tt.length, result, tt.expected)
}
})
}
}
func TestFormatTimestamp(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{"empty", "", ""},
{"invalid short", "abc", "abc"},
{"valid RFC3339", "2024-01-15T10:30:00Z", "2024-01-15"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := formatTimestamp(tt.input)
if tt.name == "valid RFC3339" {
// Just check it starts with the date (time zone varies)
if !strings.HasPrefix(result, "2024-01-1") {
t.Errorf("formatTimestamp(%q) = %q, want prefix '2024-01-1'", tt.input, result)
}
} else if result != tt.expected {
t.Errorf("formatTimestamp(%q) = %q, want %q", tt.input, result, tt.expected)
}
})
}
}
func TestExtractText(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{"simple string", `"hello world"`, "hello world"},
{"empty", ``, ""},
{"array with text", `[{"type":"text","text":"hello"},{"type":"text","text":"world"}]`, "hello world"},
{"array with non-text", `[{"type":"image","text":"ignore"},{"type":"text","text":"hello"}]`, "hello"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := extractText(json.RawMessage(tt.input))
if result != tt.expected {
t.Errorf("extractText(%q) = %q, want %q", tt.input, result, tt.expected)
}
})
}
}
func TestBuildItems(t *testing.T) {
conversations := []Conversation{
{
SessionID: "session1",
Cwd: "/home/user/project1",
FirstTimestamp: "2024-01-15T10:00:00Z",
LastTimestamp: "2024-01-15T10:03:00Z",
Messages: []Message{
{Role: "user", Text: "first message", Ts: "2024-01-15T10:00:00Z"},
{Role: "assistant", Text: "response 1", Ts: "2024-01-15T10:01:00Z"},
{Role: "user", Text: "second message", Ts: "2024-01-15T10:02:00Z"},
{Role: "assistant", Text: "response 2", Ts: "2024-01-15T10:03:00Z"},
},
},
{
SessionID: "session2",
Cwd: "/home/user/project2",
FirstTimestamp: "2024-01-16T10:00:00Z",
LastTimestamp: "2024-01-16T10:01:00Z",
Messages: []Message{
{Role: "user", Text: "hello world", Ts: "2024-01-16T10:00:00Z"},
{Role: "assistant", Text: "hi there", Ts: "2024-01-16T10:01:00Z"},
},
},
}
items := buildItems(conversations)
// Should have exactly one item per conversation
if len(items) != 2 {
t.Errorf("buildItems returned %d items, want 2", len(items))
}
// First item should be for session1
if items[0].conv.SessionID != "session1" {
t.Errorf("first item should be session1, got %q", items[0].conv.SessionID)
}
// Search text should contain all user messages
if !strings.Contains(items[0].searchText, "first message") || !strings.Contains(items[0].searchText, "second message") {
t.Errorf("search text should contain all user messages, got %q", items[0].searchText)
}
// Search text should contain session ID
if !strings.Contains(items[0].searchText, "session1") {
t.Errorf("search text should contain session ID, got %q", items[0].searchText)
}
// Search text should contain cwd
if !strings.Contains(items[0].searchText, "/home/user/project1") {
t.Errorf("search text should contain cwd, got %q", items[0].searchText)
}
// Second item should be for session2
if items[1].conv.SessionID != "session2" {
t.Errorf("second item should be session2, got %q", items[1].conv.SessionID)
}
}
func TestBuildItemsNoUserMessages(t *testing.T) {
conversations := []Conversation{
{
SessionID: "session1",
Cwd: "/home/user/project1",
FirstTimestamp: "2024-01-15T10:00:00Z",
LastTimestamp: "2024-01-15T10:00:00Z",
Messages: []Message{
{Role: "assistant", Text: "only assistant", Ts: "2024-01-15T10:00:00Z"},
},
},
}
items := buildItems(conversations)
// Should still have one item (we include all conversations now)
if len(items) != 1 {
t.Errorf("buildItems returned %d items, want 1", len(items))
}
}
func TestBuildItemsProjectExtraction(t *testing.T) {
conversations := []Conversation{
{
SessionID: "session1",
Cwd: "/home/user/my-project",
FirstTimestamp: "2024-01-15T10:00:00Z",
LastTimestamp: "2024-01-15T10:00:00Z",
Messages: []Message{
{Role: "user", Text: "test", Ts: "2024-01-15T10:00:00Z"},
},
},
}
items := buildItems(conversations)
// Search text should contain full path
if !strings.Contains(items[0].searchText, "/home/user/my-project") {
t.Errorf("search text should contain full path, got %q", items[0].searchText)
}
}
func TestHighlight(t *testing.T) {
tests := []struct {
name string
text string
query string
contains string
}{
{"empty query", "hello world", "", "hello world"},
{"matching query", "hello world", "world", "world"},
{"case insensitive", "Hello World", "world", "World"},
{"no match", "hello world", "foo", "hello world"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := highlight(tt.text, tt.query)
if !strings.Contains(result, tt.contains) {
t.Errorf("highlight(%q, %q) = %q, want to contain %q", tt.text, tt.query, result, tt.contains)
}
})
}
}
func TestParseConversationFile(t *testing.T) {
// Create a temp file with test conversation
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "test-session.jsonl")
content := `{"type":"user","cwd":"/test/project","message":{"content":"hello"},"timestamp":"2024-01-15T10:00:00Z"}
{"type":"assistant","message":{"content":"hi there"},"timestamp":"2024-01-15T10:01:00Z"}
{"type":"user","message":{"content":"goodbye"},"timestamp":"2024-01-15T10:02:00Z"}
`
if err := os.WriteFile(testFile, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
conv, err := parseConversationFile(testFile, time.Time{}, 0) // No cutoff, no size limit
if err != nil {
t.Fatalf("parseConversationFile failed: %v", err)
}
if conv == nil {
t.Fatal("parseConversationFile returned nil")
}
if conv.SessionID != "test-session" {
t.Errorf("SessionID = %q, want %q", conv.SessionID, "test-session")
}
if conv.Cwd != "/test/project" {
t.Errorf("Cwd = %q, want %q", conv.Cwd, "/test/project")
}
if len(conv.Messages) != 3 {
t.Errorf("len(Messages) = %d, want 3", len(conv.Messages))
}
if conv.FirstTimestamp != "2024-01-15T10:00:00Z" {
t.Errorf("FirstTimestamp = %q, want %q", conv.FirstTimestamp, "2024-01-15T10:00:00Z")
}
if conv.LastTimestamp != "2024-01-15T10:02:00Z" {
t.Errorf("LastTimestamp = %q, want %q", conv.LastTimestamp, "2024-01-15T10:02:00Z")
}
}
func TestParseConversationFileSkipsAgentFiles(t *testing.T) {
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "agent-test.jsonl")
content := `{"type":"user","message":{"content":"hello"},"timestamp":"2024-01-15T10:00:00Z"}`
if err := os.WriteFile(testFile, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
conv, err := parseConversationFile(testFile, time.Time{}, 0) // No cutoff, no size limit
if err != nil {
t.Fatalf("parseConversationFile failed: %v", err)
}
if conv != nil {
t.Error("parseConversationFile should return nil for agent- prefixed files")
}
}
func TestParseConversationFileEmptyMessages(t *testing.T) {
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "empty-session.jsonl")
content := `{"type":"summary","message":{"content":"summary only"}}`
if err := os.WriteFile(testFile, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
conv, err := parseConversationFile(testFile, time.Time{}, 0) // No cutoff, no size limit
if err != nil {
t.Fatalf("parseConversationFile failed: %v", err)
}
if conv != nil {
t.Error("parseConversationFile should return nil for files with no user/assistant messages")
}
}
func TestParseConversationFileSkipsOldFiles(t *testing.T) {
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "old-session.jsonl")
content := `{"type":"user","cwd":"/test","message":{"content":"hello"},"timestamp":"2024-01-15T10:00:00Z"}`
if err := os.WriteFile(testFile, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
// Set file mtime to 60 days ago
oldTime := time.Now().AddDate(0, 0, -60)
if err := os.Chtimes(testFile, oldTime, oldTime); err != nil {
t.Fatalf("failed to set file mtime: %v", err)
}
// Cutoff is 30 days ago - file should be skipped
cutoff := time.Now().AddDate(0, 0, -30)
conv, err := parseConversationFile(testFile, cutoff, 0)
if err != nil {
t.Fatalf("parseConversationFile failed: %v", err)
}
if conv != nil {
t.Error("parseConversationFile should return nil for files older than cutoff")
}
}
func TestParseConversationFileIncludesRecentFiles(t *testing.T) {
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "recent-session.jsonl")
content := `{"type":"user","cwd":"/test","message":{"content":"hello"},"timestamp":"2024-01-15T10:00:00Z"}`
if err := os.WriteFile(testFile, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
// File mtime is now (recent) - cutoff is 30 days ago
cutoff := time.Now().AddDate(0, 0, -30)
conv, err := parseConversationFile(testFile, cutoff, 0)
if err != nil {
t.Fatalf("parseConversationFile failed: %v", err)
}
if conv == nil {
t.Error("parseConversationFile should include files newer than cutoff")
}
}
func TestParseConversationFileSkipsLargeFiles(t *testing.T) {
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "large-session.jsonl")
content := `{"type":"user","cwd":"/test","message":{"content":"hello"},"timestamp":"2024-01-15T10:00:00Z"}`
if err := os.WriteFile(testFile, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
// maxSize of 10 bytes - file should be skipped
conv, err := parseConversationFile(testFile, time.Time{}, 10)
if err != nil {
t.Fatalf("parseConversationFile failed: %v", err)
}
if conv != nil {
t.Error("parseConversationFile should return nil for files larger than maxSize")
}
}
func TestGetTopic(t *testing.T) {
tests := []struct {
name string
conv Conversation
expected string
}{
{
name: "with user message",
conv: Conversation{
SessionID: "test-123",
Messages: []Message{
{Role: "user", Text: "Hello world"},
{Role: "assistant", Text: "Hi there"},
},
},
expected: "Hello world",
},
{
name: "no user message",
conv: Conversation{
SessionID: "test-456",
Messages: []Message{
{Role: "assistant", Text: "Hi there"},
},
},
expected: "test-456",
},
{
name: "empty messages",
conv: Conversation{
SessionID: "test-789",
Messages: []Message{},
},
expected: "test-789",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := getTopic(tt.conv)
if result != tt.expected {
t.Errorf("getTopic() = %q, want %q", result, tt.expected)
}
})
}
}
func TestDeleteConversation(t *testing.T) {
// Create a temp directory to simulate projects dir
tmpDir := t.TempDir()
// Override getProjectsDir for this test
origGetProjectsDir := getProjectsDir
defer func() {
// Can't actually override without refactoring, so just test the logic
}()
_ = origGetProjectsDir
// Create test conversations
conv1 := Conversation{
SessionID: "test-session-1",
Cwd: "/test/project1",
Messages: []Message{
{Role: "user", Text: "First message"},
},
}
conv2 := Conversation{
SessionID: "test-session-2",
Cwd: "/test/project2",
Messages: []Message{
{Role: "user", Text: "Second message"},
},
}
items := []listItem{
{conv: conv1, searchText: "test1"},
{conv: conv2, searchText: "test2"},
}
// Create model with test data
m := model{
items: items,
filtered: items,
cursor: 0,
deleteIndex: 0,
confirmDelete: true,
}
// Create a temporary file for the conversation
testFile := filepath.Join(tmpDir, conv1.SessionID+".jsonl")
content := `{"type":"user","cwd":"/test/project1","message":{"content":"First message"},"timestamp":"2024-01-15T10:00:00Z"}`
if err := os.WriteFile(testFile, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
// Note: We can't fully test deleteConversation without dependency injection
// but we can verify the file operations and state management logic separately
// Test file deletion
if err := os.Remove(testFile); err != nil {
t.Errorf("failed to remove file: %v", err)
}
// Verify file was deleted
if _, err := os.Stat(testFile); !os.IsNotExist(err) {
t.Error("file should be deleted but still exists")
}
// Test cursor adjustment logic
if m.cursor >= len(m.filtered) {
m.cursor = len(m.filtered) - 1
}
// Simulate deletion from filtered slice
m.filtered = append(m.filtered[:m.deleteIndex], m.filtered[m.deleteIndex+1:]...)
if len(m.filtered) != 1 {
t.Errorf("filtered should have 1 item after deletion, got %d", len(m.filtered))
}
if m.filtered[0].conv.SessionID != "test-session-2" {
t.Errorf("remaining conversation should be test-session-2, got %s", m.filtered[0].conv.SessionID)
}
}
func TestDeleteConversationInvalidIndex(t *testing.T) {
m := model{
items: []listItem{},
filtered: []listItem{},
deleteIndex: 10, // Invalid index
}
// Should not panic when index is out of bounds
m.deleteConversation()
// Verify error is set or state is unchanged
// (deleteConversation returns early for invalid index)
}
func TestDeleteConversationErrorHandling(t *testing.T) {
// Test deletion of non-existent file
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "nonexistent.jsonl")
// Try to delete non-existent file
err := os.Remove(testFile)
if err == nil {
t.Error("expected error when deleting non-existent file")
}
// Verify it's the right kind of error
if !os.IsNotExist(err) {
t.Errorf("expected IsNotExist error, got: %v", err)
}
}
func TestUpdateFilter(t *testing.T) {
items := []listItem{
{conv: Conversation{SessionID: "test-1"}, searchText: "hello world foo"},
{conv: Conversation{SessionID: "test-2"}, searchText: "goodbye world bar"},
{conv: Conversation{SessionID: "test-3"}, searchText: "hello bar baz"},
}
m := initialModel(items, "", nil)
// Test: empty query returns all items
m.textInput.SetValue("")
m.updateFilter()
if len(m.filtered) != 3 {
t.Errorf("empty query should return all items, got %d", len(m.filtered))
}
// Test: query matches subset
m.textInput.SetValue("hello")
m.updateFilter()
if len(m.filtered) != 2 {
t.Errorf("'hello' query should return 2 items, got %d", len(m.filtered))
}
// Test: case insensitive
m.textInput.SetValue("WORLD")
m.updateFilter()
if len(m.filtered) != 2 {
t.Errorf("'WORLD' query should return 2 items (case insensitive), got %d", len(m.filtered))
}
// Test: no matches
m.textInput.SetValue("xyz")
m.updateFilter()
if len(m.filtered) != 0 {
t.Errorf("'xyz' query should return 0 items, got %d", len(m.filtered))
}
// Test: cursor adjustment when filtered list shrinks
m.cursor = 2
m.textInput.SetValue("hello")
m.updateFilter()
if m.cursor >= len(m.filtered) {
t.Errorf("cursor should be adjusted to bounds, cursor=%d, filtered=%d", m.cursor, len(m.filtered))
}
}
func TestFormatListItem(t *testing.T) {
conv := Conversation{
SessionID: "test-123",
Cwd: "/home/user/very-long-project-name-that-exceeds-column-width",
LastTimestamp: "2024-01-15T10:30:00Z",
Messages: []Message{
{Role: "user", Text: "This is a very long first message that should be truncated to fit in the column"},
{Role: "assistant", Text: "Response"},
{Role: "user", Text: "Second message"},
},
}
item := listItem{conv: conv, searchText: ""}
m := initialModel([]listItem{item}, "", nil)
// Test selected formatting
result := m.formatListItem(item, true)
if !strings.Contains(result, "2024-01-15 10:30") {
t.Errorf("formatted item should contain timestamp")
}
if !strings.Contains(result, "3") { // message count
t.Errorf("formatted item should contain message count")
}
// Test non-selected formatting (has ANSI codes)
result = m.formatListItem(item, false)
if !strings.Contains(result, "\033[") {
t.Errorf("non-selected item should contain ANSI color codes")
}
// Test hit count with query
m.textInput.SetValue("message")
result = m.formatListItem(item, false)
// Should show 2 hits (both user messages contain "message")
if !strings.Contains(result, "2") {
t.Errorf("should show hit count when query matches")
}
}
func TestUpdateKeyboardNavigation(t *testing.T) {
items := []listItem{
{conv: Conversation{SessionID: "test-1"}, searchText: "first"},
{conv: Conversation{SessionID: "test-2"}, searchText: "second"},
{conv: Conversation{SessionID: "test-3"}, searchText: "third"},
}
m := initialModel(items, "", nil)
m.width = 100
m.height = 30
// Test down navigation
result, _ := m.Update(tea.KeyMsg{Type: tea.KeyDown})
m = result.(model)
if m.cursor != 1 {
t.Errorf("down key should move cursor to 1, got %d", m.cursor)
}
// Test up navigation
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyUp})
m = result.(model)
if m.cursor != 0 {
t.Errorf("up key should move cursor to 0, got %d", m.cursor)
}
// Test up at boundary (should stay at 0)
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyUp})
m = result.(model)
if m.cursor != 0 {
t.Errorf("up at boundary should stay at 0, got %d", m.cursor)
}
// Test down to end
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyDown})
m = result.(model)
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyDown})
m = result.(model)
if m.cursor != 2 {
t.Errorf("should be at last item, got %d", m.cursor)
}
// Test down at boundary (should stay at 2)
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyDown})
m = result.(model)
if m.cursor != 2 {
t.Errorf("down at boundary should stay at 2, got %d", m.cursor)
}
}
func TestUpdateDeleteConfirmation(t *testing.T) {
tmpDir := t.TempDir()
// Create a real conversation file for testing
sessionID := "delete-test-session"
testFile := filepath.Join(tmpDir, sessionID+".jsonl")
content := `{"type":"user","cwd":"/test","message":{"content":"test message"},"timestamp":"2024-01-15T10:00:00Z"}`
if err := os.WriteFile(testFile, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
// Override getProjectsDir temporarily
originalGetProjectsDir := getProjectsDir
defer func() {
// Can't easily override without refactoring, so we'll test the flow differently
_ = originalGetProjectsDir
}()
items := []listItem{
{
conv: Conversation{
SessionID: sessionID,
Cwd: "/test",
Messages: []Message{{Role: "user", Text: "test message"}},
},
searchText: "test",
},
{
conv: Conversation{
SessionID: "keep-this",
Cwd: "/test2",
Messages: []Message{{Role: "user", Text: "keep message"}},
},
searchText: "keep",
},
}
m := initialModel(items, "", nil)
m.width = 100
m.height = 30
// Trigger delete mode with Ctrl+D
result, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
m = result.(model)
if !m.confirmDelete {
t.Error("Ctrl+D should enter delete confirmation mode")
}
if m.deleteIndex != 0 {
t.Errorf("deleteIndex should be 0, got %d", m.deleteIndex)
}
// Test cancellation with 'n'
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'n'}})
m = result.(model)
if m.confirmDelete {
t.Error("'n' should exit delete confirmation mode")
}
// Test cancellation with Esc
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
m = result.(model)
if !m.confirmDelete {
t.Error("should be in delete confirmation mode")
}
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyEsc})
m = result.(model)
if m.confirmDelete {
t.Error("Esc should exit delete confirmation mode")
}
// Test that other keys are ignored in delete mode
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlD})
m = result.(model)
originalCursor := m.cursor
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyDown})
m = result.(model)
if m.cursor != originalCursor {
t.Error("arrow keys should be ignored in delete confirmation mode")
}
}
func TestUpdateCtrlU(t *testing.T) {
items := []listItem{
{conv: Conversation{SessionID: "test-1"}, searchText: "hello"},
}
m := initialModel(items, "initial query", nil)
// Verify initial query is set
if m.textInput.Value() != "initial query" {
t.Errorf("initial query should be set")
}
// Test Ctrl+U clears search
result, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlU})
m = result.(model)
if m.textInput.Value() != "" {
t.Errorf("Ctrl+U should clear search, got %q", m.textInput.Value())
}
}
func TestViewRendering(t *testing.T) {
items := []listItem{
{
conv: Conversation{
SessionID: "test-1",
Cwd: "/test/project",
LastTimestamp: "2024-01-15T10:00:00Z",
Messages: []Message{
{Role: "user", Text: "test message", Ts: "2024-01-15T10:00:00Z"},
},
},
searchText: "test",
},
}
m := initialModel(items, "", nil)
m.width = 120
m.height = 30
output := m.View()
// Check for key UI elements
if !strings.Contains(output, "ccs") {
t.Error("output should contain 'ccs' title")
}
if !strings.Contains(output, "type to search") {
t.Error("output should contain search prompt")
}
if !strings.Contains(output, "DATE") || !strings.Contains(output, "PROJECT") {
t.Error("output should contain column headers")
}
if !strings.Contains(output, "/test/project") {
t.Error("output should contain project path in preview")
}
// Test delete confirmation view
m.confirmDelete = true
m.deleteIndex = 0
output = m.View()
if !strings.Contains(output, "Delete conversation") {
t.Error("delete confirmation should be shown")
}
if !strings.Contains(output, "[y/N]") {
t.Error("delete confirmation should show [y/N] prompt")
}
// Test error message display
m.confirmDelete = false
m.errorMsg = "Test error message"
output = m.View()
if !strings.Contains(output, "Test error message") {
t.Error("error message should be displayed")
}
}
func TestInit(t *testing.T) {
m := initialModel([]listItem{}, "", nil)
cmd := m.Init()
if cmd == nil {
t.Error("Init should return a command")
}
}
func TestGetProjectsDir(t *testing.T) {
dir := getProjectsDir()
if !strings.Contains(dir, ".claude") || !strings.Contains(dir, "projects") {
t.Errorf("getProjectsDir should return path containing .claude/projects, got %s", dir)
}
}
func TestRenderPreview(t *testing.T) {
conv := Conversation{
SessionID: "test-123",
Cwd: "/test/project",
Messages: []Message{
{Role: "user", Text: "first message", Ts: "2024-01-15T10:00:00Z"},
{Role: "assistant", Text: "response", Ts: "2024-01-15T10:01:00Z"},
{Role: "user", Text: "second message with query term", Ts: "2024-01-15T10:02:00Z"},
},
}
item := listItem{conv: conv, searchText: "test"}
m := initialModel([]listItem{item}, "query", nil)
preview := m.renderPreview(item, 20)
// Check preview contains key elements
if !strings.Contains(preview, "Project:") {
t.Error("preview should contain 'Project:' header")
}
if !strings.Contains(preview, "Session:") {
t.Error("preview should contain 'Session:' header")
}
if !strings.Contains(preview, "/test/project") {
t.Error("preview should contain project path")
}
if !strings.Contains(preview, "test-123") {
t.Error("preview should contain session ID")
}
}
func TestUpdateMouseScroll(t *testing.T) {
items := []listItem{
{conv: Conversation{SessionID: "test-1"}, searchText: "first"},
{conv: Conversation{SessionID: "test-2"}, searchText: "second"},
{conv: Conversation{SessionID: "test-3"}, searchText: "third"},
}
m := initialModel(items, "", nil)
// Set window size first to initialize mouse tracking
result, _ := m.Update(tea.WindowSizeMsg{Width: 100, Height: 30})
m = result.(model)
// Mouse wheel up in list area (Y=5, which should be in list)
m.mouseInPreview = false // Explicitly set for test
result, _ = m.Update(tea.MouseMsg{Button: tea.MouseButtonWheelUp, Y: 5})
m = result.(model)
// Should not move cursor from 0
if m.cursor != 0 {
t.Errorf("wheel up at top should keep cursor at 0, got %d", m.cursor)
}
// Move to second item
result, _ = m.Update(tea.KeyMsg{Type: tea.KeyDown})
m = result.(model)
if m.cursor != 1 {
t.Errorf("should be at cursor 1, got %d", m.cursor)
}
// Mouse wheel down in list area should move cursor forward
m.mouseInPreview = false // Ensure we're scrolling list not preview
result, _ = m.Update(tea.MouseMsg{Button: tea.MouseButtonWheelDown, Y: 5})
m = result.(model)
if m.cursor != 2 {
t.Errorf("wheel down should move to cursor 2, got %d", m.cursor)
}
// Mouse wheel in preview area
m.previewScroll = 0
m.mouseInPreview = true
result, _ = m.Update(tea.MouseMsg{Button: tea.MouseButtonWheelDown, Y: 20})
m = result.(model)
if m.previewScroll != 3 {
t.Errorf("wheel down in preview should scroll preview, got %d", m.previewScroll)
}
}
func TestDeleteConversationFullFlow(t *testing.T) {
// Create temp directory that will act as projects dir
tmpDir := t.TempDir()
// Create test conversation files
session1 := "delete-me"
session2 := "keep-me"
file1 := filepath.Join(tmpDir, session1+".jsonl")
file2 := filepath.Join(tmpDir, session2+".jsonl")
content := `{"type":"user","cwd":"/test","message":{"content":"test"},"timestamp":"2024-01-15T10:00:00Z"}`
if err := os.WriteFile(file1, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
if err := os.WriteFile(file2, []byte(content), 0644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
// Save and override getProjectsDir
oldGetProjectsDir := getProjectsDir
getProjectsDir = func() string { return tmpDir }
defer func() { getProjectsDir = oldGetProjectsDir }()
// Create items
items := []listItem{
{
conv: Conversation{
SessionID: session1,
FilePath: file1,
Messages: []Message{{Role: "user", Text: "delete this"}},
},
searchText: "delete",
},
{
conv: Conversation{
SessionID: session2,
FilePath: file2,
Messages: []Message{{Role: "user", Text: "keep this"}},
},
searchText: "keep",
},
}
m := initialModel(items, "", nil)
// Verify initial state
if len(m.items) != 2 {
t.Fatalf("initial items should be 2, got %d", len(m.items))
}
if len(m.filtered) != 2 {
t.Fatalf("initial filtered should be 2, got %d", len(m.filtered))
}
m.deleteIndex = 0
m.confirmDelete = true
// Execute deletion (needs pointer receiver)
(&m).deleteConversation()
// Verify file was deleted
if _, err := os.Stat(file1); !os.IsNotExist(err) {
t.Error("file1 should be deleted")
}
// Verify second file still exists
if _, err := os.Stat(file2); err != nil {
t.Error("file2 should still exist")
}
// Verify filtered list was updated
if len(m.filtered) != 1 {
t.Errorf("filtered should have 1 item, got %d", len(m.filtered))
}
// Verify items list was updated
if len(m.items) != 1 {
t.Errorf("items should have 1 item, got %d", len(m.items))
}
// Verify remaining item is session2