diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index a7231e2f0..64e0e29d4 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -142,6 +142,47 @@ when turns or a part's end weren't kept). A magpie that others reach as a remote magpie has no file of their agents' sessions, so this is the only way it can export them. Verification: `TestGatewaySessionExportsMarkdown`. +A gateway session is titled by what it was first asked (YOU on Discord), not +its `ses_…` id: `sessions.GatewayTitle` reads the first 8 complete turns of +the oldest recorded file of it in the 7 days kept, takes the first user text +part that isn't a `<…>` context tag, `# AGENTS.md` or an image, and makes it one +line (`untagged`). A finished file's answer is cached by path; a growing +`turns.jsonl` with no title yet is read again. With nothing recorded at all +(the store's folder missing) it costs one stat. `gatewayListed` applies it in +every list (`/api/sessions`, `/manage`, `/one`, the stats summaries); a session +with no recorded text keeps its id as title. + +`GET /api/sessions/search?agent=&q=` finds an agent's sessions by what was said +in them, for the Sessions page's filter. The query is lowered and its spaces +made one (`sessions.NeedleOf`); under 2 runes it searches nothing. Native +sessions of an agent whose files are read (`HasTranscript`) are read from their +own file (`SearchSession`), first through a byte prefilter (`mayHold`: the +query's longest word, ASCII case folded without a copy, in 1 MiB chunks; +skipped for zstd files and for queries JSON may escape), then decoded only to +the first match in what the user or the model said. Of a Claude or Codex file +only the lines holding every word of the query are decoded (`readTranscriptOf`, +a part being one line's); Pi's tree is read whole. Without that, one 1.3 GB +Claude session took the whole 8 seconds; with it, all 58 of the owner's (3 GB) +are searched in 3–7 s on a loaded machine. Gateway sessions, and the native sessions of an agent whose files aren't +read (then `unread: true`), are searched in their recorded transcript +(`SearchGateway`). System prompts, tool definitions (`role: system`, `kind: +context`) and images are never matched. Sessions are read newest first by 4 +workers at most, stopping at 200 hits or 8 seconds (`cut: true`, with +`searched` of `total`); the request's context cancels the read, so the page's +next query ends the last one. Each hit carries the match with up to 36 runes +before and 120 after, cut ends marked "…". The page waits 300 ms after the +last keystroke, aborts the request in flight, shows a title, folder, id or +model match at once, adds the sessions the search found with their snippet +(the match in a ``, built as text nodes), and says when it is +searching, cut short or limited to recorded text. +Implementation: [`internal/sessions/search.go`](../../internal/sessions/search.go), +`searchSessions` in [`internal/gui/sessions_manage.go`](../../internal/gui/sessions_manage.go), +[`internal/gui/assets/sessions.js`](../../internal/gui/assets/sessions.js). +Verification: `TestSearchSession*` (`TestSearchSessionReadsOnlyLinesWithTheWords` +for the line filter), `TestContainsFold`, `TestMayHoldSkipsAFileWithoutTheWords`, +`TestGatewayTitleAndSearch`, `TestSessionsSearch*`; browser +`sessions-search.test.cjs`. + Verification: `TestGatewayConversation*` (`TestGatewayConversationNeedsTheClientsSession` and `TestGatewayConversationClientRequestPrefixedSession` for the two rules above), `TestGatewaySessionHistoryAndCalendar`, `TestGatewaySessionsNativeWinsBeforeLimits`, diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 1f254f8c2..81e5ab840 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2582,6 +2582,10 @@ const I18N = { "at effective prices": "按生效价格", "just now": "刚刚", "No session matches.": "没有匹配的会话。", + "Searching what was said…": "正在搜索对话内容…", + "Couldn't search what was said: {error}": "无法搜索对话内容:{error}", + "{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.": "这里读不到 {agent} 自己的会话文件,只搜索 magpie 通过网关记录的内容。", + "Searched what was said in the latest {n} of {total} sessions.": "已搜索最近 {n} 个会话的对话内容(共 {total} 个)。", "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "还没有会话。本机 Claude Code、Codex、Hermes、OpenCode 和 Pi 的会话会显示在这里,附费用和继续会话的命令。", "Reading the agents' session files…": "正在读取 Agent 的会话文件…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合计含 Agent 文件中的全部会话;列表为最近活动的 {n} 个 · {dirs}", @@ -6955,6 +6959,10 @@ const I18N = { "at effective prices": "按生效價格", "just now": "剛剛", "No session matches.": "沒有匹配的會話。", + "Searching what was said…": "正在搜尋對話內容…", + "Couldn't search what was said: {error}": "無法搜尋對話內容:{error}", + "{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.": "這裡讀不到 {agent} 自己的會話檔案,只搜尋 magpie 透過閘道記錄的內容。", + "Searched what was said in the latest {n} of {total} sessions.": "已搜尋最近 {n} 個會話的對話內容(共 {total} 個)。", "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "還沒有會話。本機 Claude Code、Codex、Hermes、OpenCode 和 Pi 的會話會顯示在這裡,附費用和繼續會話的命令。", "Reading the agents' session files…": "正在讀取 Agent 的會話檔案…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合計含 Agent 檔案中的全部會話;列表為最近活動的 {n} 個 · {dirs}", @@ -11332,6 +11340,10 @@ const I18N = { "at effective prices": "有効な価格で", "just now": "たった今", "No session matches.": "一致するセッションはありません。", + "Searching what was said…": "会話の内容を検索中…", + "Couldn't search what was said: {error}": "会話の内容を検索できませんでした:{error}", + "{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.": "{agent} 自身のセッションファイルはここでは読めないため、magpie がゲートウェイ経由で記録した内容だけを検索します。", + "Searched what was said in the latest {n} of {total} sessions.": "最新 {n} 件の会話の内容を検索しました(全 {total} 件)。", "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "セッションはまだありません。このコンピュータ上の Claude Code、Codex、Hermes、OpenCode、Pi のセッションが、それぞれの費用と再開コマンドとともにここに表示されます。", "Reading the agents' session files…": "エージェントのセッションファイルを読み取り中…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合計はエージェント自身のファイルにあるすべてのセッションを集計しています。一覧は最近のアクティビティ順で {n} 件 · {dirs}", @@ -15708,6 +15720,10 @@ const I18N = { "at effective prices": "zu effektiven Preisen", "just now": "gerade eben", "No session matches.": "Keine passende Sitzung.", + "Searching what was said…": "Gesprächsinhalte werden durchsucht …", + "Couldn't search what was said: {error}": "Gesprächsinhalte konnten nicht durchsucht werden: {error}", + "{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.": "Die eigenen Sitzungsdateien von {agent} sind hier nicht lesbar, daher wird nur durchsucht, was magpie über das Gateway aufgezeichnet hat.", + "Searched what was said in the latest {n} of {total} sessions.": "Gesprächsinhalte der neuesten {n} von {total} Sitzungen durchsucht.", "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "Noch keine Sitzungen. Sitzungen von Claude Code, Codex, Hermes, OpenCode und Pi auf diesem Computer erscheinen hier, jeweils mit Kosten und dem Befehl zum Fortsetzen.", "Reading the agents' session files…": "Sitzungsdateien der Agenten werden gelesen…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "Summen zählen jede Sitzung in den Dateien der Agenten; die Liste zeigt die {n} zuletzt aktiven · {dirs}", diff --git a/internal/gui/assets/sessions.css b/internal/gui/assets/sessions.css index d62767222..41e873f1b 100644 --- a/internal/gui/assets/sessions.css +++ b/internal/gui/assets/sessions.css @@ -20,6 +20,9 @@ .sm-trash-btn.on { background: var(--pill); color: var(--fg); } .sm-body { display: flex; flex-direction: column; gap: 8px; flex: none; } .sm-note { margin: 0 2px; } +/* where a session said what was searched for, the words themselves marked */ +.row .sub.sm-hit { color: var(--fg-2); } +.sm-hit mark { background: var(--accent-soft); color: var(--fg); border-radius: 3px; padding: 0 1px; font-weight: 500; } .sm-bar { gap: 8px; padding: 0 11px; } .sm-bar .grow { flex: 1; } .sm-bar .sm-delete, .sm-bar .sm-empty { display: inline-flex; align-items: center; gap: 5px; } diff --git a/internal/gui/assets/sessions.js b/internal/gui/assets/sessions.js index bf38a0ccf..664e048c5 100644 --- a/internal/gui/assets/sessions.js +++ b/internal/gui/assets/sessions.js @@ -16,6 +16,16 @@ let agent = ""; try { agent = localStorage.getItem("magpie.sessionsAgent") || ""; } catch {} let query = ""; + // The filter also finds a session by what was said in it: the server + // reads the agent's conversations a moment after the last keystroke, and + // a new keystroke cancels the read it was on (YOU on Discord: a session + // the gateway recorded is named ses_…, and its words are how it is + // remembered). found is that search, for one agent and one query. + let found = null; // { agent, needle, hits: Map(id -> hit), busy, cut, unread, searched, total, error } + let searchCtl = null; + let searchT = 0; + const SEARCH_WAIT = 300; + const needleOf = (q) => q.trim().split(/\s+/).filter(Boolean).join(" ").toLowerCase(); let trashOn = false; const picked = new Set(); // ids picked to delete, of the agent shown const opened = new Set(); // folders unfolded, by cwd @@ -61,6 +71,7 @@ failed = ""; talks.clear(); // read again when shown: a session may have gone on if (agent !== d.agent) { agent = d.agent; picked.clear(); } + if (query) searchSoon(); // the same words, in this agent's sessions } catch (e) { if (n !== loading) return; failed = e.message; @@ -83,6 +94,7 @@ trashOn = false; if (s.id) { query = ""; + searchSoon(); detail = s.id; openedFor = agent; opened.clear(); @@ -105,12 +117,69 @@ } const current = () => data?.agents.find((a) => a.agent === data.agent); + // the search of what was said, when it is of the agent and words shown + const search = () => found && found.agent === data?.agent && found.needle === needleOf(query) ? found : null; + const hitOf = (s) => search()?.hits.get(s.id); const shown = () => { const q = query.trim().toLowerCase(); const list = data?.sessions || []; - return q ? list.filter((s) => [s.title, s.cwd, s.id, ...(s.models || []).map((m) => m.model)].some((x) => (x || "").toLowerCase().includes(q))) : list; + return q ? list.filter((s) => hitOf(s) || [s.title, s.cwd, s.id, ...(s.models || []).map((m) => m.model)].some((x) => (x || "").toLowerCase().includes(q))) : list; }; + // searchSoon searches what was said for the filter's words, once typing + // pauses; fewer than two letters search nothing + function searchSoon() { + clearTimeout(searchT); + const needle = needleOf(query); + if (!data?.agent || [...needle].length < 2) { + searchCtl?.abort(); + searchCtl = null; + found = null; + return; + } + if (found && found.agent === data.agent && found.needle === needle && !found.busy && !found.error) return; + searchCtl?.abort(); + searchCtl = null; + const mine = found = { agent: data.agent, needle, hits: new Map(), busy: true }; + searchT = setTimeout(async () => { + const ctl = searchCtl = new AbortController(); + try { + const r = await api(`sessions/search?agent=${encodeURIComponent(mine.agent)}&q=${encodeURIComponent(needle)}`, undefined, undefined, ctl.signal); + if (found !== mine) return; + found = { ...mine, busy: false, hits: new Map((r?.hits || []).map((h) => [h.id, h])), cut: !!r?.cut, unread: !!r?.unread, searched: r?.searched || 0, total: r?.total || 0 }; + } catch (e) { + if (ctl.signal.aborted || found !== mine) return; + found = { ...mine, busy: false, error: e.message }; + } + if (searchCtl === ctl) searchCtl = null; + if (view === "sessions" && !trashOn) { drawnIn.clear(); redrawList(); } + }, SEARCH_WAIT); + } + + // what the search is doing, above the list, when it says more than the + // rows do + function searchNote() { + const f = search(); + if (!f) return null; + let text = ""; + if (f.busy) text = t("Searching what was said…"); + else if (f.error) text = t("Couldn't search what was said: {error}", { error: f.error }); + else if (f.unread) text = t("{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.", { agent: current()?.name || f.agent }); + else if (f.cut) text = t("Searched what was said in the latest {n} of {total} sessions.", { n: f.searched, total: f.total }); + if (!text) return null; + const p = el("p", "usage-note sm-note sm-search-note", text); + p.setAttribute("role", "status"); + return p; + } + + // the words round where a session said what was searched for + function hitLine(h) { + const d = el("div", "sub sm-hit"); + d.append(h.before || "", el("mark", "", h.match), h.after || ""); + d.title = (h.before || "") + h.match + (h.after || ""); + return d; + } + function draw() { const keepFocus = page.querySelector(".sm-agent-pick:focus, .sm-agents .opt:focus"); fitObserver?.disconnect(); @@ -249,11 +318,11 @@ q.type = "search"; q.spellcheck = false; q.autocomplete = "off"; - q.placeholder = t("Filter sessions"); + q.placeholder = t("Search sessions"); q.value = query; q.hidden = trashOn; - q.oninput = () => { query = q.value; drawnIn.clear(); redrawList(); }; - q.onkeydown = (e) => { if (e.key === "Escape" && q.value) { e.stopPropagation(); q.value = ""; query = ""; drawnIn.clear(); redrawList(); } }; + q.oninput = () => { query = q.value; drawnIn.clear(); searchSoon(); redrawList(); }; + q.onkeydown = (e) => { if (e.key === "Escape" && q.value) { e.stopPropagation(); q.value = ""; query = ""; drawnIn.clear(); searchSoon(); redrawList(); } }; const tr = el("button", "text sm-trash-btn" + (trashOn ? " on" : "")); tr.type = "button"; tr.setAttribute("aria-pressed", String(trashOn)); @@ -475,8 +544,10 @@ } tree.replaceChildren(); folderBoxes.clear(); + const note = searchNote(); + if (note) tree.append(note); if (!list.length) { - tree.append(el("div", "empty-state", query ? t("No session matches.") : t("No sessions yet"))); + if (!search()?.busy) tree.append(el("div", "empty-state", query ? t("No session matches.") : t("No sessions yet"))); return; } const q = query.trim(); @@ -581,6 +652,8 @@ sub.prepend(p, " "); } who.append(sub); + const hit = hitOf(s); + if (hit) who.append(hitLine(hit)); // what it spent, as the Usage page's list shows it r.append(who, ...sessSpent(s)); if (s.resume) { diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index 6ce6ee603..1c34b6286 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -51,8 +51,17 @@ func gatewayExternal(g usage.GatewaySession) sessions.ExternalSession { return e } +// gatewayListed is a gateway session as a list shows it: titled by what it +// was first asked, when magpie recorded it, not by its ses_… id (YOU on +// Discord) +func gatewayListed(g usage.GatewaySession) sessions.ExternalSession { + e := gatewayExternal(g) + e.Title = sessions.GatewayTitle(g.Agent, g.ID) + return e +} + func gatewaySession(g usage.GatewaySession) sessions.Session { - return sessions.MergeExternal(nil, []sessions.ExternalSession{gatewayExternal(g)})[0] + return sessions.MergeExternal(nil, []sessions.ExternalSession{gatewayListed(g)})[0] } func sessionRoutes(mux *http.ServeMux, w Windows) { @@ -86,7 +95,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { gateway := listedGateway(usage.GatewaySessions(time.Time{}, nativeKeys)) ext := make([]sessions.ExternalSession, 0, len(gateway)) for _, g := range gateway { - ext = append(ext, gatewayExternal(g)) + ext = append(ext, gatewayListed(g)) } list = sessions.MergeExternal(list, ext) if len(list) > n { @@ -388,7 +397,7 @@ func combinedSessionStats(days int) sessions.Stats { gs, gd := usage.GatewaySessionWindowExcept(since, nativeKeys) ext := make([]sessions.ExternalSession, 0, len(gs)) for _, g := range gs { - ext = append(ext, gatewayExternal(g)) + ext = append(ext, gatewayListed(g)) } daily := make([]sessions.ExternalDayUsage, 0, len(gd)) for _, d := range gd { diff --git a/internal/gui/sessions_manage.go b/internal/gui/sessions_manage.go index aca59d682..2ea688ecf 100644 --- a/internal/gui/sessions_manage.go +++ b/internal/gui/sessions_manage.go @@ -2,12 +2,15 @@ package gui import ( "cmp" + "context" "encoding/json" "errors" "net/http" "runtime" "sort" + "sync" "time" + "unicode/utf8" "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/sessions" @@ -196,6 +199,13 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) { } writeJSON(rw, out) }) + // search is the sessions of ?agent= whose conversation says ?q=, newest + // first, each with the words round its first match (YOU on Discord). A + // new query from the page cancels the request, and with it the search. + mux.HandleFunc("GET /api/sessions/search", func(rw http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + writeJSON(rw, searchSessions(r.Context(), q.Get("agent"), q.Get("q"), searchBudget)) + }) // delete moves the sessions named to magpie's trash, one by one; one // still being written is left, and said so. One seen only through the // gateway, of any agent, has what magpie keeps of it moved there. @@ -343,3 +353,131 @@ func forgetStats() { statsMemo.m = nil statsMemo.Unlock() } + +// searchHitMax is the most sessions a search lists, and searchBudget how +// long it reads before it says what it found so far. +const searchHitMax = 200 + +var searchBudget = 8 * time.Second + +type searchHitJSON struct { + ID string `json:"id"` + sessions.Hit +} + +type searchJSON struct { + Hits []searchHitJSON `json:"hits"` + // Searched is how many sessions were read, of Total that could be + Searched int `json:"searched"` + Total int `json:"total"` + // Cut: it stopped before reading them all, at searchHitMax hits or + // out of time + Cut bool `json:"cut,omitempty"` + // Unread: the agent's own sessions can't be read here (a database), + // only those magpie recorded through the gateway are searched + Unread bool `json:"unread,omitempty"` +} + +// searchSessions reads an agent's sessions, newest first, a few at once, and +// keeps those that say what was asked; every one is read only to its first +// match. +func searchSessions(ctx context.Context, agentID, query string, budget time.Duration) searchJSON { + out := searchJSON{Hits: []searchHitJSON{}} + needle := sessions.NeedleOf(query) + if agentID == "" || utf8.RuneCountInString(needle) < 2 { + return out + } + type job struct { + s sessions.Session + last time.Time + } + var jobs []job + native := map[string]bool{} + if sessions.HasTranscript(agentID) { + for _, m := range sessions.ListAgent(agentID) { + native[m.ID] = true + jobs = append(jobs, job{m.Session, m.Last}) + } + } else { + // what magpie recorded of them through the gateway is still read + out.Unread = true + for _, m := range sessions.ListAgent(agentID) { + native[m.ID] = true + jobs = append(jobs, job{sessions.Session{Gateway: true, Agent: m.Agent, ID: m.ID}, m.Last}) + } + } + for _, g := range listedGateway(usage.GatewaySessions(time.Time{}, nil)) { + if g.Agent == agentID && !native[g.ID] { + jobs = append(jobs, job{sessions.Session{Gateway: true, Agent: g.Agent, ID: g.ID}, g.Last}) + } + } + sort.SliceStable(jobs, func(i, j int) bool { return jobs[i].last.After(jobs[j].last) }) + out.Total = len(jobs) + ctx, cancel := context.WithTimeout(ctx, budget) + defer cancel() + type found struct { + i int + hit sessions.Hit + ok bool + } + work := make(chan int) + results := make(chan found) + var wg sync.WaitGroup + for range min(4, max(1, runtime.NumCPU()/2)) { + wg.Add(1) + go func() { + defer wg.Done() + for i := range work { + var f found + f.i = i + s := jobs[i].s + if s.Gateway { + f.hit, f.ok, _ = sessions.SearchGateway(ctx, s.Agent, s.ID, needle) + } else { + f.hit, f.ok, _ = sessions.SearchSession(ctx, s, needle) + } + select { + case results <- f: + case <-ctx.Done(): + return + } + } + }() + } + go func() { + defer close(work) + for i := range jobs { + select { + case work <- i: + case <-ctx.Done(): + return + } + } + }() + go func() { wg.Wait(); close(results) }() + var hits []found + for f := range results { + if ctx.Err() != nil { + break + } + out.Searched++ + if f.ok { + hits = append(hits, f) + if len(hits) >= searchHitMax { + break + } + } + } + if out.Searched < out.Total { + out.Cut = true + } + cancel() + for range results { + // what the readers were on ends with the cancel + } + sort.Slice(hits, func(i, j int) bool { return hits[i].i < hits[j].i }) + for _, f := range hits { + out.Hits = append(out.Hits, searchHitJSON{ID: jobs[f.i].s.ID, Hit: f.hit}) + } + return out +} diff --git a/internal/gui/sessions_search_test.go b/internal/gui/sessions_search_test.go new file mode 100644 index 000000000..fdb321a20 --- /dev/null +++ b/internal/gui/sessions_search_test.go @@ -0,0 +1,132 @@ +package gui + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" + "github.com/yetone/magpie/internal/usage" +) + +// YOU on Discord: a session the gateway recorded is listed as ses_…, and the +// Sessions page's filter matched only titles, folders, ids and models, so +// one couldn't be found by what was said in it. It is titled by what it was +// first asked, and /api/sessions/search finds it by any words of it. +func TestSessionsSearchFindsGatewaySessionsByWhatWasSaid(t *testing.T) { + sandboxHome(t) + sessions.Reset() + t.Cleanup(sessions.Reset) + mux := http.NewServeMux() + sessionRoutes(mux, folderOnly{}) + sessionManageRoutes(mux, folderOnly{}) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/sessions/recording", strings.NewReader(`{"on":true}`))) + if w.Code != 200 { + t.Fatalf("consent: %d %s", w.Code, w.Body) + } + now := time.Now() + say := func(id, asked, answer string, at time.Time) { + t.Helper() + usage.Append(usage.Record{Time: at, Agent: "pi", Session: id, Provider: "fake", Model: "m", Status: 200}) + if err := sessions.SaveGatewayTurn(sessions.GatewayTurn{Agent: "pi", Session: id, Time: at, + Input: []sessions.Part{ + {Role: "system", Kind: "context", Text: "You are Pi. Never mention the word zebra."}, + {Role: "user", Kind: "text", Text: asked}, + }, + Output: []sessions.Part{{Role: "assistant", Kind: "text", Text: answer}}}); err != nil { + t.Fatal(err) + } + } + say("ses_old", "rename foo to bar in the parser", "Renamed it in parse.go.", now.Add(-2*time.Minute)) + say("ses_new", "why does the Parser panic on empty input?", "An index out of range in lex.go.", now.Add(-time.Minute)) + say("ses_none", "write a haiku", "Autumn moonlight", now) + + // the list says what each was asked, not its id + w = httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/sessions/manage?agent=pi", nil)) + var manage struct { + Sessions []struct{ ID, Title string } + } + if err := json.Unmarshal(w.Body.Bytes(), &manage); err != nil { + t.Fatal(err) + } + titles := map[string]string{} + for _, s := range manage.Sessions { + titles[s.ID] = s.Title + } + if titles["ses_old"] != "rename foo to bar in the parser" || titles["ses_none"] != "write a haiku" { + t.Fatalf("titles: %v", titles) + } + + search := func(q string) searchJSON { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/sessions/search?agent=pi&q="+q, nil)) + var out searchJSON + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil { + t.Fatalf("search %q: %d %s", q, w.Code, w.Body) + } + return out + } + got := search("PARSER") + if len(got.Hits) != 2 || got.Hits[0].ID != "ses_new" || got.Hits[1].ID != "ses_old" || got.Total != 3 || got.Searched != 3 || got.Cut { + t.Fatalf("parser: %+v", got) + } + if h := got.Hits[0]; h.Match != "Parser" || h.Before != "why does the " || h.Role != "user" { + t.Fatalf("snippet: %+v", h) + } + if got := search("lex.go"); len(got.Hits) != 1 || got.Hits[0].ID != "ses_new" || got.Hits[0].Role != "assistant" { + t.Fatalf("an answer's words: %+v", got) + } + // the system prompt every turn carries is not what was said + if got := search("zebra"); len(got.Hits) != 0 { + t.Fatalf("system prompt matched: %+v", got) + } + // one letter is no search + if got := search("a"); len(got.Hits) != 0 || got.Total != 0 { + t.Fatalf("one letter: %+v", got) + } + if got := search("haiku"); len(got.Hits) != 1 || got.Hits[0].ID != "ses_none" { + t.Fatalf("haiku: %+v", got) + } +} + +// A search that runs out of time, or whose page asked another, stops and +// says it was cut short rather than reading on. +func TestSessionsSearchStopsWhenItsRequestEnds(t *testing.T) { + sandboxHome(t) + sessions.Reset() + t.Cleanup(sessions.Reset) + mux := http.NewServeMux() + sessionManageRoutes(mux, folderOnly{}) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/sessions/recording", strings.NewReader(`{"on":true}`))) + for i, id := range []string{"ses_a", "ses_b", "ses_c"} { + at := time.Now().Add(time.Duration(i) * time.Second) + usage.Append(usage.Record{Time: at, Agent: "pi", Session: id, Provider: "fake", Model: "m", Status: 200}) + if err := sessions.SaveGatewayTurn(sessions.GatewayTurn{Agent: "pi", Session: id, Time: at, + Input: []sessions.Part{{Role: "user", Kind: "text", Text: "hello there"}}}); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + done := make(chan searchJSON, 1) + go func() { done <- searchSessions(ctx, "pi", "hello", time.Minute) }() + select { + case got := <-done: + if !got.Cut || len(got.Hits) != 0 || got.Total != 3 { + t.Fatalf("a cancelled search: %+v", got) + } + case <-time.After(10 * time.Second): + t.Fatal("a cancelled search didn't return") + } + if got := searchSessions(context.Background(), "pi", "hello", time.Minute); len(got.Hits) != 3 || got.Cut { + t.Fatalf("the same search, not cancelled: %+v", got) + } +} diff --git a/internal/gui/tests/sessions-manage.test.cjs b/internal/gui/tests/sessions-manage.test.cjs index 0d8005e6e..02da50e44 100644 --- a/internal/gui/tests/sessions-manage.test.cjs +++ b/internal/gui/tests/sessions-manage.test.cjs @@ -89,7 +89,7 @@ const words = { nav: "Sessions", del: "Delete", cancel: "Cancel", trash: "Trash", restore: "Restore", resume: "Resume", askOne: "Delete this session?", askTwo: "Delete 2 sessions?", moved: "2 sessions moved to magpie's trash", active: "still running is still being written to; close it in Claude Code and try again in a minute", - restored: "fix the login form restored", picked: "2 selected", filter: "Filter sessions", + restored: "fix the login form restored", picked: "2 selected", filter: "Search sessions", cant: "magpie can list OpenCode's sessions and resume them, but not delete them: they aren't kept as files of their own.", hermesNote: "These Hermes sessions are read only; magpie can list them, but cannot resume or delete them.", codexNote: "Some Codex sessions are read only and cannot be deleted.", @@ -99,7 +99,7 @@ const words = { nav: "会话", del: "删除", cancel: "取消", trash: "回收站", restore: "恢复", resume: "继续", askOne: "删除这个会话?", askTwo: "删除这 2 个会话?", moved: "2 个会话已移到 magpie 的回收站", active: "「still running」仍在写入;请在 Claude Code 中关闭它,一分钟后再试", - restored: "已恢复「fix the login form」", picked: "已选 2 个", filter: "筛选会话", + restored: "已恢复「fix the login form」", picked: "已选 2 个", filter: "搜索会话", cant: "可列出并继续 OpenCode 的会话,但无法删除:它们没有独立文件。", hermesNote: "这些 Hermes 会话只读:可列出,但无法继续或删除。", codexNote: "部分 Codex 会话为只读,无法删除。", @@ -257,7 +257,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", } const missing = await page.evaluate(() => [ - "Sessions", "Filter sessions", "No sessions yet", "Select every session shown", "Select", "Delete", "Trash", "No folder", "deleted {when}", + "Sessions", "Search sessions", "No sessions yet", "Select every session shown", "Select", "Delete", "Trash", "No folder", "deleted {when}", "Delete this session?", "Delete {n} sessions?", "Moved to magpie's trash", "{n} sessions moved to magpie's trash", "Restore", "{title} restored", "{title} is still being written to; close it in {agent} and try again in a minute", "{n} sessions are still being written to; close them in {agent} and try again in a minute", diff --git a/internal/gui/tests/sessions-search.test.cjs b/internal/gui/tests/sessions-search.test.cjs new file mode 100644 index 000000000..74278ccff --- /dev/null +++ b/internal/gui/tests/sessions-search.test.cjs @@ -0,0 +1,168 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Sessions page's filter finds a session by what was said in it, not only +// by its title, folder, id or model (YOU on Discord: the gateway's sessions +// are named ses_…, and their words are how they are remembered). The page +// asks /api/sessions/search once typing pauses, a new query cancels the one +// in flight, one letter asks nothing, and each session found shows the words +// round its match, the match marked. A search cut short, or of an agent +// whose own files can't be read, says so. In every language, Chromium and +// WebKit, wide and narrow. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const at = (min) => new Date(Date.now() - min * 60e3).toISOString(); +const gw = (id, title, min) => ({ + agent: "pi", id, cwd: "", title, gateway: true, start: at(min + 5), last: at(min), models: [{ model: "m" }], size: 2048, deletable: true, +}); +// what each session said, as the server would search it +const said = { + "ses_01": "rename foo to bar in the parser", + "ses_02": "why does the build fail? The Redis client times out after 30 seconds on every request to the cache, and only in CI, never on a laptop", + "ses_03": "write a haiku about Kafka and autumn", +}; + +function serve(lang, log) { + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + const sessions = [gw("ses_03", "write a haiku about Kafka and autumn", 1), gw("ses_02", "why does the build fail?", 5), gw("ses_01", "rename foo to bar in the parser", 9)]; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/sessions/manage") { + return json({ + agents: [{ agent: "pi", count: sessions.length, deletable: true, name: "Pi", icon: "pi" }], + agent: "pi", sessions, terminal: false, trash: [], trashDir: "~/trash", recording: true, recorded: true, + }); + } + if (url.pathname === "/api/sessions/search") { + const q = url.searchParams.get("q"); + log.push({ agent: url.searchParams.get("agent"), q }); + // long enough for the next keystroke to land while it is out + await new Promise((r) => setTimeout(r, log.slow ? 900 : 250)); + const hits = []; + for (const [id, text] of Object.entries(said)) { + const i = text.toLowerCase().indexOf(q); + if (i >= 0) { + const after = text.slice(i + q.length); + hits.push({ id, role: "user", kind: "text", before: text.slice(0, i), match: text.slice(i, i + q.length), after: after.length > 60 ? after.slice(0, 60) + "…" : after }); + } + } + return route.fulfill({ json: { hits, searched: log.cut ? 2 : 3, total: 3, cut: !!log.cut } }).catch(() => {}); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType }); + }; +} + +const KEYS = [ + "Search sessions", "Searching what was said…", "Searched what was said in the latest {n} of {total} sessions.", + "Couldn't search what was said: {error}", + "{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.", +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: the filter finds sessions by what was said`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const [lang, width] of [["en", 1100], ["zh", 1100], ["zh-TW", 560], ["ja", 560], ["de", 420]]) { + await t.test(`${lang} at ${width}`, async () => { + const context = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const aborted = []; + page.on("requestfailed", (r) => { if (r.url().includes("/api/sessions/search")) aborted.push(new URL(r.url()).searchParams.get("q")); }); + const log = []; + await page.route("**/*", serve(lang, log)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator('#nav [data-view="sessions"]').first().click(); + const view = page.locator("#view-sessions"); + const row = (id) => view.locator(`.row.sm-sess[data-id="${id}"]`); + await row("ses_03").waitFor(); + const filter = view.locator(".sm-filter"); + const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]); + + // a gateway session is titled by what it was asked, its id beside + assert.equal(await row("ses_02").locator(".name").textContent(), "why does the build fail?"); + assert.match(await row("ses_02").locator(".sub").first().textContent(), /ses_02/); + assert.equal(await filter.getAttribute("placeholder"), await tr("Search sessions")); + + // one letter asks nothing; typing asks once, when it pauses + await filter.pressSequentially("r", { delay: 20 }); + await page.waitForTimeout(500); + assert.equal(log.length, 0, "one letter is no search"); + await filter.pressSequentially("edis", { delay: 40 }); + await view.locator(".sm-search-note").waitFor(); + assert.equal(await view.locator(".sm-search-note").textContent(), await tr("Searching what was said…")); + await row("ses_02").locator(".sm-hit mark").waitFor(); + assert.deepEqual(log.map((x) => x.q), ["redis"], "one request for the word typed"); + assert.equal(log[0].agent, "pi"); + assert.equal(await row("ses_02").locator(".sm-hit mark").textContent(), "Redis"); + assert.equal(await row("ses_03").count(), 0, "a session that didn't say it is left out"); + assert.equal(await view.locator(".sm-search-note").count(), 0, "nothing more to say once found"); + // the words round it stay on one line, inside the page + const fit = await row("ses_02").evaluate((r) => { + const hit = r.querySelector(".sm-hit"); + return { lines: Math.round(hit.getBoundingClientRect().height / parseFloat(getComputedStyle(hit).lineHeight || "15")), right: hit.getBoundingClientRect().right, page: document.querySelector("#view-sessions").getBoundingClientRect().right, over: document.documentElement.scrollWidth > innerWidth }; + }); + assert.ok(fit.right <= fit.page + 1 && !fit.over, `the snippet overflows: ${JSON.stringify(fit)}`); + + // a new query cancels the one in flight, and its answer never shows + log.slow = true; + await filter.fill("parser"); + await page.waitForTimeout(450); // past the pause: its request is out + await filter.fill("kafka"); + await row("ses_03").locator(".sm-hit mark").waitFor(); + await page.waitForTimeout(1000); + assert.deepEqual(log.slice(1).map((x) => x.q), ["parser", "kafka"]); + assert.deepEqual(aborted, ["parser"], "the earlier search was cancelled"); + assert.equal(await row("ses_01").count(), 0, "the cancelled search's answer isn't shown"); + assert.equal(await row("ses_03").locator(".sm-hit mark").textContent(), "Kafka"); + + // what a title or id matches is shown at once, before any answer + log.slow = false; + log.cut = true; + await filter.fill("ses_01"); + await row("ses_01").waitFor({ timeout: 200 }); + // a search cut short says how far it read + await view.locator(".sm-search-note").filter({ hasText: await tr("Searched what was said in the latest {n} of {total} sessions.", { n: 2, total: 3 }) }).waitFor(); + + // nothing found anywhere: no session matches, after the search + await filter.fill("zebra"); + await view.locator(".empty-state").waitFor(); + assert.equal(await view.locator(".empty-state").textContent(), await tr("No session matches.")); + + // Escape clears it and the list is whole again + await filter.press("Escape"); + await row("ses_01").waitFor(); + assert.equal(await view.locator(".sm-hit").count(), 0); + assert.equal(await view.locator(".sm-search-note").count(), 0); + + if (lang !== "en") { + const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang]?.[k]), [lang, KEYS]); + assert.deepEqual(missing, [], `${lang} has every string`); + } + if (process.env.SCREENSHOT_DIR) { + await filter.fill("redis"); + await row("ses_02").locator(".sm-hit mark").waitFor(); + await fs.mkdir(process.env.SCREENSHOT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.SCREENSHOT_DIR, `${engine}-${lang}-${width}-sessions-search.png`) }); + } + assert.deepEqual(errors, []); + await context.close(); + }); + } + }); +} diff --git a/internal/sessions/content.go b/internal/sessions/content.go index c8d2fef5a..855c2662f 100644 --- a/internal/sessions/content.go +++ b/internal/sessions/content.go @@ -126,10 +126,19 @@ type ccBlock struct { // lines of its own message what it said. add is told each part, and says // whether to read on. func claudeContent(c Call, add func(input bool, p Part) bool) error { + return claudeContentOf(c, nil, add) +} + +// claudeContentOf is claudeContent reading only the lines keep (when given) +// says yes to: a search's cheap test of a line's bytes before it is decoded. +func claudeContentOf(c Call, keep func([]byte) bool, add func(input bool, p Part) bool) error { _, err := scanAt(c.File, c.From, nil, func(b []byte, start, end int64) bool { if start >= c.To { return false } + if keep != nil && !keep(b) { + return true + } user := bytes.Contains(b, ccUserLine) asst := bytes.Contains(b, ccAssistant) if !user && !asst { @@ -247,6 +256,12 @@ var cxItem = []byte(`"type":"response_item"`) // unpacked) since the call was read is read in its new form: its lines and // their places are the same. add is as claudeContent's. func codexContent(c Call, add func(input bool, p Part) bool) error { + return codexContentOf(c, nil, add) +} + +// codexContentOf is codexContent reading only the lines keep (when given) +// says yes to, as claudeContentOf. +func codexContentOf(c Call, keep func([]byte) bool, add func(input bool, p Part) bool) error { path := c.File if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { if _, err := os.Stat(rolloutTwin(path)); err == nil { @@ -260,6 +275,9 @@ func codexContent(c Call, add func(input bool, p Part) bool) error { if !bytes.Contains(b, cxItem) { return true } + if keep != nil && !keep(b) { + return true + } var l struct { Payload struct { Type string `json:"type"` diff --git a/internal/sessions/external.go b/internal/sessions/external.go index bd2e6022c..5c32b9924 100644 --- a/internal/sessions/external.go +++ b/internal/sessions/external.go @@ -1,6 +1,7 @@ package sessions import ( + "cmp" "math" "slices" "sort" @@ -18,6 +19,7 @@ type ExternalModel struct { } type ExternalSession struct { Agent, ID string + Title string // what it was first asked (GatewayTitle); its id when "" Start, Last time.Time Models []ExternalModel Daily []ExternalDayUsage @@ -40,7 +42,7 @@ func MergeExternal(native []Session, external []ExternalSession) []Session { if e.Agent == "" || e.ID == "" || seen[e.Agent+"|"+e.ID] { continue } - s := Session{ReadOnly: true, Gateway: true, Transcript: true, Agent: e.Agent, ID: e.ID, Title: e.ID, Start: e.Start, Last: e.Last, Models: []Model{}, Unpriced: e.Unpriced} + s := Session{ReadOnly: true, Gateway: true, Transcript: true, Agent: e.Agent, ID: e.ID, Title: cmp.Or(e.Title, e.ID), Start: e.Start, Last: e.Last, Models: []Model{}, Unpriced: e.Unpriced} for _, m := range e.Models { s.Models = append(s.Models, Model{Model: m.Model, Tokens: m.Tokens, Cost: m.Cost, Priced: m.Priced}) s.Tokens.add(m.Tokens) @@ -119,7 +121,7 @@ func MergeExternalStats(st Stats, days []ExternalDayUsage, external []ExternalSe if e.ID == "" || e.Agent == "" { continue } - s := Summary{Key: e.Agent + ":" + e.ID, Agent: e.Agent, ID: e.ID, Last: e.Last, Tokens: e.Tokens, Cost: e.Cost, Priced: true, Models: []string{}, Days: []int{}, perDay: map[int]*summaryDay{}} + s := Summary{Key: e.Agent + ":" + e.ID, Agent: e.Agent, ID: e.ID, Title: e.Title, Last: e.Last, Tokens: e.Tokens, Cost: e.Cost, Priced: true, Models: []string{}, Days: []int{}, perDay: map[int]*summaryDay{}} for _, u := range e.Daily { day, err := time.ParseInLocation(time.DateOnly, u.Date, time.Local) if err != nil { diff --git a/internal/sessions/search.go b/internal/sessions/search.go new file mode 100644 index 000000000..9a4f3e690 --- /dev/null +++ b/internal/sessions/search.go @@ -0,0 +1,389 @@ +package sessions + +// Searching what was said: the Sessions page's filter finds a session by a +// word of its conversation, not only by its title, folder, id or model +// (YOU on Discord: gateway sessions are named ses_…, and what was said is +// how they are remembered). Each session's own file is read only as far as +// its first match; a file that doesn't hold the words at all, as bytes, is +// left after one pass without decoding a line of it. + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + "unicode" + "unicode/utf8" +) + +// Hit is where a session said what was searched for: a few words either +// side of the match, on one line. +type Hit struct { + Role string `json:"role"` + Kind string `json:"kind"` + Before string `json:"before"` + Match string `json:"match"` + After string `json:"after"` +} + +const ( + hitBefore = 36 // runes kept before a match + hitAfter = 120 // and after it +) + +// errFound stops a read at the first match a reader would want. +var errFound = errors.New("found") + +// fold is a text lowered rune by rune, so a rune's index in it is its index +// in the text itself. +func fold(s string) string { + var b strings.Builder + b.Grow(len(s)) + for _, r := range s { + b.WriteRune(unicode.ToLower(r)) + } + return b.String() +} + +// NeedleOf is a query as it is matched: lowered, its spaces made one. +func NeedleOf(q string) string { + return fold(strings.Join(strings.Fields(q), " ")) +} + +// hitIn finds needle (from NeedleOf) in a part's text, its spaces taken as +// one, and cuts the snippet round it. +func hitIn(p Part, needle string) (Hit, bool) { + if needle == "" || p.Text == "" { + return Hit{}, false + } + text := []rune(strings.Join(strings.Fields(p.Text), " ")) + low := fold(string(text)) + i := strings.Index(low, needle) + if i < 0 { + return Hit{}, false + } + at := utf8.RuneCountInString(low[:i]) + n := utf8.RuneCountInString(needle) + from, to := max(0, at-hitBefore), min(len(text), at+n+hitAfter) + h := Hit{Role: p.Role, Kind: p.Kind, Before: string(text[from:at]), Match: string(text[at : at+n]), After: string(text[at+n : to])} + if from > 0 { + h.Before = "…" + strings.TrimLeft(h.Before, " ") + } + if to < len(text) { + h.After = strings.TrimRight(h.After, " ") + "…" + } + return h, true +} + +// said says whether a part is something the user or the model said, a +// match there worth more than one in a tool's output or the model's thoughts. +func said(p Part) bool { + return p.Kind == "text" && (p.Role == "user" || p.Role == "assistant") +} + +// searched says whether a part is read at all: not the context an agent +// sends before every request, nor an image. +func searched(p Part) bool { + return p.Role != "system" && p.Kind != "context" && p.Kind != "image" +} + +// matcher keeps the best hit of the parts it is told: the first said, else +// the first anywhere. +type matcher struct { + needle string + hit Hit + found bool +} + +// add takes a part; false once the hit can't be bettered. +func (m *matcher) add(p Part) bool { + if !searched(p) { + return true + } + if m.found && !said(p) { + return true + } + h, ok := hitIn(p, m.needle) + if !ok { + return true + } + m.hit, m.found = h, true + return !said(p) +} + +// rawNeedle is what of the needle an agent's file must hold byte for byte, +// when it can be told: its longest word, of words with nothing JSON +// escapes. (A space in the query may be a line break or a run of them in +// the file, but each word is there as typed.) Otherwise "", and the file is +// read whole. +func rawNeedle(needle string) string { + for _, r := range needle { + if r < 0x20 || r == '"' || r == '\\' || r == '<' || r == '>' || r == '&' || r == 0x2028 || r == 0x2029 || r == utf8.RuneError { + return "" + } + // a letter whose capital lowers to more or fewer bytes, or a + // writer that escapes what isn't ASCII, could hide it from bytes + if r >= utf8.RuneSelf && !unicode.Is(unicode.Han, r) && !unicode.In(r, unicode.Hiragana, unicode.Katakana, unicode.Hangul) { + return "" + } + } + long := "" + for _, w := range strings.Fields(needle) { + if len(w) > len(long) { + long = w + } + } + return long +} + +// mayHold says whether a file can hold needle at all, read as bytes in +// lowered chunks; a packed file or one not read says yes. +func mayHold(ctx context.Context, path, needle string) bool { + if needle == "" || packed(path) { + return true + } + f, err := os.Open(path) + if err != nil { + return true + } + defer f.Close() + nb := []byte(needle) + keep := len(nb) - 1 + buf := make([]byte, 1<<20+keep) + have := 0 + for { + if ctx.Err() != nil { + return true + } + n, err := io.ReadFull(f, buf[have:]) + have += n + if containsFold(buf[:have], nb) { + return true + } + if err != nil { + return !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) + } + copy(buf, buf[have-keep:have]) + have = keep + } +} + +// containsFold says whether b holds needle, A–Z in b taken as a–z; needle +// is lowered already, and what in it isn't ASCII is caseless (rawNeedle). +// It copies nothing: candidates are found by the first byte in either case. +func containsFold(b, needle []byte) bool { + if len(needle) == 0 { + return true + } + first := needle[0] + upper := first + if 'a' <= first && first <= 'z' { + upper = first - 'a' + 'A' + } + for len(b) >= len(needle) { + i := bytes.IndexByte(b[:len(b)-len(needle)+1], first) + if upper != first { + if k := bytes.IndexByte(b[:len(b)-len(needle)+1], upper); k >= 0 && (i < 0 || k < i) { + i = k + } + } + if i < 0 { + return false + } + if equalFoldASCII(b[i:i+len(needle)], needle) { + return true + } + b = b[i+1:] + } + return false +} + +// equalFoldASCII says whether a, with A–Z lowered, is lower. +func equalFoldASCII(a, lower []byte) bool { + for i, c := range a { + if 'A' <= c && c <= 'Z' { + c += 'a' - 'A' + } + if c != lower[i] { + return false + } + } + return true +} + +// SearchSession finds needle (from NeedleOf) in what a session said, read +// from its agent's own file; ErrNoTranscript for an agent whose +// conversations aren't read. +func SearchSession(ctx context.Context, s Session, needle string) (Hit, bool, error) { + if !HasTranscript(s.Agent) || s.Path == "" { + return Hit{}, false, ErrNoTranscript + } + raw := rawNeedle(needle) + if !mayHold(ctx, s.Path, raw) { + return Hit{}, false, nil + } + var keep func([]byte) bool + if raw != "" { + // only a line holding every word is decoded: in a long session + // most lines are tool output that doesn't, and a part is a line's + var words [][]byte + for _, w := range strings.Fields(needle) { + words = append(words, []byte(w)) + } + keep = func(b []byte) bool { + for _, w := range words { + if !containsFold(b, w) { + return false + } + } + return true + } + } + m := matcher{needle: needle} + err := readTranscriptOf(s, keep, func(_ bool, p Part) bool { + return ctx.Err() == nil && m.add(p) + }) + if err == nil { + err = ctx.Err() + } + return m.hit, m.found, err +} + +// SearchGateway finds needle in what magpie recorded of a gateway session, +// the parts as its transcript shows them. +func SearchGateway(ctx context.Context, agent, id, needle string) (Hit, bool, error) { + if err := ctx.Err(); err != nil { + return Hit{}, false, err + } + t, err := GatewayTranscript(agent, id) + if err != nil { + return Hit{}, false, err + } + m := matcher{needle: needle} + for _, p := range t.Parts { + if !m.add(p) { + break + } + } + return m.hit, m.found, nil +} + +// ---- a gateway session's title ---------------------------------------------- + +// gatewayTitles keeps a recorded session's title by the file it was read +// from: its first line is written once and never again. +var gatewayTitles sync.Map // path -> string + +const gatewayTitleLines = 8 + +// GatewayTitle is what a gateway session was first asked, made one short +// line, from the first turns magpie recorded of it; "" when it recorded +// none or nothing the user wrote. +func GatewayTitle(agent, id string) string { + if agent == "" || id == "" { + return "" + } + if _, err := os.Stat(gatewayDir()); err != nil { + return "" // nothing recorded at all, as for most + } + gatewayMu.Lock() + defer gatewayMu.Unlock() + now := time.Now().UTC() + for d := 7; d >= 0; d-- { + dir := filepath.Join(gatewayDir(), now.AddDate(0, 0, -d).Format(time.DateOnly), gatewayIdentity(agent, id)) + entries, err := os.ReadDir(dir) + if err != nil { + continue + } + var names []string + for _, e := range entries { + if e.Type().IsRegular() && (strings.HasSuffix(e.Name(), ".json") || e.Name() == "turns.jsonl") { + names = append(names, e.Name()) + } + } + // the per-turn files of before are older than a day's turns.jsonl + sort.Slice(names, func(i, j int) bool { + if (names[i] == "turns.jsonl") != (names[j] == "turns.jsonl") { + return names[j] == "turns.jsonl" + } + return names[i] < names[j] + }) + for _, name := range names { + path := filepath.Join(dir, name) + if t, ok := gatewayTitles.Load(path); ok { + if t != "" { + return t.(string) + } + continue + } + t, whole := gatewayFileTitle(path, agent, id) + if t != "" || whole { + gatewayTitles.Store(path, t) + } + if t != "" { + return t + } + } + } + return "" +} + +// gatewayFileTitle reads a recorded file's first turns for the user's first +// words; whole says the answer won't change as the file grows. +func gatewayFileTitle(path, agent, id string) (title string, whole bool) { + f, err := os.Open(path) + if err != nil { + return "", false + } + defer f.Close() + info, err := f.Stat() + if err != nil { + return "", false + } + end, err := gatewayCompleteSize(f, info.Size()) + if err != nil { + return "", false + } + scan := bufio.NewScanner(io.LimitReader(f, end)) + scan.Buffer(make([]byte, 64<<10), gatewayTurnMax+1) + lines := 0 + for scan.Scan() { + lines++ + var turn GatewayTurn + if json.Unmarshal(scan.Bytes(), &turn) == nil && turn.Agent == agent && turn.Session == id { + if t := firstAsked(turn.Input); t != "" { + return t, true + } + } + if lines >= gatewayTitleLines { + return "", true + } + } + return "", !strings.HasSuffix(path, ".jsonl") +} + +// firstAsked is the first thing the user wrote in a request: not a tag an +// agent wraps its context in, nor an image. +func firstAsked(parts []Part) string { + for _, p := range parts { + if p.Role != "user" || p.Kind != "text" { + continue + } + s := strings.TrimSpace(p.Text) + if s == "" || strings.HasPrefix(s, "<") || strings.HasPrefix(s, "# AGENTS.md") || s == "[image]" { + continue + } + if t := untagged(s); t != "" { + return t + } + } + return "" +} diff --git a/internal/sessions/search_test.go b/internal/sessions/search_test.go new file mode 100644 index 000000000..599b84761 --- /dev/null +++ b/internal/sessions/search_test.go @@ -0,0 +1,236 @@ +package sessions + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// claudeFile writes a Claude Code session of the given lines and returns it +// as a session to read. +func claudeFile(t *testing.T, lines ...string) Session { + t.Helper() + path := filepath.Join(t.TempDir(), "11111111-2222-3333-4444-555555555555.jsonl") + if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + return Session{Agent: "claude", ID: "11111111-2222-3333-4444-555555555555", Path: path} +} + +const ( + claudeAsked = `{"type":"user","message":{"role":"user","content":"Fix the login\nbug in Auth.go please"},"uuid":"u1"}` + claudeTool = `{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"grep -r rainbow ."}}]},"uuid":"a1"}` + claudeSaid = `{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"The rainbow table lookup in auth.go skips the salt."}]},"uuid":"a2"}` +) + +func TestSearchSessionFindsWhatWasSaid(t *testing.T) { + s := claudeFile(t, claudeAsked, claudeTool, claudeSaid) + ctx := context.Background() + + // case and the spaces of a line break don't matter + h, ok, err := SearchSession(ctx, s, NeedleOf("LOGIN bug")) + if err != nil || !ok { + t.Fatalf("not found: %v %v", ok, err) + } + if h.Role != "user" || h.Before != "Fix the " || h.Match != "login bug" || h.After != " in Auth.go please" { + t.Fatalf("hit: %+v", h) + } + + // a word in a tool's call and in what the model said: the said one is shown + h, ok, err = SearchSession(ctx, s, NeedleOf("rainbow")) + if err != nil || !ok || h.Role != "assistant" || h.Kind != "text" || h.Match != "rainbow" { + t.Fatalf("said hit: %+v %v %v", h, ok, err) + } + + if _, ok, err := SearchSession(ctx, s, NeedleOf("kubernetes")); ok || err != nil { + t.Fatalf("found what wasn't said: %v %v", ok, err) + } +} + +func TestSearchSessionCutsALongPart(t *testing.T) { + long := strings.Repeat("alpha ", 40) + "needle" + strings.Repeat(" omega", 60) + s := claudeFile(t, `{"type":"user","message":{"role":"user","content":"`+long+`"},"uuid":"u1"}`) + h, ok, err := SearchSession(context.Background(), s, NeedleOf("needle")) + if err != nil || !ok { + t.Fatalf("not found: %v %v", ok, err) + } + if !strings.HasPrefix(h.Before, "…") || !strings.HasSuffix(h.After, "…") { + t.Fatalf("a long part's snippet should show it was cut: %+v", h) + } + if n := len([]rune(h.Before)); n > hitBefore+1 { + t.Fatalf("before is %d runes", n) + } + if n := len([]rune(h.After)); n > hitAfter+1 { + t.Fatalf("after is %d runes", n) + } +} + +func TestSearchSessionWithoutATranscript(t *testing.T) { + if _, _, err := SearchSession(context.Background(), Session{Agent: "cursor", Path: "x"}, "a"); err != ErrNoTranscript { + t.Fatalf("err = %v", err) + } +} + +func TestMayHoldSkipsAFileWithoutTheWords(t *testing.T) { + ctx := context.Background() + s := claudeFile(t, claudeAsked, claudeSaid) + if !mayHold(ctx, s.Path, rawNeedle(NeedleOf("AUTH.GO"))) { + t.Fatal("a file holding the words, in another case, said no") + } + if mayHold(ctx, s.Path, rawNeedle(NeedleOf("kubernetes"))) { + t.Fatal("a file without the words said yes") + } + // a needle the file may hold escaped reads it + for _, q := range []string{`say "hi"`, "café"} { + if rawNeedle(NeedleOf(q)) != "" { + t.Fatalf("%q is matched as raw bytes", q) + } + } + // words a line break may part in the file are looked for by the longest + if got := rawNeedle(NeedleOf("the Login bug")); got != "login" { + t.Fatalf("raw of words = %q", got) + } + if !mayHold(ctx, s.Path, rawNeedle(NeedleOf("login bug"))) { + t.Fatal("words parted by a line break in the file said no") + } + if rawNeedle(NeedleOf("登录")) == "" { + t.Fatal("Han is written as itself") + } + // a match across the edge of two chunks is still seen + path := filepath.Join(t.TempDir(), "big.jsonl") + body := make([]byte, 1<<20+10) + for i := range body { + body[i] = 'x' + } + copy(body[1<<20-3:], "NEEDLE") + if err := os.WriteFile(path, body, 0o600); err != nil { + t.Fatal(err) + } + if !mayHold(ctx, path, "needle") { + t.Fatal("a match across two chunks was missed") + } +} + +func TestSearchSessionStopsWhenCancelled(t *testing.T) { + s := claudeFile(t, claudeAsked, claudeSaid) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, ok, err := SearchSession(ctx, s, NeedleOf("login")); ok || err == nil { + t.Fatalf("a cancelled search went on: %v %v", ok, err) + } +} + +func TestGatewayTitleAndSearch(t *testing.T) { + gatewayHome(t) + if err := SetGatewayRecording(true, false); err != nil { + t.Fatal(err) + } + if got := GatewayTitle("pi", "ses_1"); got != "" { + t.Fatalf("a session never recorded has title %q", got) + } + at := time.Now().UTC() + turn := GatewayTurn{Agent: "pi", Session: "ses_1", Time: at, + Input: []Part{ + {Role: "system", Kind: "context", Text: "You are a helpful assistant. Deploy carefully."}, + {Role: "user", Kind: "text", Text: "today is Monday"}, + {Role: "user", Kind: "text", Text: " Deploy the staging\nserver tonight "}, + }, + Output: []Part{{Role: "assistant", Kind: "text", Text: "Deploying staging now."}}, + } + if err := SaveGatewayTurn(turn); err != nil { + t.Fatal(err) + } + later := GatewayTurn{Agent: "pi", Session: "ses_1", Time: at.Add(time.Second), + Input: []Part{{Role: "user", Kind: "text", Text: "and what about prod?"}}} + if err := SaveGatewayTurn(later); err != nil { + t.Fatal(err) + } + if got := GatewayTitle("pi", "ses_1"); got != "Deploy the staging server tonight" { + t.Fatalf("title = %q", got) + } + if got := GatewayTitle("pi", "ses_other"); got != "" { + t.Fatalf("another session's title = %q", got) + } + + ctx := context.Background() + h, ok, err := SearchGateway(ctx, "pi", "ses_1", NeedleOf("staging server")) + if err != nil || !ok || h.Role != "user" || h.Match != "staging server" { + t.Fatalf("hit: %+v %v %v", h, ok, err) + } + // the system prompt an agent sends every time isn't what was said + if _, ok, _ := SearchGateway(ctx, "pi", "ses_1", NeedleOf("helpful assistant")); ok { + t.Fatal("matched the system prompt") + } + if _, ok, _ := SearchGateway(ctx, "pi", "ses_1", NeedleOf("prod?")); !ok { + t.Fatal("a later turn wasn't searched") + } +} + +func TestContainsFold(t *testing.T) { + for _, c := range []struct { + b, needle string + want bool + }{ + {"The Redis cache", "redis", true}, + {"THE REDIS CACHE", "redis", true}, + {"rRedis", "redis", true}, + {"rediS", "redis", true}, + {"redi", "redis", false}, + {"Rxdis redix", "redis", false}, + {"登录失败", "登录", true}, + {"登", "登录", false}, + {"", "a", false}, + {"abc", "", true}, + } { + if got := containsFold([]byte(c.b), []byte(c.needle)); got != c.want { + t.Errorf("containsFold(%q, %q) = %v", c.b, c.needle, got) + } + } +} + +// A search decodes only the lines holding the words, in either case, and +// still finds them in a Codex file as in a Claude one. +func TestSearchSessionReadsOnlyLinesWithTheWords(t *testing.T) { + item := func(payload string) string { + return `{"timestamp":"2026-09-20T10:00:00.000Z","type":"response_item","payload":` + payload + `}` + } + path := filepath.Join(t.TempDir(), "rollout-2026-09-20T10-00-00-0190aaaa-1111-7222-8333-444455556666.jsonl") + lines := []string{ + item(`{"type":"message","role":"user","content":[{"type":"input_text","text":"List the files"}]}`), + item(`{"type":"function_call_output","call_id":"c1","output":"` + strings.Repeat("noise ", 2000) + `"}`), + item(`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"The ZEBRA crossing file is b.go."}]}`), + } + if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + s := Session{Agent: "codex", ID: "0190aaaa-1111-7222-8333-444455556666", Path: path} + h, ok, err := SearchSession(context.Background(), s, NeedleOf("zebra")) + if err != nil || !ok || h.Role != "assistant" || h.Match != "ZEBRA" || h.Before != "The " { + t.Fatalf("codex hit: %+v %v %v", h, ok, err) + } + + // read whole, every line's part is decoded; with the filter, only the + // part of the line holding the words + count := func(keep func([]byte) bool) int { + n := 0 + if err := readTranscriptOf(s, keep, func(bool, Part) bool { n++; return true }); err != nil { + t.Fatal(err) + } + return n + } + if n := count(nil); n != 3 { + t.Fatalf("read whole: %d parts", n) + } + if n := count(func(b []byte) bool { return containsFold(b, []byte("zebra")) }); n != 1 { + t.Fatalf("filtered: %d parts", n) + } + + // a Claude line whose only match is in capitals is kept + c := claudeFile(t, claudeTool, `{"type":"user","message":{"role":"user","content":"Use KUBERNETES now"},"uuid":"u2"}`) + if h, ok, err := SearchSession(context.Background(), c, NeedleOf("kubernetes")); err != nil || !ok || h.Match != "KUBERNETES" { + t.Fatalf("claude hit: %+v %v %v", h, ok, err) + } +} diff --git a/internal/sessions/transcript.go b/internal/sessions/transcript.go index b698a6bb5..22093625d 100644 --- a/internal/sessions/transcript.go +++ b/internal/sessions/transcript.go @@ -63,14 +63,21 @@ func TranscriptOf(s Session) (Transcript, error) { // readTranscript tells add each part of a session's conversation, in order, // as its agent's file has it. func readTranscript(s Session, add func(bool, Part) bool) error { + return readTranscriptOf(s, nil, add) +} + +// readTranscriptOf is readTranscript decoding only the lines keep says yes +// to, where a line stands alone (Claude's, Codex's); Pi's lines are a tree, +// read whole. +func readTranscriptOf(s Session, keep func([]byte) bool, add func(bool, Part) bool) error { whole := Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64} switch s.Agent { case "codex": - return codexContent(whole, add) + return codexContentOf(whole, keep, add) case "pi", "omp": return piTranscript(s.Path, add) default: - return claudeContent(whole, add) + return claudeContentOf(whole, keep, add) } }