package protocol import ( "encoding/json" "slices" "strings" "testing" ) // TestSearchChatResultRoundTrip pins the additive chat hit: its payload and // ScannedChats survive the wire, and a reply without them encodes neither key, // so an older peer's search_results body is unchanged. func TestSearchChatResultRoundTrip(t *testing.T) { response := Message{Type: SearchResults, ID: "c1", SearchResults: &SearchResponse{ Query: "flaky", Kind: SearchKindChat, Cap: 50, ScannedChats: 3, Results: []SearchResult{{ Kind: SearchKindChat, Target: SearchChatTarget("ses_abc"), Score: 1, MatchedField: "message", Chat: &SearchChat{SessionID: "ses_abc", Title: "Fix CI", Directory: "/work/repo", Backend: "claude", MessageID: "m9", Role: "assistant", Snippet: "the flaky test", UpdatedAt: 1700000000000}, }}, }} encoded, err := json.Marshal(response) if err != nil { t.Fatal(err) } var echoed Message if err := json.Unmarshal(encoded, &echoed); err != nil { t.Fatal(err) } got := echoed.SearchResults if got == nil || got.ScannedChats != 3 || got.Kind != SearchKindChat || len(got.Results) != 1 { t.Fatalf("chat search response lost: %+v", got) } hit := got.Results[0] if hit.Target != "chat:ses_abc" || hit.Chat == nil || *hit.Chat != *response.SearchResults.Results[0].Chat { t.Fatalf("chat payload lost: %+v", hit) } if label := hit.Label(); label != "chat · Fix CI · /work/repo" { t.Fatalf("label = %q", label) } plain, err := json.Marshal(SearchResponse{Results: []SearchResult{{Kind: SearchKindRun, Target: "run:1"}}}) if err != nil { t.Fatal(err) } if strings.Contains(string(plain), "scanned_chats") || strings.Contains(string(plain), `"chat"`) { t.Fatalf("a run-only reply encodes chat keys: %s", plain) } } // TestSearchKindChatIsNotAStoreKind keeps chats out of the all-kind store // vocabulary, so an older client's default search never changes shape. func TestSearchKindChatIsNotAStoreKind(t *testing.T) { if slices.Contains(SearchKinds, SearchKindChat) { t.Fatalf("SearchKinds = %v, chat must be requested on its own", SearchKinds) } } func TestSearchSnippetWindowsTheMatch(t *testing.T) { text := strings.Repeat("a", 60) + " Needle here " + strings.Repeat("b", 60) got := SearchSnippet(text, "needle") if !strings.HasPrefix(got, "…") || !strings.HasSuffix(got, "…") || !strings.Contains(got, "Needle") { t.Fatalf("snippet = %q", got) } if got := SearchSnippet("short\nline", "zzz"); got != "short line" { t.Fatalf("unmatched short snippet = %q", got) } }