search: support all result types (checkpoints, commits, sessions) and align with UI · Entire
Log in
search: support all result types (checkpoints, commits, sessions) and align with UI
5a1f93c→main·
evisdren·1mo ago·5 files·+1,247 added/-159 removed
Previously the CLI hardcoded `types=checkpoints` when calling the search API, so commits and sessions were never returned. This aligns the CLI with the UI by:
- Removing the `types=checkpoints` filter so the API returns all result types - Adding CommitResult and SessionResult types with custom JSON marshal/unmarshal - Adding polymorphic Result accessors (ResultOrg, ResultRepo, ResultTitle, etc.) - Adding type filter tabs (0-3 keys) and Type column to the TUI - Adding commit and session detail views - Adding --all-repos flag (defaults to current repo scoping) - Aligning default limit to 100 (matching the UI, was 200) - Including API-provided type counts and timing metadata in responses
Co-Authored-By: Claude Opus 4.6 noreply@anthropic.com
Sessions
8c0d41c15f8eView transcript
?\ Debug Search CLI and UI Result DiscrepanciesClaude Code·Opus 4.6·3 steps
Changes
5
cmd/entire/cli
search
Msearch.go+303/-13
Msearch_test.go+201/-28
Msearch_cmd.go+24/-10
Msearch_tui.go+406/-69
Msearch_tui_test.go+313/-39
23 unmodified lines
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
32
33
34
42
43
44
45
46
47
48
49
50
51
1 unmodified line
53
54
55
56
57
58
59
4 unmodified lines
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
54
55
56
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
61
62
63
64
347
348
349
350
351
352
353
354
355
356
3 unmodified lines
360
361
362
363
364
365
366
167 unmodified lines
534
535
536
247
537
538
539
540
541
252
542
543
544
255
545
546
547
548
23 unmodified lines
// AllReposFilter is the inline repo filter value that disables repo scoping.
const AllReposFilter = "*"
// Result type constants.
const (
TypeCheckpoint = "checkpoint"
TypeCommit = "commit"
TypeSession = "session"
)
// MaxLimit is the maximum number of results the search API will return per request.
const MaxLimit = 200
// DefaultLimit is the default number of results to fetch per request, matching the UI.
const DefaultLimit = 100
// Meta contains search ranking metadata for a result.
type Meta struct {
MatchType string `json:"matchType"`
Score float64 `json:"score"`
Snippet string `json:"snippet,omitempty"`
MatchType string `json:"matchType"`
Score float64 `json:"score"`
Tier *int `json:"tier,omitempty"`
Snippet string `json:"snippet,omitempty"`
Summary string `json:"summary,omitempty"`
BM25Score *float64 `json:"bm25Score,omitempty"`
ANNScore *float64 `json:"annScore,omitempty"`
}
// CheckpointResult represents a checkpoint returned by the search service.
1 unmodified line
ID string `json:"id"`
Prompt string `json:"prompt"`
CommitMessage *string `json:"commitMessage"`
CommitSubject *string `json:"commitSubject"`
CommitSHA *string `json:"commitSha"`
Branch string `json:"branch"`
Org string `json:"org"`
4 unmodified lines
FilesTouched []string `json:"filesTouched"`
}
// CommitResult represents a commit returned by the search service.
type CommitResult struct {
ID string `json:"id"`
CommitSHA string `json:"commitSha"`
CommitMessage string `json:"commitMessage"`
CommitSubject string `json:"commitSubject"`
Branch string `json:"branch"`
Org string `json:"org"`
Repo string `json:"repo"`
Author string `json:"author"`
AuthorUsername *string `json:"authorUsername"`
CreatedAt string `json:"createdAt"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
FilesChanged int `json:"filesChanged"`
HTMLUrl *string `json:"htmlUrl"`
}
// SessionResult represents a session returned by the search service.
type SessionResult struct {
SessionID string `json:"sessionId"`
DisplayName string `json:"displayName"`
Prompt *string `json:"prompt"`
Agent *string `json:"agent"`
Model *string `json:"model"`
StepCount int `json:"stepCount"`
Org string `json:"org"`
Repo string `json:"repo"`
Branch *string `json:"branch"`
AuthorUsername *string `json:"authorUsername"`
CreatedAt string `json:"createdAt"`
}
// Result wraps a search result with its type and ranking metadata.
// Exactly one of Checkpoint, Commit, or Session is non-nil based on Type.
type Result struct {
Type string `json:"type"`
Data CheckpointResult `json:"data"`
Meta Meta `json:"searchMeta"`
Type string `json:"-"`
Meta Meta `json:"-"`
Checkpoint *CheckpointResult `json:"-"`
Commit *CommitResult `json:"-"`
Session *SessionResult `json:"-"`
// rawData preserves the original JSON for unknown types (repo, pr)
rawData json.RawMessage
}
// resultJSON is the wire format for JSON marshaling/unmarshaling.
type resultJSON struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
Meta Meta `json:"searchMeta"`
}
// MarshalJSON implements custom JSON marshaling to produce the API wire format.
func (r *Result) MarshalJSON() ([]byte, error) {
var data any
switch r.Type {
case TypeCheckpoint:
data = r.Checkpoint
case TypeCommit:
data = r.Commit
case TypeSession:
data = r.Session
default:
data = r.rawData
}
raw, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("marshaling result data: %w", err)
}
out, err := json.Marshal(resultJSON{
Type: r.Type,
Data: raw,
Meta: r.Meta,
})
if err != nil {
return nil, fmt.Errorf("marshaling result: %w", err)
}
return out, nil
}
// UnmarshalJSON implements custom JSON unmarshaling to parse typed data.
func (r *Result) UnmarshalJSON(b []byte) error {
var raw resultJSON
if err := json.Unmarshal(b, &raw); err != nil {
return fmt.Errorf("unmarshaling result: %w", err)
}
r.Type = raw.Type
r.Meta = raw.Meta
r.rawData = raw.Data
switch raw.Type {
case TypeCheckpoint:
var d CheckpointResult
if err := json.Unmarshal(raw.Data, &d); err != nil {
return fmt.Errorf("unmarshaling checkpoint data: %w", err)
}
r.Checkpoint = &d
case TypeCommit:
var d CommitResult
if err := json.Unmarshal(raw.Data, &d); err != nil {
return fmt.Errorf("unmarshaling commit data: %w", err)
}
r.Commit = &d
case TypeSession:
var d SessionResult
if err := json.Unmarshal(raw.Data, &d); err != nil {
return fmt.Errorf("unmarshaling session data: %w", err)
}
r.Session = &d
}
return nil
}
// ResultOrg returns the org for any result type.
func (r *Result) ResultOrg() string {
switch r.Type {
case TypeCheckpoint:
if r.Checkpoint != nil {
return r.Checkpoint.Org
}
case TypeCommit:
if r.Commit != nil {
return r.Commit.Org
}
case TypeSession:
if r.Session != nil {
return r.Session.Org
}
}
return ""
}
// ResultRepo returns the repo for any result type.
func (r *Result) ResultRepo() string {
switch r.Type {
case TypeCheckpoint:
if r.Checkpoint != nil {
return r.Checkpoint.Repo
}
case TypeCommit:
if r.Commit != nil {
return r.Commit.Repo
}
case TypeSession:
if r.Session != nil {
return r.Session.Repo
}
}
return ""
}
// ResultBranch returns the branch for any result type.
func (r *Result) ResultBranch() string {
switch r.Type {
case TypeCheckpoint:
if r.Checkpoint != nil {
return r.Checkpoint.Branch
}
case TypeCommit:
if r.Commit != nil {
return r.Commit.Branch
}
case TypeSession:
if r.Session != nil && r.Session.Branch != nil {
return *r.Session.Branch
}
}
return ""
}
// ResultCreatedAt returns the createdAt for any result type.
func (r *Result) ResultCreatedAt() string {
switch r.Type {
case TypeCheckpoint:
if r.Checkpoint != nil {
return r.Checkpoint.CreatedAt
}
case TypeCommit:
if r.Commit != nil {
return r.Commit.CreatedAt
}
case TypeSession:
if r.Session != nil {
return r.Session.CreatedAt
}
}
return ""
}
// ResultAuthor returns the display author for any result type.
func (r *Result) ResultAuthor() string {
switch r.Type {
case TypeCheckpoint:
if r.Checkpoint != nil {
if r.Checkpoint.AuthorUsername != nil && *r.Checkpoint.AuthorUsername != "" {
return *r.Checkpoint.AuthorUsername
}
return r.Checkpoint.Author
}
case TypeCommit:
if r.Commit != nil {
if r.Commit.AuthorUsername != nil && *r.Commit.AuthorUsername != "" {
return *r.Commit.AuthorUsername
}
return r.Commit.Author
}
case TypeSession:
if r.Session != nil {
if r.Session.AuthorUsername != nil {
return *r.Session.AuthorUsername
}
}
}
return ""
}
// ResultID returns the primary ID for any result type.
func (r *Result) ResultID() string {
switch r.Type {
case TypeCheckpoint:
if r.Checkpoint != nil {
return r.Checkpoint.ID
}
case TypeCommit:
if r.Commit != nil {
return r.Commit.CommitSHA
}
case TypeSession:
if r.Session != nil {
return r.Session.SessionID
}
}
return ""
}
// ResultTitle returns the primary display text for any result type.
func (r *Result) ResultTitle() string {
switch r.Type {
case TypeCheckpoint:
if r.Checkpoint != nil {
return r.Checkpoint.Prompt
}
case TypeCommit:
if r.Commit != nil {
if r.Commit.CommitSubject != "" {
return r.Commit.CommitSubject
}
return r.Commit.CommitMessage
}
case TypeSession:
if r.Session != nil {
return r.Session.DisplayName
}
}
return ""
}
// TypeCounts holds per-type result counts.
type TypeCounts struct {
Repos int `json:"repos"`
Checkpoints int `json:"checkpoints"`
Commits int `json:"commits"`
PRs int `json:"prs"`
Sessions int `json:"sessions"`
}
// Timing holds search performance timing data.
type Timing struct {
TotalMs *float64 `json:"total_ms"`
KeywordMs *float64 `json:"keyword_ms"`
EmbeddingMs *float64 `json:"embedding_ms"`
VectorMs *float64 `json:"vector_ms"`
RerankMs *float64 `json:"rerank_ms"`
FanoutMs *float64 `json:"fanout_ms"`
SessionHydrationMs *float64 `json:"session_hydration_ms"`
}
// Response is the search service response.
type Response struct {
Results []Result `json:"results"`
Total int `json:"total"`
Page int `json:"page"`
Error string `json:"error,omitempty"`
Results []Result `json:"results"`
Total int `json:"total"`
Page int `json:"page"`
Error string `json:"error,omitempty"`
Timing *Timing `json:"timing,omitempty"`
Reranked *bool `json:"reranked,omitempty"`
Counts *TypeCounts `json:"counts,omitempty"`
}
// Config holds the configuration for a search request.
3 unmodified lines
Owner string
Repo string
Repos []string
AllRepos bool // When true, search all accessible repos (no repo scoping)
Query string
Limit int
Author string // Filter by author name
167 unmodified lines
if err := ValidateRepoFilters(cfg.Repos); err != nil {
return nil, err
}
allRepos := len(cfg.Repos) == 1 && cfg.Repos[0] == AllReposFilter
allRepos := cfg.AllRepos || (len(cfg.Repos) == 1 && cfg.Repos[0] == AllReposFilter)
if len(cfg.Repos) > 0 && !allRepos {
for _, repo := range cfg.Repos {
q.Add("repo", repo)
}
} else if len(cfg.Repos) == 0 && cfg.Owner != "" && cfg.Repo != "" {
} else if !allRepos && cfg.Owner != "" && cfg.Repo != "" {
q.Set("repo", cfg.Owner+"/"+cfg.Repo)
}
q.Set("types", "checkpoints")
// Don't set types — let the API return all types (checkpoints, commits, sessions, etc.)
if cfg.Limit > 0 {
q.Set("limit", strconv.Itoa(cfg.Limit))
}
Mcmd/entire/cli/search/search.go+303/-13
10 unmodified lines
11
12
13
14
15
16
17
18
19
20
21
22
23
116 unmodified lines
140
141
142
136
137
143
144
145
146
147
148
160 unmodified lines
309
310
311
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
312
313
314
315
10 unmodified lines
326
327
328
342
343
329
330
331
332
345
346
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
116 unmodified lines
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
10 unmodified lines
const testOwner = "entirehq"
const testRepo = "entire.io"
const testCPID = "cp1"
// writeTestJSON writes raw JSON to a response writer, ignoring write errors (test helper).
func writeTestJSON(w http.ResponseWriter, jsonStr string) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(jsonStr)) //nolint:errcheck // test helper
}
// -- ParseGitHubRemote tests --
116 unmodified lines
if capturedReq.URL.Query().Get("repo") != "myowner/myrepo" {
t.Errorf("repo = %s, want 'myowner/myrepo'", capturedReq.URL.Query().Get("repo"))
}
if capturedReq.URL.Query().Get("types") != "checkpoints" {
t.Errorf("types = %s, want 'checkpoints'", capturedReq.URL.Query().Get("types"))
// types param should NOT be set — the CLI now requests all types
if capturedReq.URL.Query().Has("types") {
t.Errorf("types param should not be set, got %q", capturedReq.URL.Query().Get("types"))
}
if capturedReq.URL.Query().Get("limit") != "10" {
t.Errorf("limit = %s, want '10'", capturedReq.URL.Query().Get("limit"))
160 unmodified lines
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
resp := Response{
Results: []Result{
{
Type: "checkpoint",
Data: CheckpointResult{
ID: "abc123def456",
Branch: "main",
Prompt: "add auth middleware",
Author: "alice",
CreatedAt: "2026-01-13T12:00:00Z",
},
Meta: Meta{
Score: 0.042,
MatchType: "both",
},
},
},
Total: 1,
Page: 1,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp) //nolint:errcheck // test helper response
writeTestJSON(w, `{"results":[{"type":"checkpoint","data":{"id":"abc123def456","branch":"main","prompt":"add auth middleware","author":"alice","createdAt":"2026-01-13T12:00:00Z","org":"","repo":"","filesTouched":[]},"searchMeta":{"score":0.042,"matchType":"both"}}],"total":1,"page":1}`)
}))
defer srv.Close()
10 unmodified lines
if len(resp.Results) != 1 {
t.Fatalf("got %d results, want 1", len(resp.Results))
}
if resp.Results[0].Data.ID != "abc123def456" {
t.Errorf("checkpoint id = %s, want abc123def456", resp.Results[0].Data.ID)
r := resp.Results[0]
if r.Type != TypeCheckpoint {
t.Errorf("type = %s, want checkpoint", r.Type)
}
if resp.Results[0].Meta.MatchType != "both" {
t.Errorf("matchType = %s, want both", resp.Results[0].Meta.MatchType)
if r.Checkpoint == nil {
t.Fatal("checkpoint data is nil")
}
if r.Checkpoint.ID != "abc123def456" {
t.Errorf("checkpoint id = %s, want abc123def456", r.Checkpoint.ID)
}
if r.Meta.MatchType != "both" {
t.Errorf("matchType = %s, want both", r.Meta.MatchType)
}
}
func TestSearch_SuccessWithMultipleTypes(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
writeTestJSON(w, `{"results":[{"type":"checkpoint","data":{"id":"cp1","prompt":"fix bug","branch":"main","org":"o","repo":"r","author":"alice","createdAt":"2026-01-13T12:00:00Z","filesTouched":[]},"searchMeta":{"matchType":"keyword","score":0.5}},{"type":"commit","data":{"id":"cm1","commitSha":"abc1234567890","commitMessage":"fix: auth bug","commitSubject":"fix: auth bug","branch":"main","org":"o","repo":"r","author":"bob","createdAt":"2026-01-14T12:00:00Z","additions":10,"deletions":5,"filesChanged":3},"searchMeta":{"matchType":"semantic","score":0.3}},{"type":"session","data":{"sessionId":"ss1","displayName":"Debug auth","org":"o","repo":"r","createdAt":"2026-01-15T12:00:00Z","stepCount":5},"searchMeta":{"matchType":"both","score":0.4}}],"total":3,"page":1,"counts":{"repos":0,"checkpoints":1,"commits":1,"prs":0,"sessions":1}}`)
}))
defer srv.Close()
resp, err := Search(context.Background(), Config{
ServiceURL: srv.URL,
GitHubToken: "tok",
Owner: "o",
Repo: "r",
Query: "auth",
})
if err != nil {
t.Fatal(err)
}
if len(resp.Results) != 3 {
t.Fatalf("got %d results, want 3", len(resp.Results))
}
// Checkpoint
if resp.Results[0].Checkpoint == nil {
t.Fatal("result[0] checkpoint is nil")
}
if resp.Results[0].Checkpoint.ID != testCPID {
t.Errorf("checkpoint ID = %q", resp.Results[0].Checkpoint.ID)
}
// Commit
if resp.Results[1].Commit == nil {
t.Fatal("result[1] commit is nil")
}
if resp.Results[1].Commit.CommitSHA != "abc1234567890" {
t.Errorf("commit SHA = %q", resp.Results[1].Commit.CommitSHA)
}
if resp.Results[1].Commit.Additions != 10 {
t.Errorf("commit additions = %d", resp.Results[1].Commit.Additions)
}
// Session
if resp.Results[2].Session == nil {
t.Fatal("result[2] session is nil")
}
if resp.Results[2].Session.SessionID != "ss1" {
t.Errorf("session ID = %q", resp.Results[2].Session.SessionID)
}
if resp.Results[2].Session.StepCount != 5 {
t.Errorf("session steps = %d", resp.Results[2].Session.StepCount)
}
// Counts
if resp.Counts == nil {
t.Fatal("counts is nil")
}
if resp.Counts.Checkpoints != 1 || resp.Counts.Commits != 1 || resp.Counts.Sessions != 1 {
t.Errorf("counts = %+v", resp.Counts)
}
}
func TestSearch_ResultAccessors(t *testing.T) {
t.Parallel()
cp := Result{
Type: TypeCheckpoint,
Checkpoint: &CheckpointResult{ID: testCPID, Org: "o", Repo: "r", Branch: "main", Author: "alice", CreatedAt: "2026-01-01T00:00:00Z", Prompt: "fix bug"},
}
if cp.ResultOrg() != "o" {
t.Errorf("ResultOrg = %q", cp.ResultOrg())
}
if cp.ResultTitle() != "fix bug" {
t.Errorf("ResultTitle = %q", cp.ResultTitle())
}
if cp.ResultID() != testCPID {
t.Errorf("ResultID = %q", cp.ResultID())
}
cm := Result{
Type: TypeCommit,
Commit: &CommitResult{CommitSHA: "abc123", CommitSubject: "fix: bug", Org: "o", Repo: "r", Branch: "dev", Author: "bob"},
}
if cm.ResultTitle() != "fix: bug" {
t.Errorf("commit ResultTitle = %q", cm.ResultTitle())
}
if cm.ResultID() != "abc123" {
t.Errorf("commit ResultID = %q", cm.ResultID())
}
ss := Result{
Type: TypeSession,
Session: &SessionResult{SessionID: "ss1", DisplayName: "Debug session", Org: "o", Repo: "r"},
}
if ss.ResultTitle() != "Debug session" {
t.Errorf("session ResultTitle = %q", ss.ResultTitle())
}
if ss.ResultID() != "ss1" {
t.Errorf("session ResultID = %q", ss.ResultID())
}
}
func TestSearch_ResultJSONRoundTrip(t *testing.T) {
t.Parallel()
original := Result{
Type: TypeCheckpoint,
Checkpoint: &CheckpointResult{
ID: testCPID,
Prompt: "fix bug",
Branch: "main",
Org: "o",
Repo: "r",
Author: "alice",
CreatedAt: "2026-01-01T00:00:00Z",
},
Meta: Meta{MatchType: "keyword", Score: 0.5},
}
data, err := json.Marshal(&original)
if err != nil {
t.Fatal(err)
}
// Verify wire format has "type", "data", "searchMeta" keys
if !strings.Contains(string(data), `"type":"checkpoint"`) {
t.Errorf("JSON missing type: %s", data)
}
if !strings.Contains(string(data), `"data":{`) {
t.Errorf("JSON missing data: %s", data)
}
if !strings.Contains(string(data), `"searchMeta":{`) {
t.Errorf("JSON missing searchMeta: %s", data)
}
// Round-trip
var decoded Result
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatal(err)
}
if decoded.Type != TypeCheckpoint {
t.Errorf("decoded type = %q", decoded.Type)
}
if decoded.Checkpoint == nil || decoded.Checkpoint.ID != testCPID {
t.Errorf("decoded checkpoint = %+v", decoded.Checkpoint)
}
if decoded.Meta.Score != 0.5 {
t.Errorf("decoded score = %f", decoded.Meta.Score)
}
}
116 unmodified lines
}
}
func TestSearch_AllReposFlagOmitsRepoParam(t *testing.T) {
t.Parallel()
var capturedReq *http.Request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedReq = r
resp := Response{Results: []Result{}, Total: 0, Page: 1}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp) //nolint:errcheck // test helper response
}))
defer srv.Close()
_, err := Search(context.Background(), Config{
ServiceURL: srv.URL,
GitHubToken: "tok",
Owner: "default-owner",
Repo: "default-repo",
Query: "q",
AllRepos: true,
})
if err != nil {
t.Fatal(err)
}
if got := capturedReq.URL.Query()["repo"]; len(got) != 0 {
t.Errorf("repo params = %v, want omitted for AllRepos=true", got)
}
}
func TestSearch_MultipleExplicitReposRejected(t *testing.T) {
t.Parallel()
Mcmd/entire/cli/search/search_test.go+201/-28
17 unmodified lines
18
19
20
21
21
22
23
24
2 unmodified lines
27
28
29
30
31
32
33
34
35
35
36
36
37
38
39
40
41
42
43
44
45
46
47
25 unmodified lines
73
74
75
76
77
78
79
80
81
82
83
84
46 unmodified lines
131
132
133
134
135
136
137
9 unmodified lines
147
148
149
139
150
151
152
153
10 unmodified lines
164
165
166
156
167
168
169
170
35 unmodified lines
206
207
208
209
210
211
212
79 unmodified lines
292
293
294
283
284
285
286
287
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
17 unmodified lines
"github.com/spf13/cobra"
)
func newSearchCmd() *cobra.Command {
func newSearchCmd() *cobra.Command { //nolint:maintidx // command wiring is inherently complex
var (
jsonOutput bool
limitFlag int
2 unmodified lines
dateFlag string
branchFlag string
repoFlag string
allReposFlag bool
insecureHTTPAuth bool
)
cmd := &cobra.Command{
Use: "search [query]",
Short: "Search checkpoints using semantic and keyword matching",
Long: `Search checkpoints using hybrid search (semantic + keyword),
Short: "Search checkpoints, commits, and sessions using semantic and keyword matching",
Long: `Search checkpoints, commits, and sessions using hybrid search (semantic + keyword),
powered by the Entire search service.
Requires authentication via 'entire login' (GitHub device flow).
By default, results are scoped to the current repository. Use --all-repos to
search across all accessible repos.
Run without arguments to open an interactive search. Results are
displayed in an interactive table. Use --json for machine-readable output.
25 unmodified lines
return fmt.Errorf("validating repo filter: %w", err)
}
// Check for repo:* in inline filters
allRepos := allReposFlag
if len(repos) == 1 && repos[0] == search.AllReposFilter {
allRepos = true
}
w := cmd.OutOrStdout()
isTerminal := interactive.IsTerminalWriter(w)
hasFilters := authorFlag != "" || dateFlag != "" || branchFlag != "" || len(repos) > 0
46 unmodified lines
Owner: owner,
Repo: repoName,
Repos: repos,
AllRepos: allRepos,
Query: query,
Limit: limitFlag,
Page: pageFlag,
9 unmodified lines
// No query provided + interactive = open TUI with search bar focused
if query == "" && !searchCfg.HasFilters() {
searchCfg.Limit = search.MaxLimit
searchCfg.Limit = search.DefaultLimit
styles := newStatusStyles(w)
model := newSearchModel(nil, "", 0, searchCfg, styles)
model.mode = modeSearch
10 unmodified lines
// the maximum and paginate client-side for all output modes.
requestedLimit := searchCfg.Limit
requestedPage := searchCfg.Page
searchCfg.Limit = search.MaxLimit
searchCfg.Limit = search.DefaultLimit
searchCfg.Page = 0 // let API default to page 1
resp, err := search.Search(ctx, searchCfg)
35 unmodified lines
cmd.Flags().StringVar(&dateFlag, "date", "", "Filter by time period (week or month)")
cmd.Flags().StringVar(&branchFlag, "branch", "", "Filter by branch name")
cmd.Flags().StringVar(&repoFlag, "repo", "", "Filter by repository (owner/name or *)")
cmd.Flags().BoolVar(&allReposFlag, "all-repos", false, "Search all accessible repos instead of just the current one")
addInsecureHTTPAuthFlag(cmd, &insecureHTTPAuth)
cmd.RegisterFlagCompletionFunc("date", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { //nolint:errcheck,gosec // only fails if the flag isn't defined; defined directly above
79 unmodified lines
}
out := struct {
Results []search.Result `json:"results"`
Total int `json:"total"`
Page int `json:"page"`
TotalPages int `json:"total_pages"`
Limit int `json:"limit"`
Results []search.Result `json:"results"`
Total int `json:"total"`
Page int `json:"page"`
TotalPages int `json:"total_pages"`
Limit int `json:"limit"`
Counts *search.TypeCounts `json:"counts,omitempty"`
}{
Results: pageResults,
Total: total,
Page: page,
TotalPages: totalPages,
Limit: limit,
Counts: resp.Counts,
}
data, err := jsonutil.MarshalIndentWithNewline(out, "", " ")
if err != nil {
Mcmd/entire/cli/search_cmd.go+24/-10
3 unmodified lines
4
5
6
7
8
9
10
23 unmodified lines
34
35
36
37
38
39
40
16 unmodified lines
57
58
59
60
61
62
63
64
20 unmodified lines
85
86
87
88
89
90
91
92
6 unmodified lines
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
10 unmodified lines
125
126
127
112
113
128
129
130
131
132
133
134
1 unmodified line
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
124
157
158
159
160
128
129
161
162
163
131
164
165
166
134
167
168
136
169
170
171
172
173
174
175
176
177
139
178
179
180
181
5 unmodified lines
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
56 unmodified lines
270
271
272
273
274
275
276
86 unmodified lines
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
14 unmodified lines
415
416
417
325
326
418
419
420
421
422
423
8 unmodified lines
432
433
434
341
435
436
437
438
51 unmodified lines
490
491
492
399
493
494
495
496
51 unmodified lines
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
19 unmodified lines
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
23 unmodified lines
639
640
641
516
642
643
644
645
646
647
521
648
649
650
651
15 unmodified lines
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
544
545
546
685
686
687
688
689
548
690
691
550
551
692
693
694
553
554
695
696
556
697
698
699
559
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
562
724
725
565
726
727
728
729
9 unmodified lines
739
740
741
581
742
743
744
745
746
587
747
748
749
750
10 unmodified lines
761
762
763
764
765
766
767
768
769
770
606
607
771
772
773
774
775
2 unmodified lines
778
779
780
616
617
618
619
620
621
781
782
783
784
785
786
787
788
624
789
790
791
792
10 unmodified lines
803
804
805
641
806
807
808
809
810
811
812
648
813
814
815
816
1 unmodified line
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
76 unmodified lines
1064
1065
1066
738
1067
1068
1069
740
1070
1071
1072
742
1073
1074
1075
1076
59 unmodified lines
1136
1137
1138
808
809
810
811
812
813
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
823
1156
1157
1158
826
1159
1160
1161
1162
8 unmodified lines
1171
1172
1173
841
842
843
844
845
846
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
122 unmodified lines
1306
1307
1308
975
1309
1310
1311
1312
979
1313
1314
1315
1316
1317
1318
984
1319
1320
1321
1322
1323
989
990
991
992
993
994
1324
1325
1326
1327
1328
1329
1330
1331
996
1332
1333
998
1334
1335
1336
1337
1338
1339
1003
1340
1341
1342
1343
3 unmodified lines
"context"
"fmt"
"io"
"strconv"
"strings"
"time"
23 unmodified lines
type searchResultsMsg struct {
results []search.Result
total int
counts *search.TypeCounts
err error
}
16 unmodified lines
helpSep lipgloss.Style // dim separator dots in footer
detailTitle lipgloss.Style // colored title and section headers (orange, bold)
detailBorder lipgloss.Style // border style for detail card
tabActive lipgloss.Style // active type tab
tabInactive lipgloss.Style // inactive type tab
}
// Search palette mirrors activity's dark-mode CSS variables (Tailwind 400-level).
20 unmodified lines
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color(searchAccentPurple)).
Padding(1, 2)
s.tabActive = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color(searchAccentOrange))
s.tabInactive = lipgloss.NewStyle().Foreground(lipgloss.Color("245"))
return s
}
6 unmodified lines
const resultsPerPage = 25
// typeFilter represents the active type tab in the TUI.
type typeFilter string
const (
typeFilterAll typeFilter = ""
typeFilterCheckpoints typeFilter = typeFilter(search.TypeCheckpoint)
typeFilterCommits typeFilter = typeFilter(search.TypeCommit)
typeFilterSessions typeFilter = typeFilter(search.TypeSession)
)
// searchModel is the bubbletea model for interactive search results.
type searchModel struct {
results []search.Result
10 unmodified lines
searchCfg search.Config
apiPage int // 1-based last-fetched API page
styles searchStyles
detailVP viewport.Model // full-screen detail view
browseVP viewport.Model // scrollable browse view
detailVP viewport.Model // full-screen detail view
browseVP viewport.Model // scrollable browse view
filterType typeFilter // active type tab filter
counts *search.TypeCounts // per-type counts from API
// darkBg is captured once before bubbletea takes over the terminal so the
// snippet renderer never re-queries the terminal via OSC during the Update
1 unmodified line
darkBg bool
}
// filteredResults returns results matching the active type filter.
func (m searchModel) filteredResults() []search.Result {
if m.filterType == typeFilterAll {
return m.results
}
var out []search.Result
for _, r := range m.results {
if typeFilter(r.Type) == m.filterType {
out = append(out, r)
}
}
return out
}
// pageResults returns the slice of results for the current page.
func (m searchModel) pageResults() []search.Result {
filtered := m.filteredResults()
start := m.page * resultsPerPage
if start >= len(m.results) {
if start >= len(filtered) {
return nil
}
end := start + resultsPerPage
if end > len(m.results) {
end = len(m.results)
if end > len(filtered) {
end = len(filtered)
}
return m.results[start:end]
return filtered[start:end]
}
// totalPages returns the number of pages based on the API's total result count.
// totalPages returns the number of pages based on the filtered result count.
func (m searchModel) totalPages() int {
if m.total == 0 {
n := len(m.filteredResults())
// When showing all types, use the API total if it's larger than loaded results
// (we may not have fetched everything yet).
if m.filterType == typeFilterAll && m.total > n {
n = m.total
}
if n == 0 {
return 1
}
return (m.total + resultsPerPage - 1) / resultsPerPage
return (n + resultsPerPage - 1) / resultsPerPage
}
// selectedResult returns the currently selected result, accounting for pagination.
5 unmodified lines
return nil
}
// computeTypeCounts calculates per-type counts from the loaded results,
// falling back to API-provided counts when available.
func (m searchModel) computeTypeCounts() (checkpoints, commits, sessions int) {
if m.counts != nil {
return m.counts.Checkpoints, m.counts.Commits, m.counts.Sessions
}
for _, r := range m.results {
switch typeFilter(r.Type) {
case typeFilterCheckpoints:
checkpoints++
case typeFilterCommits:
commits++
case typeFilterSessions:
sessions++
case typeFilterAll:
// not a valid result type; skip
}
}
return
}
func newSearchModel(results []search.Result, query string, total int, cfg search.Config, ss statusStyles) searchModel {
styles := newSearchStyles(ss)
56 unmodified lines
m.searchErr = ""
m.results = msg.results
m.total = msg.total
m.counts = msg.counts
m.apiPage = 1
m.cursor = 0
m.page = 0
86 unmodified lines
}
func (m searchModel) updateBrowseMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
// Type tab keys (1/2/3)
switch msg.String() {
case "1":
m.filterType = typeFilterCheckpoints
m.cursor = 0
m.page = 0
m.browseVP.GotoTop()
m = m.refreshBrowseContent()
return m, nil
case "2":
m.filterType = typeFilterSessions
m.cursor = 0
m.page = 0
m.browseVP.GotoTop()
m = m.refreshBrowseContent()
return m, nil
case "3":
m.filterType = typeFilterCommits
m.cursor = 0
m.page = 0
m.browseVP.GotoTop()
m = m.refreshBrowseContent()
return m, nil
case "0":
m.filterType = typeFilterAll
m.cursor = 0
m.page = 0
m.browseVP.GotoTop()
m = m.refreshBrowseContent()
return m, nil
}
pageLen := len(m.pageResults())
switch {
case key.Matches(msg, keys.Quit), key.Matches(msg, keys.Back), msg.String() == "h":
14 unmodified lines
m = m.refreshBrowseContent()
m.browseVP.GotoTop()
case key.Matches(msg, keys.End):
if len(m.results) > 0 {
lastLoaded := len(m.results) - 1
filtered := m.filteredResults()
if len(filtered) > 0 {
lastLoaded := len(filtered) - 1
m.page = min(lastLoaded/resultsPerPage, m.totalPages()-1)
if pageLen := len(m.pageResults()); pageLen > 0 {
m.cursor = pageLen - 1
8 unmodified lines
m.browseVP.GotoTop()
// Fetch next API page if we've scrolled past loaded results
start := m.page * resultsPerPage
if start >= len(m.results) && !m.fetchingMore {
if start >= len(m.filteredResults()) && !m.fetchingMore {
m.fetchingMore = true
m = m.refreshBrowseContent()
return m, fetchMoreResults(m.searchCfg, m.apiPage+1)
51 unmodified lines
if err != nil {
return searchResultsMsg{err: err}
}
return searchResultsMsg{results: resp.Results, total: resp.Total}
return searchResultsMsg{results: resp.Results, total: resp.Total, counts: resp.Counts}
}
}
51 unmodified lines
return b.String()
}
// viewTypeTabs renders the type filter tabs with counts.
func (m searchModel) viewTypeTabs() string {
cpCount, cmCount, ssCount := m.computeTypeCounts()
allCount := cpCount + cmCount + ssCount
renderTab := func(label string, filter typeFilter, count int, keyHint string) string {
text := fmt.Sprintf("[%s] %s %d", keyHint, label, count)
if m.filterType == filter {
return m.styles.render(m.styles.tabActive, text)
}
return m.styles.render(m.styles.tabInactive, text)
}
tabs := []string{
renderTab("All", typeFilterAll, allCount, "0"),
renderTab("Checkpoints", typeFilterCheckpoints, cpCount, "1"),
renderTab("Sessions", typeFilterSessions, ssCount, "2"),
renderTab("Commits", typeFilterCommits, cmCount, "3"),
}
return strings.Join(tabs, " ")
}
// renderBrowseContent builds the scrollable content for browse mode (everything except the footer).
func (m searchModel) renderBrowseContent() string {
var b strings.Builder
19 unmodified lines
return b.String()
}
// Type tabs
b.WriteString(pad + m.viewTypeTabs())
b.WriteString("\n\n")
// Section: RESULTS
b.WriteString(pad + m.styles.render(m.styles.sectionTitle, "RESULTS"))
b.WriteString("\n\n")
// Table (current page only)
filtered := m.filteredResults()
if len(filtered) == 0 {
b.WriteString(pad + m.styles.render(m.styles.dim, "No results for this type."))
return b.String()
}
if m.fetchingMore && m.pageResults() == nil {
b.WriteString(pad + m.styles.render(m.styles.dim, "Loading more results...") + "\n")
} else {
23 unmodified lines
var b strings.Builder
// Column headers
hdr := fmt.Sprintf("%-*s %-*s %-*s %-*s %-*s %-*s",
hdr := fmt.Sprintf("%-*s %-*s %-*s %-*s %-*s %-*s %-*s",
cols.typeCol, "Type",
cols.age, "Age",
cols.id, "ID",
cols.branch, "Branch",
cols.repo, "Repo",
cols.prompt, "Prompt",
cols.prompt, "Title",
cols.author, "Author",
)
b.WriteString(pad + m.styles.render(m.styles.dim, hdr) + "\n")
15 unmodified lines
return b.String()
}
// typeLabel returns a short type badge for display in the table.
func typeLabel(resultType string) string {
switch resultType {
case search.TypeCheckpoint:
return "CP"
case search.TypeCommit:
return "CM"
case search.TypeSession:
return "SS"
default:
return strings.ToUpper(resultType[:min(2, len(resultType))])
}
}
func (m searchModel) viewRow(r search.Result, cols columnLayout) string {
age := fmt.Sprintf("%-*s", cols.age, stringutil.TruncateRunes(formatSearchAge(r.Data.CreatedAt), cols.age, ""))
id := fmt.Sprintf("%-*s", cols.id, stringutil.TruncateRunes(r.Data.ID, cols.id-1, "…"))
branch := fmt.Sprintf("%-*s", cols.branch, stringutil.TruncateRunes(r.Data.Branch, cols.branch-1, "…"))
typeBadge := fmt.Sprintf("%-*s", cols.typeCol, typeLabel(r.Type))
age := fmt.Sprintf("%-*s", cols.age, stringutil.TruncateRunes(formatSearchAge(r.ResultCreatedAt()), cols.age, ""))
id := fmt.Sprintf("%-*s", cols.id, stringutil.TruncateRunes(formatResultID(r), cols.id-1, "…"))
branch := fmt.Sprintf("%-*s", cols.branch, stringutil.TruncateRunes(r.ResultBranch(), cols.branch-1, "…"))
repo := fmt.Sprintf("%-*s", cols.repo, stringutil.TruncateRunes(
r.Data.Org+"/"+r.Data.Repo, cols.repo-1, "…",
r.ResultOrg()+"/"+r.ResultRepo(), cols.repo-1, "…",
))
prompt := fmt.Sprintf("%-*s", cols.prompt, stringutil.TruncateRunes(
stringutil.CollapseWhitespace(r.Data.Prompt), cols.prompt-1, "…",
title := fmt.Sprintf("%-*s", cols.prompt, stringutil.TruncateRunes(
stringutil.CollapseWhitespace(r.ResultTitle()), cols.prompt-1, "…",
))
authorName := derefStr(r.Data.AuthorUsername, r.Data.Author)
author := fmt.Sprintf("%-*s", cols.author, stringutil.TruncateRunes(authorName, cols.author-1, "…"))
author := fmt.Sprintf("%-*s", cols.author, stringutil.TruncateRunes(r.ResultAuthor(), cols.author-1, "…"))
return fmt.Sprintf("%s %s %s %s %s %s", age, id, branch, repo, prompt, author)
return fmt.Sprintf("%s %s %s %s %s %s %s", typeBadge, age, id, branch, repo, title, author)
}
// renderDetailContent builds the text content for a checkpoint detail (no border/card chrome).
// formatResultID returns a display-friendly ID for a result.
func formatResultID(r search.Result) string {
if r.Type == search.TypeCommit && r.Commit != nil && len(r.Commit.CommitSHA) > 7 {
return r.Commit.CommitSHA[:7]
}
return r.ResultID()
}
// renderDetailContent builds the text content for a result detail (no border/card chrome).
func (m searchModel) renderDetailContent(r search.Result, contentWidth int, showSections bool) string {
switch r.Type {
case search.TypeCheckpoint:
return m.renderCheckpointDetail(r, contentWidth, showSections)
case search.TypeCommit:
return m.renderCommitDetail(r, contentWidth, showSections)
case search.TypeSession:
return m.renderSessionDetail(r, contentWidth, showSections)
default:
return m.renderCheckpointDetail(r, contentWidth, showSections)
}
}
func (m searchModel) renderCheckpointDetail(r search.Result, contentWidth int, showSections bool) string {
const labelWidth = 12
// Available width for field values: content width minus label minus space.
valueWidth := contentWidth - labelWidth - 1
if valueWidth < 20 {
valueWidth = 0 // disable wrapping on very narrow terminals
valueWidth = 0
}
var content strings.Builder
9 unmodified lines
content.WriteString(formatLabel(label) + " " + value + "\n")
}
// writeWrappedField word-wraps a long value, indenting continuation lines to align with the value column.
writeWrappedField := func(label, value string) {
if valueWidth == 0 || len(value) <= valueWidth {
writeField(label, value)
return
}
indent := strings.Repeat(" ", labelWidth+1) // align with value column
indent := strings.Repeat(" ", labelWidth+1)
wrapped := wrapText(value, valueWidth)
lines := strings.Split(wrapped, "\n")
content.WriteString(formatLabel(label) + " " + lines[0] + "\n")
10 unmodified lines
}
}
cp := r.Checkpoint
if cp == nil {
return content.String()
}
// ── OVERVIEW ──
writeSection("OVERVIEW")
writeField("ID", r.Data.ID)
writeWrappedField("Prompt", stringutil.CollapseWhitespace(r.Data.Prompt))
writeField("ID", cp.ID)
writeWrappedField("Prompt", stringutil.CollapseWhitespace(cp.Prompt))
matchType := r.Meta.MatchType
if r.Meta.Score > 0 {
matchType += " " + m.styles.render(m.styles.dim, fmt.Sprintf("(score: %.3f)", r.Meta.Score))
2 unmodified lines
// ── SOURCE ──
writeSection("SOURCE")
writeWrappedField("Commit", formatCommit(r.Data.CommitSHA, r.Data.CommitMessage))
writeField("Branch", r.Data.Branch)
writeField("Repo", r.Data.Org+"/"+r.Data.Repo)
authorStr := r.Data.Author
if r.Data.AuthorUsername != nil && *r.Data.AuthorUsername != "" {
authorStr = *r.Data.AuthorUsername + " " + m.styles.render(m.styles.dim, "("+r.Data.Author+")")
writeWrappedField("Commit", formatCommit(cp.CommitSHA, cp.CommitMessage))
writeField("Branch", cp.Branch)
writeField("Repo", cp.Org+"/"+cp.Repo)
authorStr := cp.Author
if cp.AuthorUsername != nil && *cp.AuthorUsername != "" {
authorStr = *cp.AuthorUsername + " " + m.styles.render(m.styles.dim, "("+cp.Author+")")
}
writeField("Author", authorStr)
createdStr := formatDetailCreatedAt(r.Data.CreatedAt, m.styles)
createdStr := formatDetailCreatedAt(cp.CreatedAt, m.styles)
writeField("Created", createdStr)
// ── SNIPPET ──
10 unmodified lines
}
// ── FILES ──
if len(r.Data.FilesTouched) > 0 {
if len(cp.FilesTouched) > 0 {
content.WriteString("\n")
if showSections {
content.WriteString(m.styles.render(m.styles.detailTitle, "FILES") + "\n")
} else {
content.WriteString(m.styles.render(m.styles.label, "Files:") + "\n")
}
for _, f := range r.Data.FilesTouched {
for _, f := range cp.FilesTouched {
content.WriteString(" " + f + "\n")
}
}
1 unmodified line
return strings.TrimRight(content.String(), "\n")
}
func (m searchModel) renderCommitDetail(r search.Result, contentWidth int, showSections bool) string {
const labelWidth = 12
valueWidth := contentWidth - labelWidth - 1
if valueWidth < 20 {
valueWidth = 0
}
var content strings.Builder
content.WriteString(m.styles.render(m.styles.detailTitle, "Commit Detail"))
content.WriteString("\n")
formatLabel := func(label string) string {
return m.styles.render(m.styles.label, fmt.Sprintf("%-*s", labelWidth, label+":"))
}
writeField := func(label, value string) {
content.WriteString(formatLabel(label) + " " + value + "\n")
}
writeWrappedField := func(label, value string) {
if valueWidth == 0 || len(value) <= valueWidth {
writeField(label, value)
return
}
indent := strings.Repeat(" ", labelWidth+1)
wrapped := wrapText(value, valueWidth)
lines := strings.Split(wrapped, "\n")
content.WriteString(formatLabel(label) + " " + lines[0] + "\n")
for _, line := range lines[1:] {
content.WriteString(indent + line + "\n")
}
}
writeSection := func(title string) {
if showSections {
content.WriteString("\n" + m.styles.render(m.styles.detailTitle, title) + "\n")
} else {
content.WriteString("\n")
}
}
cm := r.Commit
if cm == nil {
return content.String()
}
writeSection("OVERVIEW")
sha := cm.CommitSHA
if len(sha) > 7 {
sha = sha[:7]
}
writeField("SHA", sha)
writeWrappedField("Subject", cm.CommitSubject)
if cm.CommitMessage != cm.CommitSubject {
writeWrappedField("Message", stringutil.CollapseWhitespace(cm.CommitMessage))
}
matchType := r.Meta.MatchType
if r.Meta.Score > 0 {
matchType += " " + m.styles.render(m.styles.dim, fmt.Sprintf("(score: %.3f)", r.Meta.Score))
}
writeField("Match", matchType)
writeSection("SOURCE")
writeField("Branch", cm.Branch)
writeField("Repo", cm.Org+"/"+cm.Repo)
authorStr := cm.Author
if cm.AuthorUsername != nil && *cm.AuthorUsername != "" {
authorStr = *cm.AuthorUsername + " " + m.styles.render(m.styles.dim, "("+cm.Author+")")
}
writeField("Author", authorStr)
writeField("Created", formatDetailCreatedAt(cm.CreatedAt, m.styles))
writeSection("STATS")
writeField("Additions", fmt.Sprintf("+%d", cm.Additions))
writeField("Deletions", fmt.Sprintf("-%d", cm.Deletions))
writeField("Files", fmt.Sprintf("%d changed", cm.FilesChanged))
if cm.HTMLUrl != nil && *cm.HTMLUrl != "" {
writeField("URL", *cm.HTMLUrl)
}
return strings.TrimRight(content.String(), "\n")
}
func (m searchModel) renderSessionDetail(r search.Result, contentWidth int, showSections bool) string {
const labelWidth = 12
valueWidth := contentWidth - labelWidth - 1
if valueWidth < 20 {
valueWidth = 0
}
var content strings.Builder
content.WriteString(m.styles.render(m.styles.detailTitle, "Session Detail"))
content.WriteString("\n")
formatLabel := func(label string) string {
return m.styles.render(m.styles.label, fmt.Sprintf("%-*s", labelWidth, label+":"))
}
writeField := func(label, value string) {
content.WriteString(formatLabel(label) + " " + value + "\n")
}
ss := r.Session
if ss == nil {
return content.String()
}
writeSection("OVERVIEW")
writeField("Session ID", ss.SessionID)
writeWrappedField("Name", ss.DisplayName)
if ss.Prompt != nil && *ss.Prompt != "" {
writeWrappedField("Prompt", stringutil.CollapseWhitespace(*ss.Prompt))
}
if ss.Agent != nil && *ss.Agent != "" {
writeField("Agent", *ss.Agent)
}
if ss.Model != nil && *ss.Model != "" {
writeField("Model", *ss.Model)
}
writeField("Steps", strconv.Itoa(ss.StepCount))
matchType := r.Meta.MatchType
if r.Meta.Score > 0 {
matchType += " " + m.styles.render(m.styles.dim, fmt.Sprintf("(score: %.3f)", r.Meta.Score))
}
writeField("Match", matchType)
writeSection("SOURCE")
writeField("Repo", ss.Org+"/"+ss.Repo)
if ss.Branch != nil && *ss.Branch != "" {
writeField("Branch", *ss.Branch)
}
if ss.AuthorUsername != nil && *ss.AuthorUsername != "" {
writeField("Author", *ss.AuthorUsername)
}
writeField("Created", formatDetailCreatedAt(ss.CreatedAt, m.styles))
return strings.TrimRight(content.String(), "\n")
}
// formatDetailCreatedAt renders date (default) + relative time (dim) for the detail view.
func formatDetailCreatedAt(createdAt string, styles searchStyles) string {
t, err := time.Parse(time.RFC3339, createdAt)
76 unmodified lines
if pages > 1 {
left += dot + m.styles.helpItem("n/p", "page")
}
left += dot + m.styles.helpItem(keys.Quit.Help().Key, keys.Quit.Help().Desc)
left += dot + m.styles.helpItem("0-3", "type") + dot +
m.styles.helpItem(keys.Quit.Help().Key, keys.Quit.Help().Desc)
right := fmt.Sprintf("%d results", m.total)
filtered := m.filteredResults()
right := fmt.Sprintf("%d results", len(filtered))
if pages > 1 {
right = fmt.Sprintf("page %d/%d · %d results", m.page+1, pages, m.total)
right = fmt.Sprintf("page %d/%d · %d results", m.page+1, pages, len(filtered))
}
gap := m.width - lipgloss.Width(left) - lipgloss.Width(right) - 2
59 unmodified lines
// columnLayout holds computed column widths for the search results table.
type columnLayout struct {
age int
id int
branch int
repo int
prompt int
author int
typeCol int
age int
id int
branch int
repo int
prompt int
author int
}
// computeColumns calculates column widths from terminal width.
func computeColumns(width int) columnLayout {
const (
typeWidth = 5
ageWidth = 10
idWidth = 12
repoMin = 10
authorWidth = 14
gaps = 5 // spaces between columns
gaps = 6 // spaces between columns (one more than before for type col)
)
remaining := width - ageWidth - idWidth - authorWidth - gaps
remaining := width - typeWidth - ageWidth - idWidth - authorWidth - gaps
if remaining < 20 {
remaining = 20
}
8 unmodified lines
}
return columnLayout{
age: ageWidth,
id: idWidth,
branch: branchWidth,
repo: repoWidth,
prompt: promptWidth,
author: authorWidth,
typeCol: typeWidth,
age: ageWidth,
id: idWidth,
branch: branchWidth,
repo: repoWidth,
prompt: promptWidth,
author: authorWidth,
}
}
122 unmodified lines
// renderSearchStatic writes a non-interactive table for accessible mode.
func renderSearchStatic(w io.Writer, results []search.Result, query string, total int, styles statusStyles) {
fmt.Fprintf(w, "Found %d checkpoints matching %q\n\n", total, query)
fmt.Fprintf(w, "Found %d results matching %q\n\n", total, query)
cols := computeColumns(styles.width)
fmt.Fprintf(w, "%-*s %-*s %-*s %-*s %-*s %-*s\n",
fmt.Fprintf(w, "%-*s %-*s %-*s %-*s %-*s %-*s %-*s\n",
cols.typeCol, "TYPE",
cols.age, "AGE",
cols.id, "ID",
cols.branch, "BRANCH",
cols.repo, "REPO",
cols.prompt, "PROMPT",
cols.prompt, "TITLE",
cols.author, "AUTHOR",
)
for _, r := range results {
age := formatSearchAge(r.Data.CreatedAt)
id := stringutil.TruncateRunes(r.Data.ID, cols.id, "")
branch := stringutil.TruncateRunes(r.Data.Branch, cols.branch, "...")
repo := stringutil.TruncateRunes(r.Data.Org+"/"+r.Data.Repo, cols.repo, "...")
prompt := stringutil.TruncateRunes(
stringutil.CollapseWhitespace(r.Data.Prompt), cols.prompt, "...",
typeBadge := typeLabel(r.Type)
age := formatSearchAge(r.ResultCreatedAt())
id := stringutil.TruncateRunes(formatResultID(r), cols.id, "")
branch := stringutil.TruncateRunes(r.ResultBranch(), cols.branch, "...")
repo := stringutil.TruncateRunes(r.ResultOrg()+"/"+r.ResultRepo(), cols.repo, "...")
title := stringutil.TruncateRunes(
stringutil.CollapseWhitespace(r.ResultTitle()), cols.prompt, "...",
)
author := stringutil.TruncateRunes(derefStr(r.Data.AuthorUsername, r.Data.Author), cols.author, "...")
author := stringutil.TruncateRunes(r.ResultAuthor(), cols.author, "...")
fmt.Fprintf(w, "%-*s %-*s %-*s %-*s %-*s %-*s\n",
fmt.Fprintf(w, "%-*s %-*s %-*s %-*s %-*s %-*s %-*s\n",
cols.typeCol, typeBadge,
cols.age, age,
cols.id, id,
cols.branch, branch,
cols.repo, repo,
cols.prompt, prompt,
cols.prompt, title,
cols.author, author,
)
}
Mcmd/entire/cli/search_tui.go+406/-69
22 unmodified lines
23
24
25
26
26
27
28
29
14 unmodified lines
44
45
46
47
47
48
49
50
13 unmodified lines
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
1 unmodified line
108
109
110
111
112
113
114
115
116
117
118
119
120
121
62 unmodified lines
184
185
186
142
187
188
189
190
166 unmodified lines
357
358
359
315
360
361
362
363
364
365
321
366
367
368
369
370
371
372
373
374
27 unmodified lines
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
3 unmodified lines
562
563
564
565
566
567
568
23 unmodified lines
592
593
594
393
595
596
597
598
5 unmodified lines
604
605
606
607
608
609
610
187 unmodified lines
798
799
800
598
801
802
803
804
4 unmodified lines
809
810
811
609
812
813
814
815
9 unmodified lines
825
826
827
625
626
828
829
830
831
832
629
630
833
834
835
836
837
838
839
633
840
841
635
636
842
843
844
638
639
845
846
847
641
642
848
849
850
851
852
32 unmodified lines
885
886
887
681
888
889
890
891
892
893
894
895
896
897
687
898
899
900
690
691
692
693
901
902
695
696
903
904
905
906
907
908
909
910
911
912
913
914
2 unmodified lines
917
918
919
705
920
921
922
923
924
925
926
927
1 unmodified line
929
930
931
932
933
934
935
936
937
13 unmodified lines
951
952
953
732
954
955
956
957
958
959
960
961
21 unmodified lines
983
984
985
760
986
987
988
989
42 unmodified lines
1032
1033
1034
809
810
1035
1036
1037
1038
1039
3 unmodified lines
1043
1044
1045
820
821
1046
1047
1048
1049
1050
11 unmodified lines
1062
1063
1064
839
1065
1066
1067
1068
81 unmodified lines
1150
1151
1152
927
1153
1154
1155
1156
1157
1158
1159
1160
14 unmodified lines
1175
1176
1177
948
1178
1179
1180
1181
1182
1183
1184
1185
16 unmodified lines
1202
1203
1204
971
1205
1206
1207
1208
1209
1210
1211
1212
171 unmodified lines
1384
1385
1386
1149
1387
1388
1389
1390
1391
1392
1393
15 unmodified lines
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
22 unmodified lines
return []search.Result{
{
Type: "checkpoint",
Data: search.CheckpointResult{
Checkpoint: &search.CheckpointResult{
ID: "a3b2c4d5e6f7",
Prompt: "add auth middleware to protect API routes",
CommitSHA: &sha1,
14 unmodified lines
},
{
Type: "checkpoint",
Data: search.CheckpointResult{
Checkpoint: &search.CheckpointResult{
ID: "d5e6f789ab01",
Prompt: "fix auth token refresh",
CommitSHA: &sha2,
13 unmodified lines
}
}
func testMultiTypeResults() []search.Result {
results := testResults()
results = append(results,
search.Result{
Type: "commit",
Commit: &search.CommitResult{
ID: "cm1",
CommitSHA: "abc1234567890",
CommitMessage: "fix: auth token validation",
CommitSubject: "fix: auth token validation",
Branch: "main",
Org: "entirehq",
Repo: "entire.io",
Author: "carol",
CreatedAt: "2026-03-22T09:00:00Z",
Additions: 15,
Deletions: 3,
FilesChanged: 2,
},
Meta: search.Meta{MatchType: "keyword", Score: 0.4},
},
search.Result{
Type: "session",
Session: &search.SessionResult{
SessionID: "ss1",
DisplayName: "Debug auth flow",
Org: "entirehq",
Repo: "entire.io",
CreatedAt: "2026-03-23T11:00:00Z",
StepCount: 8,
},
Meta: search.Meta{MatchType: "semantic", Score: 0.3},
},
)
return results
}
func testModel() searchModel {
ss := statusStyles{colorEnabled: false, width: 100}
cfg := search.Config{ServiceURL: "http://test", Owner: "o", Repo: "r", Limit: 20}
1 unmodified line
return initTestViewport(m)
}
func testMultiTypeModel() searchModel {
ss := statusStyles{colorEnabled: false, width: 120}
cfg := search.Config{ServiceURL: "http://test", Owner: "o", Repo: "r", Limit: 20}
results := testMultiTypeResults()
m := newSearchModel(results, "auth", len(results), cfg, ss)
return initTestViewport(m)
}
// initTestViewport sets a simulated terminal height and initializes the browse viewport for tests that call View().
func initTestViewport(m searchModel) searchModel {
m.height = 60
62 unmodified lines
results := make([]search.Result, 30)
for i := range results {
results[i] = search.Result{Data: search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
results[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
}
tests := []struct {
166 unmodified lines
}
// Column headers
for _, col := range []string{"Age", "ID", "Branch", "Repo", "Prompt", "Author"} {
for _, col := range []string{"Type", "Age", "ID", "Branch", "Repo", "Title", "Author"} {
if !strings.Contains(view, col) {
t.Errorf("view missing column header %q", col)
}
}
// Table data
// Table data - type badge
if !strings.Contains(view, "CP") {
t.Error("view missing checkpoint type badge")
}
// Table data - ID
if !strings.Contains(view, "a3b2c4d5e6f") {
t.Error("view missing first result ID")
}
27 unmodified lines
}
}
func TestSearchModel_ViewMultiTypes(t *testing.T) {
t.Parallel()
m := testMultiTypeModel()
view := m.View().Content
// Type badges
if !strings.Contains(view, "CP") {
t.Error("view missing CP type badge")
}
if !strings.Contains(view, "CM") {
t.Error("view missing CM type badge")
}
if !strings.Contains(view, "SS") {
t.Error("view missing SS type badge")
}
// Type tabs
if !strings.Contains(view, "Checkpoints") {
t.Error("view missing Checkpoints tab")
}
if !strings.Contains(view, "Sessions") {
t.Error("view missing Sessions tab")
}
if !strings.Contains(view, "Commits") {
t.Error("view missing Commits tab")
}
}
func TestSearchModel_TypeFilterKeys(t *testing.T) {
t.Parallel()
m := testMultiTypeModel()
// Press 1 → filter to checkpoints
m = updateModel(t, m, tea.KeyPressMsg{Code: '1', Text: "1"})
if m.filterType != typeFilterCheckpoints {
t.Errorf("after 1: filterType = %q, want %q", m.filterType, typeFilterCheckpoints)
}
if len(m.filteredResults()) != 2 {
t.Errorf("checkpoint filter: got %d results, want 2", len(m.filteredResults()))
}
// Press 2 → filter to sessions
m = updateModel(t, m, tea.KeyPressMsg{Code: '2', Text: "2"})
if m.filterType != typeFilterSessions {
t.Errorf("after 2: filterType = %q, want %q", m.filterType, typeFilterSessions)
}
if len(m.filteredResults()) != 1 {
t.Errorf("session filter: got %d results, want 1", len(m.filteredResults()))
}
// Press 3 → filter to commits
m = updateModel(t, m, tea.KeyPressMsg{Code: '3', Text: "3"})
if m.filterType != typeFilterCommits {
t.Errorf("after 3: filterType = %q, want %q", m.filterType, typeFilterCommits)
}
if len(m.filteredResults()) != 1 {
t.Errorf("commit filter: got %d results, want 1", len(m.filteredResults()))
}
// Press 0 → show all
m = updateModel(t, m, tea.KeyPressMsg{Code: '0', Text: "0"})
if m.filterType != typeFilterAll {
t.Errorf("after 0: filterType = %q, want %q", m.filterType, typeFilterAll)
}
if len(m.filteredResults()) != 4 {
t.Errorf("all filter: got %d results, want 4", len(m.filteredResults()))
}
}
func TestSearchModel_TypeFilterResetsCursorAndPage(t *testing.T) {
t.Parallel()
m := testMultiTypeModel()
m.cursor = 2
m.page = 1
m = updateModel(t, m, tea.KeyPressMsg{Code: '1', Text: "1"})
if m.cursor != 0 {
t.Errorf("cursor should reset to 0 on type change, got %d", m.cursor)
}
if m.page != 0 {
t.Errorf("page should reset to 0 on type change, got %d", m.page)
}
}
func TestSearchModel_CommitDetail(t *testing.T) {
t.Parallel()
m := testMultiTypeModel()
// Filter to commits and check detail
m.filterType = typeFilterCommits
m.cursor = 0
m = m.refreshBrowseContent()
r := m.selectedResult()
if r == nil {
t.Fatal("no selected result")
}
if r.Type != "commit" {
t.Fatalf("selected result type = %q, want commit", r.Type)
}
content := m.renderDetailContent(*r, 80, true)
if !strings.Contains(content, "Commit Detail") {
t.Error("missing Commit Detail title")
}
if !strings.Contains(content, "abc1234") {
t.Error("missing truncated SHA")
}
if !strings.Contains(content, "fix: auth token validation") {
t.Error("missing commit subject")
}
if !strings.Contains(content, "+15") {
t.Error("missing additions")
}
if !strings.Contains(content, "-3") {
t.Error("missing deletions")
}
}
func TestSearchModel_SessionDetail(t *testing.T) {
t.Parallel()
m := testMultiTypeModel()
// Filter to sessions and check detail
m.filterType = typeFilterSessions
m.cursor = 0
m = m.refreshBrowseContent()
r := m.selectedResult()
if r == nil {
t.Fatal("no selected result")
}
if r.Type != "session" {
t.Fatalf("selected result type = %q, want session", r.Type)
}
content := m.renderDetailContent(*r, 80, true)
if !strings.Contains(content, "Session Detail") {
t.Error("missing Session Detail title")
}
if !strings.Contains(content, "ss1") {
t.Error("missing session ID")
}
if !strings.Contains(content, "Debug auth flow") {
t.Error("missing display name")
}
if !strings.Contains(content, "8") {
t.Error("missing step count")
}
}
func TestSearchModel_BrowseFooterHelp(t *testing.T) {
t.Parallel()
m := testModel()
3 unmodified lines
"/ search",
"↑/↓, j/k scroll",
"home/end, g/G top/bottom",
"0-3 type",
"q quit",
}
lastIndex := -1
23 unmodified lines
ss := statusStyles{colorEnabled: false, width: 120}
5 unmodified lines
"↑/↓, j/k scroll",
"home/end, g/G top/bottom",
"n/p page",
"0-3 type",
"q quit",
}
lastIndex := -1
187 unmodified lines
// Empty string username should fall back to display name
empty := ""
r.Data.AuthorUsername = &empty
r.Checkpoint.AuthorUsername = &empty
content = m.renderDetailContent(r, 80, false)
if !strings.Contains(content, "bob") {
t.Error("author should show display name when username is empty string")
4 unmodified lines
t.Parallel()
m := testModel()
r := testResults()[0]
r.Data.Prompt = "line one\nline two\nline three"
r.Checkpoint.Prompt = "line one\nline two\nline three"
content := m.renderDetailContent(r, 80, false)
// CollapseWhitespace should merge the newlines into spaces
9 unmodified lines
t.Parallel()
var buf bytes.Buffer
styles := statusStyles{colorEnabled: false, width: 100}
renderSearchStatic(&buf, testResults(), "auth", 2, styles)
styles := statusStyles{colorEnabled: false, width: 120}
results := testMultiTypeResults()
renderSearchStatic(&buf, results, "auth", len(results), styles)
output := buf.String()
if !strings.Contains(output, `Found 2 checkpoints matching "auth"`) {
t.Error("static output missing header")
if !strings.Contains(output, `Found 4 results matching "auth"`) {
t.Errorf("static output missing header, got:\n%s", output)
}
if !strings.Contains(output, "TYPE") {
t.Error("static output missing TYPE header")
}
if !strings.Contains(output, "REPO") {
t.Error("static output missing repo header")
t.Error("static output missing REPO header")
}
if !strings.Contains(output, "entire") {
t.Error("static output missing repo value")
if !strings.Contains(output, "CP") {
t.Error("static output missing CP badge")
}
if !strings.Contains(output, "a3b2c4d5e6") {
t.Error("static output missing first result ID")
if !strings.Contains(output, "CM") {
t.Error("static output missing CM badge")
}
if !strings.Contains(output, "d5e6f789ab") {
t.Error("static output missing second result ID")
if !strings.Contains(output, "SS") {
t.Error("static output missing SS badge")
}
}
32 unmodified lines
}
// 26 loaded results, total=26 → 2 pages
many := newSearchModel(make([]search.Result, 26), "q", 26, cfg, ss)
results := make([]search.Result, 26)
for i := range results {
results[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
}
many := newSearchModel(results, "q", 26, cfg, ss)
if got := many.totalPages(); got != 2 {
t.Errorf("totalPages() with total=26 = %d, want 2", got)
}
}
func TestSearchModel_TotalPagesUsesAPITotal(t *testing.T) {
func TestSearchModel_TotalPagesUsesFilteredCount(t *testing.T) {
t.Parallel()
// Only 20 results loaded but API reports total=100
ss := statusStyles{colorEnabled: false, width: 100}
cfg := search.Config{}
m := newSearchModel(make([]search.Result, 20), "q", 100, cfg, ss)
m := testMultiTypeModel()
if got := m.totalPages(); got != 4 {
t.Errorf("totalPages() with 20 loaded but total=100 = %d, want 4", got)
// Unfiltered: 4 results → 1 page
if got := m.totalPages(); got != 1 {
t.Errorf("unfiltered totalPages = %d, want 1", got)
}
// Filter to checkpoints: 2 results → 1 page
m.filterType = typeFilterCheckpoints
if got := m.totalPages(); got != 1 {
t.Errorf("checkpoint-filtered totalPages = %d, want 1", got)
}
}
2 unmodified lines
ss := statusStyles{colorEnabled: false, width: 100}
cfg := search.Config{}
m := newSearchModel(make([]search.Result, 25), "q", 50, cfg, ss)
results := make([]search.Result, 25)
for i := range results {
results[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
}
m := newSearchModel(results, "q", 50, cfg, ss)
if m.apiPage != 1 {
t.Fatalf("initial apiPage = %d, want 1", m.apiPage)
1 unmodified line
// Simulate receiving more results
newResults := make([]search.Result, 25)
for i := range newResults {
newResults[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("new-%02d", i)}}
}
m = updateModel(t, m, searchMoreResultsMsg{results: newResults})
if len(m.results) != 50 {
13 unmodified lines
// 25 loaded results, total=50 → 2 display pages but only 1 page loaded
ss := statusStyles{colorEnabled: false, width: 100}
cfg := search.Config{ServiceURL: "http://test", Owner: "o", Repo: "r", Limit: 25}
m := newSearchModel(make([]search.Result, 25), "q", 50, cfg, ss)
results := make([]search.Result, 25)
for i := range results {
results[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
}
m := newSearchModel(results, "q", 50, cfg, ss)
// Navigate to page 2 — should trigger fetch
updated, cmd := m.Update(tea.KeyPressMsg{Code: 'n', Text: "n"})
21 unmodified lines
cfg := search.Config{ServiceURL: "http://test", Owner: "o", Repo: "r", Limit: 25}
results := make([]search.Result, 50)
for i := range results {
results[i] = search.Result{Data: search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
results[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
}
m := newSearchModel(results, "q", 50, cfg, ss)
42 unmodified lines
t.Fatal("selectedResult() = nil, want first result")
return
}
if r.Data.ID != "a3b2c4d5e6f7" {
t.Errorf("selectedResult().Data.ID = %q, want %q", r.Data.ID, "a3b2c4d5e6f7")
if r.Checkpoint == nil || r.Checkpoint.ID != "a3b2c4d5e6f7" {
t.Errorf("selectedResult().Checkpoint.ID = %q, want %q", r.ResultID(), "a3b2c4d5e6f7")
}
// Move cursor to second result
3 unmodified lines
t.Fatal("selectedResult() at cursor 1 = nil")
return
}
if r.Data.ID != "d5e6f789ab01" {
t.Errorf("selectedResult().Data.ID = %q, want %q", r.Data.ID, "d5e6f789ab01")
if r.Checkpoint == nil || r.Checkpoint.ID != "d5e6f789ab01" {
t.Errorf("selectedResult().Checkpoint.ID = %q, want %q", r.ResultID(), "d5e6f789ab01")
}
// Out-of-range cursor returns nil
11 unmodified lines
cfg := search.Config{ServiceURL: "http://test", Owner: "o", Repo: "r"}
results := make([]search.Result, 30)
for i := range results {
results[i] = search.Result{Data: search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
results[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
}
m := newSearchModel(results, "q", 30, cfg, ss)
81 unmodified lines
ss := statusStyles{colorEnabled: false, width: 100}
cfg := search.Config{}
m := newSearchModel(make([]search.Result, 25), "q", 50, cfg, ss)
results := make([]search.Result, 25)
for i := range results {
results[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
}
m := newSearchModel(results, "q", 50, cfg, ss)
m.fetchingMore = true
m = updateModel(t, m, searchMoreResultsMsg{err: errTestSearch})
14 unmodified lines
ss := statusStyles{colorEnabled: false, width: 100}
cfg := search.Config{}
m := newSearchModel(make([]search.Result, 25), "q", 100, cfg, ss)
results := make([]search.Result, 25)
for i := range results {
results[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
}
m := newSearchModel(results, "q", 100, cfg, ss)
if m.totalPages() != 4 {
t.Fatalf("initial totalPages = %d, want 4", m.totalPages())
16 unmodified lines
// Model with 25 loaded results but on page 2 (no data) while fetching
ss := statusStyles{colorEnabled: false, width: 100}
cfg := search.Config{}
m := initTestViewport(newSearchModel(make([]search.Result, 25), "q", 50, cfg, ss))
results := make([]search.Result, 25)
for i := range results {
results[i] = search.Result{Type: "checkpoint", Checkpoint: &search.CheckpointResult{ID: fmt.Sprintf("id-%02d", i)}}
}
m := initTestViewport(newSearchModel(results, "q", 50, cfg, ss))
m.page = 1
m.fetchingMore = true
m = m.refreshBrowseContent()
171 unmodified lines
func TestComputeColumns(t *testing.T) {
t.Parallel()
cols := computeColumns(100)
cols := computeColumns(120)
if cols.typeCol != 5 {
t.Errorf("type width = %d, want 5", cols.typeCol)
}
if cols.age != 10 {
t.Errorf("age width = %d, want 10", cols.age)
}
15 unmodified lines
t.Errorf("repo width on narrow terminal = %d, want >= 10", cols.repo)
}
}
func TestSearchModel_ComputeTypeCounts(t *testing.T) {
t.Parallel()
m := testMultiTypeModel()
cp, cm, ss := m.computeTypeCounts()
if cp != 2 {
t.Errorf("checkpoints = %d, want 2", cp)
}
if cm != 1 {
t.Errorf("commits = %d, want 1", cm)
}
if ss != 1 {
t.Errorf("sessions = %d, want 1", ss)
}
}
func TestSearchModel_ComputeTypeCounts_UsesAPICounts(t *testing.T) {
t.Parallel()
m := testMultiTypeModel()
m.counts = &search.TypeCounts{Checkpoints: 10, Commits: 5, Sessions: 3}
cp, cm, ss := m.computeTypeCounts()
if cp != 10 {
t.Errorf("checkpoints = %d, want 10", cp)
}
if cm != 5 {
t.Errorf("commits = %d, want 5", cm)
}
if ss != 3 {
t.Errorf("sessions = %d, want 3", ss)
}
}
Mcmd/entire/cli/search_tui_test.go+313/-39