diff --git a/internal/protocol/search.go b/internal/protocol/search.go index 9dae88e8..6724bdd6 100644 --- a/internal/protocol/search.go +++ b/internal/protocol/search.go @@ -84,8 +84,22 @@ type SearchRequest struct { // and private/ scratch, see ClassifyArtifacts). Off by default: artifact // search surfaces only deliverables. IncludeDebug bool `json:"include_debug,omitempty"` + // Scope narrows a kind=chat search to one chat ("chat:"). + // A scoped search returns every text-part occurrence of Query in that + // chat's messages, newest message first, one result per occurrence with + // its message id, part index and offset, paged by Cursor/NextCursor. + Scope string `json:"scope,omitempty"` + // Cursor continues a scoped chat search: a previous reply's NextCursor, + // or a chat_messages next_cursor to start just before the messages a + // client already holds. Empty starts at the newest message. + Cursor string `json:"cursor,omitempty"` + // CaseSensitive makes a scoped chat search match case exactly. + CaseSensitive bool `json:"case_sensitive,omitempty"` } +// SearchChatScope is a scoped chat search's Scope for one session. +func SearchChatScope(sessionID string) string { return "chat:" + sessionID } + // SearchResponse is the bounded set of matches. Results are ordered by recency // descending (a chat's last use for kind chat), numeric entity/visit IDs // descending, then target ascending, before the cap applies; Score records the @@ -105,6 +119,11 @@ type SearchResponse struct { // 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"` + // NextCursor continues a scoped chat search that stopped before the + // chat's oldest message (result cap or scan budget); empty when done. + NextCursor string `json:"next_cursor,omitempty"` + // ScannedMessages is how many messages a scoped chat search read. + ScannedMessages int `json:"scanned_messages,omitempty"` } // SearchResult is one typed, navigable match. Kind selects which payload is @@ -202,6 +221,13 @@ type SearchChat struct { MessageID string `json:"message_id,omitempty"` Role string `json:"role,omitempty"` Snippet string `json:"snippet,omitempty"` + // Part and Offset locate one occurrence in a scoped chat search: the + // index of the text part in the message's parts and the match's start + // in that part's text, in UTF-16 code units (as a browser or Dart string + // counts). Length is the match's length in the same units. + Part int `json:"part,omitempty"` + Offset int `json:"offset,omitempty"` + Length int `json:"length,omitempty"` } // SearchChatTarget is a chat hit's target token. diff --git a/internal/server/search_chat_scoped.go b/internal/server/search_chat_scoped.go new file mode 100644 index 00000000..8ed0e7a8 --- /dev/null +++ b/internal/server/search_chat_scoped.go @@ -0,0 +1,208 @@ +package server + +import ( + "context" + "errors" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf16" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// Scoped chat search ("find in chat"): every occurrence of a query in one +// chat's message text, newest message first, paged. A client uses it to count +// and reach matches in history it has not loaded yet. +const ( + // scopedChatPageMessages is how many messages one broker read returns. + scopedChatPageMessages = 200 + // scopedChatMaxMessages bounds the messages one scoped request reads; + // a longer history continues through NextCursor. + scopedChatMaxMessages = 2000 +) + +// scopedChatBudget bounds how long one scoped request reads history before it +// replies with what it found and a cursor. A variable so a test can shorten it. +var scopedChatBudget = 2 * time.Second + +// scopedChatSession returns the session id a chat search's Scope names, or "" +// when the request is not scoped. +func scopedChatSession(req protocol.SearchRequest) string { + scope := strings.TrimSpace(req.Scope) + if scope == "" { + return "" + } + return strings.TrimPrefix(scope, "chat:") +} + +// scopedCursor is where a scoped search resumes: the broker's history cursor +// for a page (empty for the newest) and how many of that page's newest +// messages were already searched. It travels as "|"; a +// cursor without the separator is a chat_messages next_cursor. +type scopedCursor struct { + history string + skip int +} + +func parseScopedCursor(value string) scopedCursor { + skip, history, found := strings.Cut(value, "|") + if !found { + return scopedCursor{history: value} + } + n, err := strconv.Atoi(skip) + if err != nil || n < 0 { + return scopedCursor{history: history} + } + return scopedCursor{history: history, skip: n} +} + +func (c scopedCursor) String() string { return strconv.Itoa(c.skip) + "|" + c.history } + +// searchChatScoped answers a scoped chat search. Results hold one hit per +// occurrence; a message's occurrences are never split across replies, so a +// reply may exceed the cap by one message's worth. +func searchChatScoped(ctx context.Context, req protocol.SearchRequest, broker chatBroker) (*protocol.SearchResponse, error) { + sessionID := scopedChatSession(req) + if !validChatSessionID(sessionID) { + return nil, errors.New("a valid chat session id is required in scope chat:") + } + if broker == nil { + return nil, errors.New("chat is not configured on this server") + } + response := &protocol.SearchResponse{ + Query: req.Query, + Kind: protocol.SearchKindChat, + Results: []protocol.SearchResult{}, + Cap: chatSearchLimit(req.Limit), + ScanBoundBytes: protocol.SearchMaxScanBytes, + } + query := []rune(strings.TrimSpace(req.Query)) + if len(query) == 0 { + return response, nil + } + ctx, cancel := context.WithTimeout(ctx, scopedChatBudget) + defer cancel() + cursor := parseScopedCursor(req.Cursor) + for { + page, err := broker.Messages(ctx, sessionID, scopedChatPageMessages, cursor.history) + if err != nil { + if ctx.Err() != nil && response.ScannedMessages > 0 { + // Out of time: what was found stands; the client continues. + response.Truncated = true + response.NextCursor = cursor.String() + return response, nil + } + return nil, err + } + messages := page.Messages + for index := len(messages) - 1 - cursor.skip; index >= 0; index-- { + message := messages[index] + response.Results = append(response.Results, scopedMessageHits(sessionID, message, query, req.CaseSensitive)...) + response.ScannedMessages++ + cursor.skip++ + done := index == 0 && (!page.HasMore || page.NextCursor == "") + if done { + return response, nil + } + if len(response.Results) >= response.Cap || + response.ScannedMessages >= scopedChatMaxMessages || ctx.Err() != nil { + response.Truncated = true + if index == 0 { + cursor = scopedCursor{history: page.NextCursor} + } + response.NextCursor = cursor.String() + return response, nil + } + } + if !page.HasMore || page.NextCursor == "" { + return response, nil + } + cursor = scopedCursor{history: page.NextCursor} + } +} + +// scopedMessageHits is one hit per occurrence of query in message's text parts. +func scopedMessageHits(sessionID string, message protocol.ChatMessage, query []rune, caseSensitive bool) []protocol.SearchResult { + var hits []protocol.SearchResult + for partIndex, part := range message.Parts { + if part.Type != protocol.ChatPartText || part.Text == "" { + continue + } + for _, match := range runeMatches([]rune(part.Text), query, caseSensitive) { + hits = append(hits, protocol.SearchResult{ + Kind: protocol.SearchKindChat, + Target: protocol.SearchChatTarget(sessionID), + Score: chatScoreMessage, + MatchedField: "message", + Chat: &protocol.SearchChat{ + SessionID: sessionID, + MessageID: message.ID, + Role: message.Role, + Snippet: protocol.SearchSnippet(part.Text, string(query)), + Part: partIndex, + Offset: match.offset, + Length: match.length, + }, + }) + } + } + return hits +} + +type runeMatch struct{ offset, length int } + +// runeMatches finds the non-overlapping occurrences of query in text, folding +// case unless caseSensitive, and reports each in UTF-16 code units. +func runeMatches(text, query []rune, caseSensitive bool) []runeMatch { + if len(query) == 0 || len(query) > len(text) { + return nil + } + var matches []runeMatch + units := 0 // UTF-16 units before text[i] + for i := 0; i <= len(text)-len(query); { + if runesEqual(text[i:i+len(query)], query, caseSensitive) { + length := utf16Len(text[i : i+len(query)]) + matches = append(matches, runeMatch{offset: units, length: length}) + units += length + i += len(query) + continue + } + units += utf16.RuneLen(text[i]) + i++ + } + return matches +} + +func runesEqual(a, b []rune, caseSensitive bool) bool { + for i := range a { + if a[i] == b[i] { + continue + } + if caseSensitive || !foldEqual(a[i], b[i]) { + return false + } + } + return true +} + +func foldEqual(a, b rune) bool { + if unicode.ToLower(a) == unicode.ToLower(b) { + return true + } + for folded := unicode.SimpleFold(a); folded != a; folded = unicode.SimpleFold(folded) { + if folded == b { + return true + } + } + return false +} + +func utf16Len(runes []rune) int { + n := 0 + for _, r := range runes { + n += utf16.RuneLen(r) + } + return n +} diff --git a/internal/server/search_chat_scoped_test.go b/internal/server/search_chat_scoped_test.go new file mode 100644 index 00000000..987b9f22 --- /dev/null +++ b/internal/server/search_chat_scoped_test.go @@ -0,0 +1,147 @@ +package server + +import ( + "context" + "fmt" + "strconv" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// scopedHistoryChat serves one session's history oldest first in pages of the +// requested size; a cursor is the index one past the page's oldest message. +type scopedHistoryChat struct { + *fakeChat + messages []protocol.ChatMessage +} + +func (c *scopedHistoryChat) Messages(_ context.Context, _ string, limit int, cursor string) (protocol.ChatHistoryPage, error) { + end := len(c.messages) + if cursor != "" { + n, err := strconv.Atoi(cursor) + if err != nil { + return protocol.ChatHistoryPage{}, err + } + end = n + } + start := max(end-limit, 0) + page := protocol.ChatHistoryPage{Messages: c.messages[start:end]} + if start > 0 { + page.HasMore = true + page.NextCursor = strconv.Itoa(start) + } + return page, nil +} + +func pagedHistory(n int) []protocol.ChatMessage { + messages := make([]protocol.ChatMessage, n) + for i := range messages { + text := fmt.Sprintf("message %d", i) + if i%10 == 0 { + text = fmt.Sprintf("Needle %d and needle again", i) + } + messages[i] = chatText(fmt.Sprintf("m%d", i), protocol.ChatRoleAssistant, text) + } + return messages +} + +func TestScopedChatSearchReturnsEveryOccurrenceNewestFirst(t *testing.T) { + broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)} + response, err := searchChatScoped(context.Background(), protocol.SearchRequest{ + Query: "needle", Kind: protocol.SearchKindChat, Scope: protocol.SearchChatScope("ses_a"), Limit: 200, + }, broker) + if err != nil { + t.Fatal(err) + } + if len(response.Results) != 90 || response.NextCursor != "" || response.Truncated { + t.Fatalf("results=%d cursor=%q truncated=%v", len(response.Results), response.NextCursor, response.Truncated) + } + first := response.Results[0].Chat + if first.MessageID != "m440" || first.Offset != 0 || first.Length != 6 { + t.Fatalf("first hit = %+v", first) + } + second := response.Results[1].Chat + if second.MessageID != "m440" || second.Offset != len("Needle 440 and ") { + t.Fatalf("second hit = %+v", second) + } + if last := response.Results[89].Chat; last.MessageID != "m0" { + t.Fatalf("last hit = %+v", last) + } +} + +func TestScopedChatSearchPagesThroughCursor(t *testing.T) { + broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)} + request := protocol.SearchRequest{Query: "needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Limit: 7} + var ids []string + for pages := 0; ; pages++ { + if pages > 50 { + t.Fatal("cursor never ended") + } + response, err := searchChatScoped(context.Background(), request, broker) + if err != nil { + t.Fatal(err) + } + for _, hit := range response.Results { + ids = append(ids, hit.Chat.MessageID) + } + if response.NextCursor == "" { + break + } + request.Cursor = response.NextCursor + } + if len(ids) != 90 { + t.Fatalf("hits across pages = %d", len(ids)) + } + seen := map[string]int{} + for _, id := range ids { + seen[id]++ + } + if len(seen) != 45 || seen["m0"] != 2 || seen["m440"] != 2 { + t.Fatalf("each needle message twice, got %v", seen) + } +} + +func TestScopedChatSearchStartsAtHistoryCursorAndMatchesCase(t *testing.T) { + broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)} + response, err := searchChatScoped(context.Background(), protocol.SearchRequest{ + Query: "Needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Cursor: "250", CaseSensitive: true, + }, broker) + if err != nil { + t.Fatal(err) + } + if len(response.Results) != 25 || response.Results[0].Chat.MessageID != "m240" { + t.Fatalf("results=%d first=%+v", len(response.Results), response.Results[0].Chat) + } +} + +func TestScopedChatSearchCountsUTF16Offsets(t *testing.T) { + matches := runeMatches([]rune("😀 Ünïcode ünïcode"), []rune("ÜNÏ"), false) + if len(matches) != 2 || matches[0].offset != 3 || matches[1].offset != 11 || matches[0].length != 3 { + t.Fatalf("matches = %+v", matches) + } + if got := runeMatches([]rune("aaaa"), []rune("aa"), true); len(got) != 2 { + t.Fatalf("overlapping matches counted: %+v", got) + } +} + +func TestScopedChatSearchRejectsAnInvalidScope(t *testing.T) { + broker := &scopedHistoryChat{fakeChat: scriptedChat()} + if _, err := searchChatScoped(context.Background(), protocol.SearchRequest{Query: "x", Scope: "chat:../etc"}, broker); err == nil { + t.Fatal("invalid scope accepted") + } +} + +func TestScopedChatSearchOverTheSocket(t *testing.T) { + broker := &transcriptChat{fakeChat: scriptedChat(), pages: map[string][]protocol.ChatMessage{}} + ctx, conn := chatSearchFixture(t, broker) + writeChat(t, ctx, conn, protocol.Message{Type: protocol.Search, ID: "scoped", Search: &protocol.SearchRequest{ + Query: "flaky", Kind: protocol.SearchKindChat, Scope: "chat:ses_text", + }}) + reply := readReply(t, ctx, conn, "scoped") + // transcriptChat refuses any page size but the global search's, so the + // scoped search's own read comes back as an error reply. + if reply.Type != protocol.Error { + t.Fatalf("reply = %+v", reply) + } +} diff --git a/internal/server/search_chats.go b/internal/server/search_chats.go index 95e150d5..cb957989 100644 --- a/internal/server/search_chats.go +++ b/internal/server/search_chats.go @@ -40,6 +40,13 @@ func isChatSearch(request protocol.Message) bool { // chatSearchReply answers one kind=chat search request. func chatSearchReply(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry) protocol.Message { + if scopedChatSession(*request.Search) != "" { + response, err := searchChatScoped(ctx, *request.Search, broker) + if err != nil { + return protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()} + } + return protocol.Message{Type: protocol.SearchResults, ID: request.ID, SearchResults: response} + } if registry == nil { return protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat search unavailable: operator session registry is not configured on this server"} } diff --git a/internal/server/websocket.go b/internal/server/websocket.go index b44124b5..1a2f3591 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -285,8 +285,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // A chat search runs beside the read loop so its transcript readback // never delays the run search sent with it; a newer one cancels the // previous, whose reply the client would discard as stale anyway. + // A newer chat search replaces an older one of the same mode: the + // chat list's search and a find-in-chat search never cancel each other. cancelChatSearch := func() {} - defer func() { cancelChatSearch() }() + cancelScopedChatSearch := func() {} + defer func() { cancelChatSearch(); cancelScopedChatSearch() }() // Keystrokes and sizes take their own lane (terminal_lane.go), so // they never wait behind a slow request read before them. The lane // is drained before the deferred detaches above run. @@ -312,9 +315,14 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin continue } if isChatSearch(request) { - cancelChatSearch() searchCtx, cancel := context.WithCancel(connCtx) - cancelChatSearch = cancel + if scopedChatSession(*request.Search) != "" { + cancelScopedChatSearch() + cancelScopedChatSearch = cancel + } else { + cancelChatSearch() + cancelChatSearch = cancel + } go func(request protocol.Message) { defer cancel() _ = write(chatSearchReply(searchCtx, request, options.Chat, registry))