Search: find operator chats by title, directory and message text

A search with kind chat matches the operator-session registry's titles and
directories and the newest messages of recent transcripts through the chat
broker (bounded count, concurrency and one-second budget), answered off the
connection's read loop. The all-kind search is unchanged for older clients.

The app sends the chat search after its run search and shows a Chats group
with title, harness, directory and snippet; a chat hit opens that chat in the
Chat tab. The probe fixture answers chat searches over ?chats=N.
This commit is contained in:
2026-11-03 13:01:53 +00:00
parent d34185b56c
commit bff7115e4e
31 changed files with 1659 additions and 118 deletions
+71 -1
View File
@@ -24,6 +24,12 @@ const (
SearchKindStep = "step"
SearchKindField = "field"
SearchKindArtifact = "artifact"
// SearchKindChat narrows to operator chat sessions. It is not part of
// SearchKinds: the store's all-kind search never includes chats, so an
// older client's reply is unchanged. A client asks for chats with this
// kind as its own request, which the server answers concurrently with
// (and never ahead of or blocking) the run/artifact search.
SearchKindChat = "chat"
)
// SearchKinds is the accepted Kind vocabulary in display order; the CLI help
@@ -52,6 +58,13 @@ const (
// SearchMaxScanSteps bounds how many recorded steps one query inspects while
// scanning input/output/transcript field text.
SearchMaxScanSteps = 2000
// SearchMaxScanChats bounds how many of the most recently used operator
// chats one chat search reads message text from; titles and directories
// of every listed chat are always matched.
SearchMaxScanChats = 24
// SearchChatMessagesPerChat is how many of a chat's newest messages one
// chat search reads.
SearchChatMessagesPerChat = 100
// SearchMaxScanBytes bounds the total field bytes (input_json + output_json +
// evidence_json + transcript) one query decodes and searches before it stops
// and reports Truncated.
@@ -85,12 +98,15 @@ type SearchResponse struct {
ScannedBytes int `json:"scanned_bytes"`
Cap int `json:"cap"`
ScanBoundBytes int `json:"scan_bound_bytes"`
// ScannedChats is how many chat transcripts a chat search read message
// text from (kind chat only); additive, so older peers ignore it.
ScannedChats int `json:"scanned_chats,omitempty"`
}
// SearchResult is one typed, navigable match. Kind selects which payload is
// set; Target is a stable token an existing CLI command can resolve
// (pipeline:<id>, pipeline:<id>:v<version>, run:<id>, run:<id>:<sequence>,
// run:<id>:<sequence>:<field>, or an artifact URL). Score and MatchedField
// run:<id>:<sequence>:<field>, an artifact URL, or chat:<session id>). Score and MatchedField
// expose the ranking tier and why the hit matched so a client can re-rank;
// Recency is the hit's sortable UTC timestamp.
type SearchResult struct {
@@ -105,6 +121,7 @@ type SearchResult struct {
Step *SearchStep `json:"step,omitempty"`
Field *SearchField `json:"field,omitempty"`
Artifact *SearchArtifact `json:"artifact,omitempty"`
Chat *SearchChat `json:"chat,omitempty"`
}
// SearchPipeline is a pipeline name/identity hit: its latest version and stage count.
@@ -166,6 +183,24 @@ type SearchArtifact struct {
URL string `json:"url"`
}
// SearchChat is an operator chat session hit: its registry facts and, for a
// message-text match, the matching message's id, role and a snippet around
// the first match. MatchedField is "title", "directory" or "message".
type SearchChat struct {
SessionID string `json:"session_id"`
Title string `json:"title"`
Directory string `json:"directory,omitempty"`
Backend string `json:"backend,omitempty"`
Closed bool `json:"closed,omitempty"`
UpdatedAt int64 `json:"updated_at,omitempty"`
MessageID string `json:"message_id,omitempty"`
Role string `json:"role,omitempty"`
Snippet string `json:"snippet,omitempty"`
}
// SearchChatTarget is a chat hit's target token.
func SearchChatTarget(sessionID string) string { return "chat:" + sessionID }
// Label is the compact human description of a hit, built from the result's
// typed payload rather than its target token, so it is the single definition
// shared by the CLI and the TUI. A text-field hit's snippet is deliberately not
@@ -198,10 +233,45 @@ func (r SearchResult) Label() string {
if r.Artifact != nil {
return fmt.Sprintf("run %d · step %d · %s · %s", r.Artifact.RunID, r.Artifact.Sequence, r.Artifact.Name, r.Artifact.ContentType)
}
case SearchKindChat:
if r.Chat != nil {
label := "chat · " + r.Chat.Title
if r.Chat.Directory != "" {
label += " · " + r.Chat.Directory
}
return label
}
}
return r.Target
}
// SearchSnippet reduces text to a single clean line and centers a short window
// on the first case-insensitive match, folding runes so UTF-8 boundaries are
// never split and the result is always well-formed. Text with no match is
// truncated from its start.
func SearchSnippet(text, query string) string {
normalized := NormalizeText(text)
runes := []rune(normalized)
index := RuneIndexFold(runes, []rune(query))
if index < 0 {
if len(runes) <= 80 {
return normalized
}
return string(runes[:80]) + "…"
}
const margin = 40
start := max(index-margin, 0)
end := min(index+len([]rune(query))+margin, len(runes))
snippet := string(runes[start:end])
if start > 0 {
snippet = "…" + snippet
}
if end < len(runes) {
snippet = snippet + "…"
}
return snippet
}
// RuneIndexFold returns the rune index where query first matches text
// case-insensitively, or -1 when it does not. It folds runes rather than bytes
// so a caller never splits a UTF-8 boundary, and an empty query never matches.
+67
View File
@@ -0,0 +1,67 @@
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)
}
}