Files
pipelines/internal/server/search_chat_scoped.go
T
alan 8bd219e636 Chat: find in chat (Ctrl+F / Cmd+F)
A find bar over the transcript: query, Match case, n of N (counted from
the newest), Enter for an older match and Shift+Enter for a newer one.
Matches are painted over the rendered text, code blocks included, without
restyling it; the current match is scrolled into view. Matches in history
not loaded yet come from the server's chat:<id>-scoped search and are
reached by loading older pages. Esc closes and returns to the composer.
The key is the pane's, so a focused terminal keeps Ctrl+F. Fixture answers
scoped searches for captures; cheatsheet lists the key. The scoped search
matches the query as typed, spaces included, like the client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:41:39 +00:00

211 lines
6.3 KiB
Go

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 "<skip>|<history cursor>"; 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:<id>")
}
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,
}
// Find matches the query as typed, spaces included, like the client's
// own matching of the loaded transcript.
query := []rune(req.Query)
if strings.TrimSpace(req.Query) == "" {
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
}