From 9935119f1d68046e7efb1b809d034d804b9e7fa7 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 13 Oct 2026 06:17:31 +0800 Subject: [PATCH] sessions: search finds Cursor and OpenCode sessions read from their stores, and a Cursor chat's system prompt isn't shown as said (#1743) Follow-up to liubing's #1743 patch, which put cursor and opencode in HasTranscript. That moved their search from magpie's recorded transcript to SearchSession, whose byte prefilter (mayHold) reads s.Path. For these agents s.Path isn't the conversation: - OpenCode's JSON storage: the session info file, without messages, so every word missed; - OpenCode's and Cursor's SQLite stores: the newest pages are in the -wal, so a live chat's latest turns missed. linesFile now skips the prefilter for them (a Cursor .jsonl still gets it). cursorTranscript also handed the CLI store's system message ("You are a coding agent.") to the transcript as a said part; system messages are skipped, as the listing already does. The patch's tests commit left TestSearchSessionWithoutATranscript red (it used cursor as the agent without a transcript; now gemini). sessions-empty-range.test.cjs runs in every language, de at 420px. Run: go test -tags nogui -count=1 ./internal/sessions/ ok, and -race ok; sessions-empty-range 10/10 (Chromium+WebKit, en zh zh-TW ja de); sessions-today/overview/toolbar/search/manage/calendar-fill/paging GUI tests pass. Broken by hand: prefilter always on -> TestSearchOpenCodeFiles and TestSearchCursorLiveChat red; system skip removed -> TestSearchCursorLiveChat red. Also broke the patch itself: editor files not appended, readOnly Delete guard, stats message dates, CLI dedupe, HasTranscript entries, parseCursor readOnly dispatch, and the "All sessions" button (via MAGPIE_TEST_APP_JS); each went red. Co-authored-by: liubing --- docs/subsystems/gateway-sessions.md | 5 +- .../gui/tests/sessions-empty-range.test.cjs | 8 +-- internal/sessions/cursor_editor.go | 4 ++ internal/sessions/search.go | 16 ++++- internal/sessions/search_db_test.go | 67 +++++++++++++++++++ internal/sessions/search_test.go | 2 +- 6 files changed, 95 insertions(+), 7 deletions(-) create mode 100644 internal/sessions/search_db_test.go diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index e4fe2f2f2..96b8b7b9d 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -158,7 +158,10 @@ 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 +skipped for zstd files, for queries JSON may escape, and for a session whose +path isn't the file its conversation is in, `linesFile`: an OpenCode session's +info file or database, a Cursor chat's SQLite store, whose newest pages sit in +its `-wal`; `search_db_test.go`), 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 diff --git a/internal/gui/tests/sessions-empty-range.test.cjs b/internal/gui/tests/sessions-empty-range.test.cjs index 86028eefd..1dc5a5ae9 100644 --- a/internal/gui/tests/sessions-empty-range.test.cjs +++ b/internal/gui/tests/sessions-empty-range.test.cjs @@ -10,11 +10,11 @@ const old = "2026-01-01T12:00:00Z"; const session = { agent: "opencode", id: "old-chat", name: "OpenCode", title: "Historical conversation", cwd: "/work", start: old, last: old, models: [], input: 0, output: 0, cost: 0, resume: "", path: "/test/opencode.db#old-chat" }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { - for (const lang of ["en", "zh"]) { - test(`${engine} ${lang}: empty Today offers existing history without changing the agent`, async (t) => { + for (const [lang, all, width] of [["en", "All", 900], ["zh", "全部", 900], ["zh-TW", "全部", 900], ["ja", "すべて", 900], ["de", "Alle", 420]]) { + test(`${engine} ${lang} ${width}px: empty Today offers existing history without changing the agent`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); - const page = await browser.newPage(); + const page = await browser.newPage({ viewport: { width, height: 760 } }); page.setDefaultTimeout(8000); await page.route("**/*", async (route) => { const url = new URL(route.request().url()); @@ -38,7 +38,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator("#sessStats .sess-show-history").click(); await page.getByText("Historical conversation", { exact: true }).waitFor(); assert.equal(await page.locator('#sessAgent [data-agent="opencode"]').getAttribute("aria-pressed"), "true"); - assert.equal(await page.locator("#sessRange .opt.on").innerText(), lang === "zh" ? "全部" : "All"); + assert.equal(await page.locator("#sessRange .opt.on").innerText(), all); }); } } diff --git a/internal/sessions/cursor_editor.go b/internal/sessions/cursor_editor.go index 29a1be00f..5a31fc3f2 100644 --- a/internal/sessions/cursor_editor.go +++ b/internal/sessions/cursor_editor.go @@ -266,6 +266,10 @@ func cursorTranscript(path string, add func(bool, Part) bool) error { return ErrNoTranscript } for _, m := range cursorMessages(db, meta.Root) { + if m.Role == "system" { + // the agent's own prompt, not said in the conversation + continue + } if m.Role == "user" { typed, _ := cursorTyped(cursorParts(m.Content)) if !emit(m.Role, typed, time.Time{}) { diff --git a/internal/sessions/search.go b/internal/sessions/search.go index 9a4f3e690..f09b87dd4 100644 --- a/internal/sessions/search.go +++ b/internal/sessions/search.go @@ -227,7 +227,7 @@ func SearchSession(ctx context.Context, s Session, needle string) (Hit, bool, er return Hit{}, false, ErrNoTranscript } raw := rawNeedle(needle) - if !mayHold(ctx, s.Path, raw) { + if linesFile(s) && !mayHold(ctx, s.Path, raw) { return Hit{}, false, nil } var keep func([]byte) bool @@ -257,6 +257,20 @@ func SearchSession(ctx context.Context, s Session, needle string) (Hit, bool, er return m.hit, m.found, err } +// linesFile says whether s.Path is the file its conversation is written in, +// so that one without the needle's bytes can be passed over unread. An +// OpenCode session's is its info (the messages are elsewhere) or a database, +// and a Cursor chat's a database too, whose newest pages are in its -wal. +func linesFile(s Session) bool { + switch s.Agent { + case "opencode": + return false + case "cursor": + return strings.HasSuffix(s.Path, ".jsonl") + } + return true +} + // 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) { diff --git a/internal/sessions/search_db_test.go b/internal/sessions/search_db_test.go new file mode 100644 index 000000000..a850656c9 --- /dev/null +++ b/internal/sessions/search_db_test.go @@ -0,0 +1,67 @@ +package sessions + +import ( + "context" + "path/filepath" + "strings" + "testing" +) + +// searchesEveryPart has SearchSession find each word of each text part of +// s's transcript: a session whose conversation isn't in the file its Path +// names (a database, OpenCode's session info) is searched all the same. +// The agent's own system prompt isn't part of it. +func searchesEveryPart(t *testing.T, s Session) { + t.Helper() + tr, err := TranscriptOf(s) + if err != nil || len(tr.Parts) == 0 { + t.Fatalf("%s %s: no transcript: %v", s.Agent, s.ID, err) + } + tried := 0 + for _, p := range tr.Parts { + if p.Role == "system" { + t.Fatalf("%s %s: the agent's own prompt is shown as said: %q", s.Agent, s.ID, p.Text) + } + if p.Kind != "text" { + continue + } + for _, w := range strings.Fields(p.Text) { + w = strings.Trim(w, ".,!?\"'()") + if len(w) < 4 { + continue + } + tried++ + if _, ok, err := SearchSession(context.Background(), s, NeedleOf(w)); !ok || err != nil { + t.Fatalf("%s %s: %q, said in %q, wasn't found: %v", s.Agent, s.ID, w, p.Text, err) + } + } + } + if tried == 0 { + t.Fatalf("%s %s: nothing to look for in %+v", s.Agent, s.ID, tr.Parts) + } +} + +func TestSearchOpenCodeFiles(t *testing.T) { + setupMore(t) + searchesEveryPart(t, find(t, List(All), "opencode", ocMain)) +} + +func TestSearchOpenCodeDatabase(t *testing.T) { + data, _ := setupMore(t) + db := ocMakeV2(t, filepath.Join(data, "opencode", "opencode.db")) + defer db.Close() + searchesEveryPart(t, find(t, List(All), "opencode", ocMain)) +} + +func TestSearchCursorLiveChat(t *testing.T) { + dir := cursorSetup(t) + makeCursorChats(t, dir) + ss := List(0) + for _, id := range []string{curMain, curOther} { + s, ok := findSession(ss, "cursor", id) + if !ok { + t.Fatalf("%s isn't listed", id) + } + searchesEveryPart(t, s) + } +} diff --git a/internal/sessions/search_test.go b/internal/sessions/search_test.go index 599b84761..1531bb183 100644 --- a/internal/sessions/search_test.go +++ b/internal/sessions/search_test.go @@ -69,7 +69,7 @@ func TestSearchSessionCutsALongPart(t *testing.T) { } func TestSearchSessionWithoutATranscript(t *testing.T) { - if _, _, err := SearchSession(context.Background(), Session{Agent: "cursor", Path: "x"}, "a"); err != ErrNoTranscript { + if _, _, err := SearchSession(context.Background(), Session{Agent: "gemini", Path: "x"}, "a"); err != ErrNoTranscript { t.Fatalf("err = %v", err) } }