-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
1524 lines (1340 loc) · 42.5 KB
/
Copy pathmain.go
File metadata and controls
1524 lines (1340 loc) · 42.5 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 (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"syscall"
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
var version = "dev"
// Message represents a conversation message
type Message struct {
Role string `json:"role"`
Text string `json:"text"`
Ts string `json:"ts"`
}
// Conversation represents a parsed conversation
type Conversation struct {
SessionID string `json:"session_id"`
Title string `json:"title"` // custom-title (user-set) or ai-title
IsCustomTitle bool `json:"is_custom_title"` // true only when Title came from a user-set custom-title
Cwd string `json:"cwd"`
FirstTimestamp string `json:"first_timestamp"`
LastTimestamp string `json:"last_timestamp"`
Messages []Message `json:"messages"`
FilePath string `json:"file_path"` // Full path to the .jsonl file
Size int64 `json:"size"` // .jsonl file size in bytes
}
// RawMessage represents the JSON structure in conversation files
type RawMessage struct {
Type string `json:"type"`
Cwd string `json:"cwd"`
Message struct {
Content json.RawMessage `json:"content"`
} `json:"message"`
Timestamp string `json:"timestamp"`
CustomTitle string `json:"customTitle"`
AiTitle string `json:"aiTitle"`
}
// TextContent for parsing content arrays
type TextContent struct {
Type string `json:"type"`
Text string `json:"text"`
}
// listItem holds display and search data for a conversation
type listItem struct {
conv Conversation
searchText string // All searchable content
searchLower string // searchText lowercased once, for case-insensitive filtering
}
// selectedStyle highlights the cursor row. The rest of the UI is rendered with
// raw ANSI escapes in View/formatListItem/renderPreview.
var selectedStyle = lipgloss.NewStyle().
Background(lipgloss.Color("62")).
Foreground(lipgloss.Color("230")).
Bold(true)
// model is the bubbletea application state
type model struct {
items []listItem
filtered []listItem
textInput textinput.Model
cursor int
previewScroll int
width int
height int
listHeight int // Calculated visible list height
selected *Conversation
quitting bool
claudeFlags []string
confirmDelete bool // Are we in delete confirmation mode?
deleteIndex int // Index of item to delete
confirmPrune bool // Are we in prune confirmation mode?
pruneIndex int // Index of item to prune
pruneSaved int64 // Bytes the pending prune would reclaim (measured on Ctrl+R)
errorMsg string // Show deletion/prune errors
preview *previewCache // memoised preview lines for the selected conversation
hits *hitCounter // memoised per-query hit counts, keyed by SessionID
lastFilterQuery string // lowercased query the current m.filtered was built from
}
// previewCache memoises buildPreviewLines for the selected conversation so the
// preview isn't rebuilt (scanning every message) on every frame. It lives behind
// a pointer so it survives the value-receiver copies of model that View makes.
type previewCache struct {
key string
lines []string
}
// hitCounter memoises HITS (messages containing the query) per conversation for
// the current query, so formatListItem doesn't rescan every visible row's
// messages on every frame. Pointer-held so it survives model value copies.
type hitCounter struct {
query string
byID map[string]int
}
// countHits is the number of a conversation's messages containing query.
func countHits(conv Conversation, query string) int {
queryLower := strings.ToLower(query)
n := 0
for _, msg := range conv.Messages {
if strings.Contains(strings.ToLower(msg.Text), queryLower) {
n++
}
}
return n
}
// hitCount returns the memoised hit count for item under the current query.
func (m model) hitCount(item listItem) int {
query := m.textInput.Value()
if query == "" {
return 0
}
if m.hits == nil { // model built without initialModel (e.g. tests)
return countHits(item.conv, query)
}
if m.hits.query != query {
m.hits.query = query
m.hits.byID = make(map[string]int)
}
id := item.conv.SessionID
if h, ok := m.hits.byID[id]; ok {
return h
}
h := countHits(item.conv, query)
m.hits.byID[id] = h
return h
}
func initialModel(items []listItem, filterQuery string, claudeFlags []string) model {
ti := textinput.New()
ti.Placeholder = "type to search..."
ti.Prompt = "> "
ti.Focus()
ti.SetValue(filterQuery)
ti.Width = 40
m := model{
items: items,
textInput: ti,
claudeFlags: claudeFlags,
preview: &previewCache{},
hits: &hitCounter{byID: make(map[string]int)},
}
m.updateFilter()
return m
}
// previewLines returns the preview lines for the selected conversation,
// rebuilding only when the selection or query changes. Keyed by SessionID (not
// cursor index) so it stays correct when the filtered list shifts.
func (m model) previewLines() []string {
if len(m.filtered) == 0 {
return nil
}
conv := m.filtered[m.cursor].conv
query := m.textInput.Value()
if m.preview == nil { // model built without initialModel (e.g. tests)
return buildPreviewLines(conv, query)
}
key := conv.SessionID + "\x00" + query
if m.preview.key != key {
m.preview.key = key
m.preview.lines = buildPreviewLines(conv, query)
}
return m.preview.lines
}
func (m *model) updateFilter() {
queryLower := strings.ToLower(m.textInput.Value())
if queryLower == "" {
// Make a copy to avoid sharing backing array with m.items
m.filtered = make([]listItem, len(m.items))
copy(m.filtered, m.items)
} else {
// Incremental narrowing: if the new query contains the previous one, every
// item matching the new query already matched the old one, so filter the
// previous (smaller) result set instead of rescanning every conversation.
source := m.items
if m.lastFilterQuery != "" && strings.Contains(queryLower, m.lastFilterQuery) {
source = m.filtered
}
next := make([]listItem, 0, len(source))
for _, item := range source {
if strings.Contains(item.searchLower, queryLower) {
next = append(next, item)
}
}
m.filtered = next
}
m.lastFilterQuery = queryLower
// Keep cursor in bounds
if m.cursor >= len(m.filtered) {
m.cursor = max(0, len(m.filtered)-1)
}
m.previewScroll = 0
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
// Calculate visible list height
m.listHeight = m.height * 30 / 100
if m.listHeight < 3 {
m.listHeight = 3
}
// Clear so a shrink doesn't leave wider stale rows behind.
return m, tea.ClearScreen
case tea.KeyMsg:
// Handle delete confirmation mode
if m.confirmDelete {
switch msg.String() {
case "y", "Y":
m.deleteConversation()
return m, nil
case "n", "N", "esc":
m.confirmDelete = false
return m, nil
}
return m, nil // Ignore all other keys
}
// Handle prune confirmation mode
if m.confirmPrune {
switch msg.String() {
case "y", "Y":
m.pruneConversation()
return m, nil
case "n", "N", "esc":
m.confirmPrune = false
return m, nil
}
return m, nil // Ignore all other keys
}
// Clear error message on any keypress in normal mode
if m.errorMsg != "" {
m.errorMsg = ""
}
switch msg.String() {
case "ctrl+c", "esc":
m.quitting = true
return m, tea.Quit
case "enter":
if len(m.filtered) > 0 {
m.selected = &m.filtered[m.cursor].conv
}
m.quitting = true
return m, tea.Quit
case "ctrl+d":
if len(m.filtered) > 0 {
m.confirmDelete = true
m.deleteIndex = m.cursor
}
return m, nil
case "ctrl+r":
if len(m.filtered) > 0 {
// Measure the projected saving so the prompt can show it.
// ponytail: reads the file once now (and again on confirm) - a
// multi-GB file briefly blocks, acceptable for a manual action.
st, err := pruneFile(m.filtered[m.cursor].conv.FilePath, false, pruneOpts{dropSnapshots: true, stripToolResults: true})
if err != nil {
m.errorMsg = fmt.Sprintf("Prune preview failed: %v", err)
return m, nil
}
m.confirmPrune = true
m.pruneIndex = m.cursor
m.pruneSaved = st.bytesIn - st.bytesOut
}
return m, nil
case "up", "ctrl+p":
if m.cursor > 0 {
m.cursor--
m.previewScroll = 0
}
return m, nil
case "down", "ctrl+n":
if m.cursor < len(m.filtered)-1 {
m.cursor++
m.previewScroll = 0
}
return m, nil
case "pgup", "ctrl+k":
m.previewScroll = max(0, m.previewScroll-10)
return m, nil
case "pgdown", "ctrl+j":
m.previewScroll = min(m.previewScroll+10, m.maxPreviewScroll())
return m, nil
case "ctrl+u":
m.textInput.SetValue("")
m.updateFilter()
return m, nil
}
}
// Update text input
var cmd tea.Cmd
prevValue := m.textInput.Value()
m.textInput, cmd = m.textInput.Update(msg)
if m.textInput.Value() != prevValue {
m.updateFilter()
}
return m, cmd
}
func (m model) View() string {
if m.width == 0 || m.height == 0 {
return "Loading..."
}
var b strings.Builder
// The list spans the full terminal width; TOPIC flexes to fill it.
tableWidth := m.width
// Title line with help right-aligned
title := fmt.Sprintf("ccs · claude code search · %s", version)
help := "Resume:Enter Delete:Ctrl+D Prune:Ctrl+R Scroll:Ctrl+J/K Exit:Esc"
titlePadding := tableWidth - 2 - len(title) - len(help)
if titlePadding < 1 {
titlePadding = 1
}
b.WriteString(fmt.Sprintf(" \033[1;36mccs\033[0m \033[90m· claude code search · %s%s%s\033[0m\n",
version, strings.Repeat(" ", titlePadding), help))
// Search line or delete confirmation
var sections []string
var inputSection string
if m.confirmPrune {
conv := m.filtered[m.pruneIndex].conv
inputSection = lipgloss.NewStyle().
Foreground(lipgloss.Color("214")). // Amber
Render(fmt.Sprintf("Prune \"%s\"? %s -> %s, saves %s (keeps dialogue). [y/N]",
truncate(getTopic(conv), 32), formatBytes(conv.Size), formatBytes(conv.Size-m.pruneSaved), formatBytes(m.pruneSaved)))
sections = append(sections, " "+inputSection)
} else if m.confirmDelete {
topic := getTopic(m.filtered[m.deleteIndex].conv)
inputSection = lipgloss.NewStyle().
Foreground(lipgloss.Color("196")). // Red
Render(fmt.Sprintf("Delete conversation \"%s\"? [y/N]", truncate(topic, 50)))
sections = append(sections, " "+inputSection)
} else {
count := fmt.Sprintf("(%d/%d)", len(m.filtered), len(m.items))
searchPadding := tableWidth - 2 - 2 - 40 - len(count) - 1 // 2 for indent, 2 for "> ", 40 for textInput, -1 to shift left
if searchPadding < 1 {
searchPadding = 1
}
inputSection = fmt.Sprintf(" %s%s\033[90m%s\033[0m", m.textInput.View(), strings.Repeat(" ", searchPadding), count)
sections = append(sections, inputSection)
}
// Show error message if set
if m.errorMsg != "" {
errorStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("196"))
sections = append(sections, " "+errorStyle.Render(m.errorMsg))
}
b.WriteString(strings.Join(sections, "\n"))
b.WriteString("\n\n")
// Calculate heights
listHeight := m.height * 30 / 100
if listHeight < 3 {
listHeight = 3
}
previewHeight := m.height - listHeight - 6 // 6 for title + search + blank + header + borders
// Column headers
b.WriteString(fmt.Sprintf(" \033[90m%-*s %-*s %-*s %*s %*s %*s\033[0m\n",
colDate, "DATE", colProject, "PROJECT", m.topicColWidth(), "TOPIC", colMsgs, "MSGS", colHits, "HITS", colSize, "SIZE"))
b.WriteString(strings.Repeat("─", m.width))
b.WriteString("\n")
visibleItems := listHeight
start := 0
if m.cursor >= visibleItems {
start = m.cursor - visibleItems + 1
}
for i := start; i < min(start+visibleItems, len(m.filtered)); i++ {
item := m.filtered[i]
isSelected := i == m.cursor
line := m.formatListItem(item, isSelected)
if isSelected {
// Pad to full width for selection highlight
line = padRight("> "+line, m.width)
b.WriteString(selectedStyle.Render(line))
} else {
b.WriteString(" " + line)
}
b.WriteString("\n")
}
// Fill remaining list space
for i := len(m.filtered) - start; i < visibleItems; i++ {
b.WriteString("\n")
}
// Preview section
b.WriteString(strings.Repeat("─", m.width))
b.WriteString("\n")
if len(m.filtered) > 0 {
preview := m.renderPreview(m.filtered[m.cursor], previewHeight)
b.WriteString(preview)
}
return b.String()
}
// Fixed list column widths. TOPIC is the flex column - it absorbs the rest of
// the terminal width (see topicColWidth).
const (
colDate = 16
colProject = 22
colMsgs = 5
colHits = 4
colSize = 6
colGap = 2 // spaces between columns
listIndent = 2 // leading " " / "> " on each row
numGaps = 5
)
// topicColWidth flexes the TOPIC column to fill the terminal width.
func (m model) topicColWidth() int {
used := listIndent + colDate + colProject + colMsgs + colHits + colSize + numGaps*colGap
if w := m.width - used; w > 10 {
return w
}
return 10
}
func (m model) formatListItem(item listItem, selected bool) string {
ts := formatTimestamp(item.conv.LastTimestamp)
project := item.conv.Cwd
if idx := strings.LastIndex(project, "/"); idx >= 0 {
project = project[idx+1:]
}
project = truncate(project, colProject)
// Mark only user-set custom titles. Claude auto-generates an ai-title for
// almost every session, so marking any title would flag nearly every row;
// the ✎ should mean "you named this". ponytail: the glyph is ambiguous-width,
// so a marked row may sit one cell narrow on CJK-width terminals - cosmetic
// only, truncate is rune-safe.
topic := getTopic(item.conv)
if item.conv.IsCustomTitle {
topic = "✎ " + topic
}
tw := m.topicColWidth()
topic = truncate(topic, tw)
// Message count
msgs := len(item.conv.Messages)
// Number of messages containing the query (memoised per query).
hits := m.hitCount(item)
size := formatBytes(item.conv.Size)
// Format: date | project | topic | msgs | hits | size (aligned columns)
if selected {
return fmt.Sprintf("%-*s %-*s %-*s %*d %*d %*s",
colDate, ts, colProject, project, tw, topic, colMsgs, msgs, colHits, hits, colSize, size)
}
return fmt.Sprintf("\033[90m%-*s\033[0m \033[1;33m%-*s\033[0m %-*s %*d \033[36m%*d\033[0m \033[35m%*s\033[0m",
colDate, ts, colProject, project, tw, topic, colMsgs, msgs, colHits, hits, colSize, size)
}
// buildPreviewLines builds the scrollable message lines of a conversation
// preview (everything below the fixed header). Shared by renderPreview and
// maxPreviewScroll so the render and the scroll-clamp can never disagree on how
// far the preview can scroll.
func buildPreviewLines(conv Conversation, query string) []string {
var msgLines []string
// Find messages containing the query
queryLower := strings.ToLower(query)
matchSet := make(map[int]bool)
if query != "" {
for i, msg := range conv.Messages {
if strings.Contains(strings.ToLower(msg.Text), queryLower) {
matchSet[i] = true
}
}
}
// Build set of indices to show
showSet := make(map[int]bool)
// Always show first 2 and last 2 messages
for i := 0; i < 2 && i < len(conv.Messages); i++ {
showSet[i] = true
}
for i := len(conv.Messages) - 2; i < len(conv.Messages); i++ {
if i >= 0 {
showSet[i] = true
}
}
// Add matches with context
for idx := range matchSet {
if idx > 0 {
showSet[idx-1] = true
}
showSet[idx] = true
if idx < len(conv.Messages)-1 {
showSet[idx+1] = true
}
}
// Display messages with gaps
lastShown := -1
for i := 0; i < len(conv.Messages); i++ {
if !showSet[i] {
continue
}
if lastShown >= 0 && i > lastShown+1 {
skipped := i - lastShown - 1
msgLines = append(msgLines, fmt.Sprintf("\033[90m ... %d messages ...\033[0m", skipped))
msgLines = append(msgLines, "")
} else if lastShown == -1 && i > 0 {
msgLines = append(msgLines, fmt.Sprintf("\033[90m ... %d earlier messages\033[0m", i))
msgLines = append(msgLines, "")
}
msg := conv.Messages[i]
ts := formatTimestamp(msg.Ts)
var prefix string
if matchSet[i] {
if msg.Role == "user" {
prefix = fmt.Sprintf("\033[1;32m>>> %s User:\033[0m", ts) // Bold green
} else {
prefix = fmt.Sprintf("\033[1;34m>>> %s Claude:\033[0m", ts) // Bold blue
}
} else {
if msg.Role == "user" {
prefix = fmt.Sprintf("\033[32m %s User:\033[0m", ts) // Green
} else {
prefix = fmt.Sprintf("\033[34m %s Claude:\033[0m", ts) // Blue
}
}
msgLines = append(msgLines, prefix)
text := msg.Text
if r := []rune(text); len(r) > 500 {
text = string(r[:500]) + "... (truncated)" // slice on runes, not bytes
}
for _, line := range strings.Split(text, "\n") {
msgLines = append(msgLines, " "+highlight(line, query))
}
msgLines = append(msgLines, "")
lastShown = i
}
if lastShown < len(conv.Messages)-1 {
remaining := len(conv.Messages) - lastShown - 1
msgLines = append(msgLines, fmt.Sprintf("\033[90m ... %d more messages\033[0m", remaining))
}
return msgLines
}
// maxPreviewScroll is the furthest the preview of the current selection can
// scroll - one line short of the rendered message-line count.
func (m model) maxPreviewScroll() int {
if len(m.filtered) == 0 {
return 0
}
return max(0, len(m.previewLines())-1)
}
func (m model) renderPreview(item listItem, height int) string {
query := m.textInput.Value()
conv := item.conv
// Fixed header (always visible)
var header []string
header = append(header, "\033[1;33mProject:\033[0m "+highlight(conv.Cwd, query))
if conv.Title != "" {
header = append(header, "\033[1;33mName:\033[0m "+highlight(conv.Title, query))
}
header = append(header, "\033[1;33mSession:\033[0m "+highlight(conv.SessionID, query))
header = append(header, "")
msgLines := m.previewLines() // memoised; item is always the selected conversation
// Apply scroll to messages only (header stays fixed). Clamp locally for this
// render; the persisted m.previewScroll is bounded in Update via
// maxPreviewScroll (this method has a value receiver, so a write here would
// be discarded).
msgHeight := height - len(header)
if msgHeight < 1 {
msgHeight = 1
}
scroll := min(m.previewScroll, max(0, len(msgLines)-1))
end := min(scroll+msgHeight, len(msgLines))
visibleMsgLines := msgLines[scroll:end]
// Combine header + scrolled messages
allLines := append(header, visibleMsgLines...)
return strings.Join(allLines, "\n")
}
func highlight(text, query string) string {
if query == "" {
return text
}
tr := []rune(text)
lr := []rune(strings.ToLower(text))
queryLower := strings.ToLower(query)
qr := []rune(queryLower)
// Match on runes so multibyte text (CJK, emoji) is never sliced mid-rune.
// ponytail: a handful of runes change length when lowercased (İ, Kelvin K),
// which breaks the lr/tr index alignment - bail to plain text rather than
// emit corrupted bytes. Highlighting those is not worth the complexity.
if len(lr) != len(tr) || len(qr) == 0 {
return text
}
var result strings.Builder
for i := 0; i < len(tr); {
if i+len(qr) <= len(tr) && string(lr[i:i+len(qr)]) == queryLower {
// Yellow background, black text for highlight
result.WriteString("\033[43;30m")
result.WriteString(string(tr[i : i+len(qr)]))
result.WriteString("\033[0m")
i += len(qr)
} else {
result.WriteRune(tr[i])
i++
}
}
return result.String()
}
func padRight(s string, length int) string {
r := []rune(s)
if len(r) >= length {
return string(r[:length])
}
// ponytail: pads by rune count, not display width; CJK/emoji rows can still
// look a cell narrow. Swap in go-runewidth if column alignment matters.
return s + strings.Repeat(" ", length-len(r))
}
// ============================================================================
// Data loading (preserved from original)
// ============================================================================
// getProjectsDir returns the path to the Claude projects directory
// Declared as a variable so it can be overridden in tests
var getProjectsDir = func() string {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".claude", "projects")
}
func extractText(content json.RawMessage) string {
if len(content) == 0 {
return ""
}
var str string
if err := json.Unmarshal(content, &str); err == nil {
return str
}
var arr []TextContent
if err := json.Unmarshal(content, &arr); err == nil {
var parts []string
for _, item := range arr {
if item.Type == "text" && item.Text != "" {
parts = append(parts, item.Text)
}
}
return strings.Join(parts, " ")
}
return ""
}
func parseConversationFile(path string, cutoff time.Time, maxSize int64) (*Conversation, error) {
info, err := os.Stat(path)
if err != nil {
return nil, err
}
if strings.HasPrefix(info.Name(), "agent-") {
return nil, nil
}
// Skip files larger than maxSize (0 means no limit)
if maxSize > 0 && info.Size() > maxSize {
return nil, nil
}
// Skip files not modified since cutoff (file mtime check)
if !cutoff.IsZero() && info.ModTime().Before(cutoff) {
return nil, nil
}
sessionID := strings.TrimSuffix(info.Name(), ".jsonl")
conv := &Conversation{
SessionID: sessionID,
FilePath: path,
Size: info.Size(),
}
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
// A single JSONL line holds a whole turn - a big tool result or a base64
// image can be tens of MB. ponytail: 64MB ceiling; if a line ever exceeds
// it the scanner.Err() check below skips the file rather than silently
// truncating the parse.
scanner.Buffer(make([]byte, 1024*1024), 64*1024*1024)
for scanner.Scan() {
lineBytes := scanner.Bytes()
var raw RawMessage
if err := json.Unmarshal(lineBytes, &raw); err != nil {
continue
}
if raw.Type == "custom-title" {
conv.Title = raw.CustomTitle // user-set name wins over ai-title
conv.IsCustomTitle = raw.CustomTitle != ""
} else if raw.Type == "ai-title" {
if conv.Title == "" {
conv.Title = raw.AiTitle
}
} else if raw.Type == "user" {
if conv.Cwd == "" {
conv.Cwd = raw.Cwd
}
text := extractText(raw.Message.Content)
if strings.TrimSpace(text) != "" {
if conv.FirstTimestamp == "" {
conv.FirstTimestamp = raw.Timestamp
}
conv.Messages = append(conv.Messages, Message{
Role: "user",
Text: text,
Ts: raw.Timestamp,
})
}
} else if raw.Type == "assistant" {
text := extractText(raw.Message.Content)
if strings.TrimSpace(text) != "" {
conv.Messages = append(conv.Messages, Message{
Role: "assistant",
Text: text,
Ts: raw.Timestamp,
})
}
}
}
// A scan error (e.g. a line over the buffer cap) leaves the parse partial.
// Surface it instead of trusting a silently-truncated conversation.
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("reading %s: %w", path, err)
}
if len(conv.Messages) == 0 {
return nil, nil
}
conv.LastTimestamp = conv.Messages[len(conv.Messages)-1].Ts
if conv.Cwd == "" {
conv.Cwd = "unknown"
}
return conv, nil
}
func getConversations(cutoff time.Time, maxSize int64, excludeDirs []string) ([]Conversation, error) {
projectsDir := getProjectsDir()
var files []string
err := filepath.Walk(projectsDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if info.IsDir() && info.Name() == "subagents" {
return filepath.SkipDir
}
if info.IsDir() {
for _, exc := range excludeDirs {
if strings.Contains(info.Name(), exc) {
return filepath.SkipDir
}
}
}
if !info.IsDir() && strings.HasSuffix(path, ".jsonl") && !strings.HasPrefix(info.Name(), "agent-") {
files = append(files, path)
}
return nil
})
if err != nil {
return nil, err
}
// Worker pool to limit concurrent file operations
const numWorkers = 8
jobs := make(chan string, len(files))
results := make(chan *Conversation, len(files))
var wg sync.WaitGroup
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for path := range jobs {
conv, err := parseConversationFile(path, cutoff, maxSize)
if err == nil && conv != nil {
results <- conv
}
}
}()
}
for _, file := range files {
jobs <- file
}
close(jobs)
go func() {
wg.Wait()
close(results)
}()
var conversations []Conversation
for conv := range results {
conversations = append(conversations, *conv)
}
sort.Slice(conversations, func(i, j int) bool {
return conversations[i].LastTimestamp > conversations[j].LastTimestamp
})
return conversations, nil
}
func formatTimestamp(ts string) string {
if ts == "" {
return ""
}
t, err := time.Parse(time.RFC3339, ts)
if err != nil {
if len(ts) >= 16 {
return ts[:16]
}
return ts
}
return t.Local().Format("2006-01-02 15:04")
}
// formatBytes renders a byte count compactly (fits the 6-wide SIZE column).
func formatBytes(n int64) string {
switch {
case n >= 1<<30:
return fmt.Sprintf("%.1fGB", float64(n)/(1<<30))
case n >= 1<<20:
return fmt.Sprintf("%dMB", n/(1<<20))
case n >= 1<<10:
return fmt.Sprintf("%dKB", n/(1<<10))
default:
return fmt.Sprintf("%dB", n)
}
}
func truncate(s string, maxLen int) string {
s = strings.Join(strings.Fields(s), " ")
r := []rune(s)
if len(r) <= maxLen {
return s
}
if maxLen < 3 {
return string(r[:maxLen]) // no room for the ellipsis
}
return string(r[:maxLen-3]) + "..."
}
// getTopic returns the session name (custom/ai title), else first user message, else session ID
func getTopic(conv Conversation) string {
if conv.Title != "" {
return conv.Title
}
for _, msg := range conv.Messages {
if msg.Role == "user" {
return msg.Text
}
}
return conv.SessionID
}
// deleteConversation removes the selected conversation from disk and UI
func (m *model) deleteConversation() {
if m.deleteIndex >= len(m.filtered) {
return
}
conv := m.filtered[m.deleteIndex].conv
// Delete the file (ignore if already deleted)
if err := os.Remove(conv.FilePath); err != nil && !os.IsNotExist(err) {
m.errorMsg = fmt.Sprintf("Delete failed: %v", err)
m.confirmDelete = false
return
}
// Remove from filtered slice
m.filtered = append(m.filtered[:m.deleteIndex], m.filtered[m.deleteIndex+1:]...)
// Remove from items slice (find by SessionID)
for i, item := range m.items {
if item.conv.SessionID == conv.SessionID {
m.items = append(m.items[:i], m.items[i+1:]...)
break
}
}
// Adjust cursor
if len(m.filtered) == 0 {
m.cursor = 0
} else if m.cursor >= len(m.filtered) {
m.cursor = len(m.filtered) - 1
}
// Otherwise cursor stays at same position (shows next item)
// Exit confirmation mode
m.confirmDelete = false
m.errorMsg = ""
}
// pruneConversation prunes the selected conversation file in place and refreshes
// its displayed size. The conversation stays in the list (only shrunk).
// ponytail: synchronous - a multi-GB file briefly blocks the UI, same as delete.
func (m *model) pruneConversation() {
m.confirmPrune = false
if m.pruneIndex >= len(m.filtered) {
return
}
conv := m.filtered[m.pruneIndex].conv
st, err := pruneFile(conv.FilePath, true, pruneOpts{dropSnapshots: true, stripToolResults: true})
if err != nil {
m.errorMsg = fmt.Sprintf("Prune failed: %v", err)
return