From 64d0f12a16e11acb5c1ebcaca22053094a1cd9b5 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Fri, 6 Nov 2026 05:22:07 +0100 Subject: [PATCH 1/7] feat(search): full-text message search for native clients MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `GET /api/sessions/messages/search?q=&limit=&cursor=` scans this machine's transcript corpus newest-first and answers `{ query, results, partial, cursor, scannedFiles, scannedBytes, skippedFiles }`. Snippets carry the matching text with its session and entry, so a client can jump straight to the message. The scan is bounded per file (16 MiB), in total (64 MiB) and by wall clock (5 s); a slice that hits a bound answers `partial: true` plus an opaque cursor, and the cursor is bound to its query so a reused one is refused with 400. At most two scans run at once — a third gets 429 `search_busy` with `Retry-After` instead of starving the event loop. Errors never carry a filesystem path. --- app/api/sessions/messages/search/route.ts | 83 +++ lib/session-message-search.test.mjs | 529 +++++++++++++++++++ lib/session-message-search.ts | 610 ++++++++++++++++++++++ server/routes.ts | 2 + 4 files changed, 1224 insertions(+) create mode 100644 app/api/sessions/messages/search/route.ts create mode 100644 lib/session-message-search.test.mjs create mode 100644 lib/session-message-search.ts diff --git a/app/api/sessions/messages/search/route.ts b/app/api/sessions/messages/search/route.ts new file mode 100644 index 000000000..5bcc4e137 --- /dev/null +++ b/app/api/sessions/messages/search/route.ts @@ -0,0 +1,83 @@ +import { + decodeSearchCursor, + releaseSearchSlot, + searchSessionMessages, + SearchCursorError, + SEARCH_DEFAULT_LIMIT, + SEARCH_MAX_LIMIT, + SEARCH_MAX_QUERY_LENGTH, + tryAcquireSearchSlot, +} from "@/lib/session-message-search"; + +const NO_STORE = { "Cache-Control": "no-store" } as const; + +function badRequest(error: string, code: string): Response { + return Response.json({ error, code }, { status: 400, headers: NO_STORE }); +} + +/** + * GET /api/sessions/messages/search?q=&limit=&cursor= + * + * Read-only full-text search across the session files of this machine. The + * scan is bounded: results are newest-first, `partial:true` plus `cursor` mean + * "call again for the next slice". Authentication is the normal omp-web gate + * in `proxy.ts`, because this lives under `/api/`. + * + * At most `SEARCH_MAX_CONCURRENT` scans run per process; further requests get + * `429` + `Retry-After` instead of starving the event loop. + */ +export async function GET(req: Request): Promise { + const url = new URL(req.url); + const query = (url.searchParams.get("q") ?? "").trim(); + if (!query) return badRequest("Search query is required", "query_required"); + if (query.length > SEARCH_MAX_QUERY_LENGTH) { + return badRequest(`Search query is too long (max ${SEARCH_MAX_QUERY_LENGTH})`, "query_too_long"); + } + + const rawLimit = url.searchParams.get("limit"); + const limit = rawLimit === null ? SEARCH_DEFAULT_LIMIT : Number(rawLimit); + if (!Number.isSafeInteger(limit) || limit < 1 || limit > SEARCH_MAX_LIMIT) { + return badRequest(`limit must be an integer between 1 and ${SEARCH_MAX_LIMIT}`, "invalid_limit"); + } + + const rawCursor = url.searchParams.get("cursor"); + if (rawCursor !== null && !decodeSearchCursor(rawCursor)) { + return badRequest("Invalid search cursor", "invalid_cursor"); + } + + if (!tryAcquireSearchSlot()) { + return Response.json( + { error: "Too many searches in flight, retry shortly", code: "search_busy" }, + { status: 429, headers: { ...NO_STORE, "Retry-After": "1" } }, + ); + } + + try { + const page = await searchSessionMessages({ + query, + limit, + ...(rawCursor !== null ? { cursor: rawCursor } : {}), + }); + return Response.json({ + query, + results: page.results, + partial: page.partial, + cursor: page.cursor, + scannedFiles: page.scannedFiles, + scannedBytes: page.scannedBytes, + skippedFiles: page.skippedFiles, + }, { headers: NO_STORE }); + } catch (error) { + if (error instanceof SearchCursorError) { + return badRequest( + error.message === "cursor_query_mismatch" ? "Cursor belongs to another search" : "Invalid search cursor", + error.message, + ); + } + // fs/parse failures can carry absolute paths; keep them server-side. + console.error("[api/sessions/messages/search]", error); + return Response.json({ error: "Search failed", code: "internal_error" }, { status: 500, headers: NO_STORE }); + } finally { + releaseSearchSlot(); + } +} diff --git a/lib/session-message-search.test.mjs b/lib/session-message-search.test.mjs new file mode 100644 index 000000000..4f9c1f0f3 --- /dev/null +++ b/lib/session-message-search.test.mjs @@ -0,0 +1,529 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +const search = await import("./session-message-search.ts"); +// File I/O is slow on loaded Windows hosts; only the budget test relies on the clock. +const TEST_BUDGET_MS = 120_000; +const route = await import("../app/api/sessions/messages/search/route.ts"); +const { invalidateSessionListCache } = await import("./session-reader.ts"); + +function message(id, role, text, timestamp = "2026-01-01T00:00:00.000Z") { + const content = role === "toolResult" + ? [{ type: "text", text }] + : [{ type: "text", text }]; + return JSON.stringify({ + type: "message", + id, + parentId: null, + timestamp, + message: { role, content, ...(role === "toolResult" ? { toolCallId: `call-${id}` } : {}) }, + }); +} + +function sessionFile(id, cwd, lines) { + const header = JSON.stringify({ + type: "session", + version: 3, + id, + timestamp: "2026-01-01T00:00:00.000Z", + cwd, + }); + return `${header}\n${lines.join("\n")}\n`; +} + +function writeSession(dir, name, body, mtimeMs) { + const filePath = join(dir, name); + writeFileSync(filePath, body, "utf8"); + const seconds = mtimeMs / 1000; + utimesSync(filePath, seconds, seconds); + return filePath; +} + +const newestLines = [ + message("a-user-1", "user", "Alpha needle here"), + message("a-assistant", "assistant", "nothing to see"), + message("a-thinking", "assistant", "visible answer"), + message("a-user-2", "user", "second needle at the end"), + message("a-tool", "toolResult", "needle inside a tool result"), +]; +// The thinking block is not searchable; the visible text is. +newestLines[2] = JSON.stringify({ + type: "message", + id: "a-thinking", + parentId: null, + timestamp: "2026-01-01T00:00:05.000Z", + message: { + role: "assistant", + content: [ + { type: "thinking", thinking: "needle in reasoning" }, + { type: "text", text: "visible answer" }, + ], + }, +}); + +const olderLines = [ + message("b-user", "user", "NEEDLE case insensitive", "2026-01-01T00:00:10.000Z"), + message("b-assistant", "assistant", "a needle reply", "2026-01-01T00:00:11.000Z"), + message("b-tool", "toolResult", "needle tool", "2026-01-01T00:00:12.000Z"), +]; + +function fixture() { + const dir = mkdtempSync(join(tmpdir(), "omp-web-search-")); + const newestPath = writeSession(dir, "newest.jsonl", sessionFile("s-new", "/work/new", newestLines), 3_000); + const olderPath = writeSession(dir, "older.jsonl", sessionFile("s-old", "/work/old", olderLines), 2_000); + const files = [ + { path: newestPath, id: "s-new", cwd: "/work/new", title: "Newest", size: statSync(newestPath).size, modifiedMs: 3000 }, + { path: olderPath, id: "s-old", cwd: "/work/old", title: "Older", size: statSync(olderPath).size, modifiedMs: 2000 }, + ]; + return { dir, files }; +} + +/** Point the omp agent dir at a throwaway location for the duration of `run`. */ +async function withAgentDir(run) { + const agentDir = mkdtempSync(join(tmpdir(), "omp-web-search-agent-")); + const projectDir = join(agentDir, "sessions", "-project"); + mkdirSync(projectDir, { recursive: true }); + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = agentDir; + invalidateSessionListCache(); + try { + await run(projectDir); + } finally { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + invalidateSessionListCache(); + rmSync(agentDir, { recursive: true, force: true }); + } +} + +test("search returns newest sessions first and newest messages first inside a session", async (t) => { + const { dir, files } = fixture(); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + const page = await search.searchSessionMessages({ query: "needle", budgetMs: TEST_BUDGET_MS, sessions: files }); + assert.equal(page.partial, false); + assert.equal(page.cursor, null); + assert.deepEqual( + page.results.map((hit) => hit.entryId), + ["a-user-2", "a-user-1", "b-assistant", "b-user"], + ); + assert.deepEqual( + page.results.map((hit) => hit.sessionId), + ["s-new", "s-new", "s-old", "s-old"], + ); + + const first = page.results[0]; + assert.equal(first.title, "Newest"); + assert.equal(first.cwd, "/work/new"); + assert.equal(first.role, "user"); + assert.equal(first.timestamp, "2026-01-01T00:00:00.000Z"); + assert.equal(first.snippet.slice(first.matchStart, first.matchEnd).toLowerCase(), "needle"); + assert.match(first.snippet, /second/); + + // Thinking blocks are not transcript text, so the assistant entry above + // (whose visible text has no match) must not appear. + assert.ok(!page.results.some((hit) => hit.entryId === "a-thinking")); +}); + +test("matching is case-insensitive and supports plain substrings", async (t) => { + const { dir, files } = fixture(); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + const page = await search.searchSessionMessages({ query: "NeEdLe", budgetMs: TEST_BUDGET_MS, sessions: files }); + assert.equal(page.results.length, 4); + const hit = page.results.find((result) => result.entryId === "b-user"); + assert.ok(hit); + assert.equal(hit.snippet.slice(hit.matchStart, hit.matchEnd), "NEEDLE"); + + const none = await search.searchSessionMessages({ query: "no-such-term", budgetMs: TEST_BUDGET_MS, sessions: files }); + assert.deepEqual(none.results, []); +}); + +test("tool results and thinking blocks are not searchable", async (t) => { + const { dir, files } = fixture(); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + const page = await search.searchSessionMessages({ query: "needle", budgetMs: TEST_BUDGET_MS, sessions: files }); + assert.ok(!page.results.some((hit) => hit.entryId === "a-tool")); + assert.ok(!page.results.some((hit) => hit.entryId === "b-tool")); + assert.ok(!page.results.some((hit) => hit.role === "tool")); +}); + +test("cursor pagination neither skips nor duplicates lines, even across tiny chunk boundaries", async (t) => { + const { dir, files } = fixture(); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + const complete = await search.searchSessionMessages({ query: "needle", budgetMs: TEST_BUDGET_MS, sessions: files }); + const expected = complete.results.map((hit) => hit.entryId); + + for (const chunkBytes of [64, 97, 1024]) { + const seen = []; + let cursor; + let pages = 0; + do { + const page = await search.searchSessionMessages({ + query: "needle", + limit: 1, + ...(cursor ? { cursor } : {}), + chunkBytes, + budgetMs: TEST_BUDGET_MS, + sessions: files, + }); + seen.push(...page.results.map((hit) => hit.entryId)); + assert.ok(page.results.length <= 1); + if (page.cursor) { + assert.equal(page.partial, true); + cursor = page.cursor; + } else { + assert.equal(page.partial, false); + cursor = undefined; + } + pages++; + assert.ok(pages < 50, "pagination must terminate"); + } while (cursor); + assert.deepEqual(seen, expected, `chunk size ${chunkBytes}`); + } +}); + +test("a time/size budget stops the scan with a resumable cursor", async (t) => { + const { dir, files } = fixture(); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + const seen = []; + let cursor; + let partialPages = 0; + let pages = 0; + do { + const page = await search.searchSessionMessages({ + query: "needle", + ...(cursor ? { cursor } : {}), + maxFileScanBytes: 40, + chunkBytes: 16, + sessions: files, + }); + seen.push(...page.results.map((hit) => hit.entryId)); + if (page.partial) partialPages++; + cursor = page.cursor ?? undefined; + pages++; + assert.ok(pages < 50, "budget pagination must terminate"); + } while (cursor); + assert.ok(partialPages > 0, "byte cap must produce partial pages"); + assert.deepEqual(seen, ["a-user-2", "a-user-1", "b-assistant", "b-user"]); +}); + +test("the time budget starts after the session listing", async (t) => { + const { dir, files } = fixture(); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + // A slow directory listing must not eat the scan budget: otherwise the very + // first page comes back empty with a cursor that never advances. + let clock = 0; + const page = await search.searchSessionMessages({ + query: "needle", + now: () => clock, + listSessions: async () => { + clock += 10_000; + return files; + }, + budgetMs: 5_000, + }); + assert.equal(page.partial, false); + assert.equal(page.cursor, null); + assert.deepEqual(page.results.map((hit) => hit.entryId), ["a-user-2", "a-user-1", "b-assistant", "b-user"]); +}); + +test("very large files are skipped", async (t) => { + const { dir, files } = fixture(); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const huge = { ...files[0], path: join(dir, "newest.jsonl"), size: search.SEARCH_LARGE_FILE_BYTES + 1 }; + + const skipped = await search.searchSessionMessages({ query: "needle", budgetMs: TEST_BUDGET_MS, sessions: [huge, files[1]] }); + assert.equal(skipped.skippedFiles, 1); + assert.deepEqual(skipped.results.map((hit) => hit.sessionId), ["s-old", "s-old"]); +}); + +test("cursors are bound to their query and survive a vanished file", async (t) => { + const { dir, files } = fixture(); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + const first = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS, sessions: files }); + assert.ok(first.cursor); + await assert.rejects( + () => search.searchSessionMessages({ query: "other", cursor: first.cursor, sessions: files }), + (error) => error.name === "SearchCursorError" && error.message === "cursor_query_mismatch", + ); + + // Drop the newest file: the cursor's fallback continues with older files. + const withoutNewest = [files[1]]; + const resumed = await search.searchSessionMessages({ + query: "needle", + cursor: first.cursor, + sessions: withoutNewest, + }); + assert.deepEqual(resumed.results.map((hit) => hit.entryId), ["b-assistant", "b-user"]); + assert.equal(resumed.cursor, null); +}); + +test("malformed and non-message lines are ignored", async (t) => { + const dir = mkdtempSync(join(tmpdir(), "omp-web-search-bad-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const body = [ + JSON.stringify({ type: "session", version: 3, id: "s-bad", timestamp: "2026-01-01T00:00:00.000Z", cwd: "/w" }), + "{not json", + JSON.stringify({ type: "model_change", id: "m", parentId: null, timestamp: "2026-01-01T00:00:01.000Z", model: "needle" }), + message("bad-1", "user", "needle survives"), + JSON.stringify({ type: "message", id: "", parentId: null, timestamp: "2026-01-01T00:00:02.000Z", message: { role: "user", content: "needle without id" } }), + ].join("\n"); + const filePath = writeSession(dir, "bad.jsonl", `${body}\n`, 1000); + const files = [{ path: filePath, id: "s-bad", cwd: "/w", title: "", size: statSync(filePath).size, modifiedMs: 1000 }]; + + const page = await search.searchSessionMessages({ query: "needle", budgetMs: TEST_BUDGET_MS, sessions: files }); + assert.deepEqual(page.results.map((hit) => hit.entryId), ["bad-1"]); +}); + +test("lines that start exactly at a chunk boundary are matched exactly once", async (t) => { + const dir = mkdtempSync(join(tmpdir(), "omp-web-search-uniform-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + // Every line is 255 JSON bytes (2^8-1) + LF = 256 bytes, so any chunk size + // that is a multiple of 256 puts every window edge on a line start. + const LINE_BYTES = 255; + const STRIDE = 256; + const total = 2600; + const lines = []; + const expected = []; + for (let index = 0; index < total; index++) { + const entry = { + type: "message", + id: `u-${index}`, + parentId: null, + timestamp: "2026-01-01T00:00:00.000Z", + message: { role: "user", content: [{ type: "text", text: "" }] }, + }; + const base = JSON.stringify(entry); + const hit = index % 97 === 0 || index === total - 1; + const body = hit ? "needle" : "filler"; + entry.message.content[0].text = body + "x".repeat(LINE_BYTES - base.length - body.length); + const line = JSON.stringify(entry); + assert.equal(Buffer.byteLength(line), LINE_BYTES, `line ${index} must stay uniform`); + lines.push(line); + if (hit) expected.push(`u-${index}`); + } + const filePath = writeSession(dir, "uniform.jsonl", sessionFile("s-uniform", "/w", lines), 1000); + const size = statSync(filePath).size; + const files = [{ path: filePath, id: "s-uniform", cwd: "/w", title: "Uniform", size, modifiedMs: 1000 }]; + const raw = readFileSync(filePath); + const newestFirst = [...expected].reverse(); + + for (const chunkBytes of [STRIDE * 32, STRIDE * 1024]) { + const page = await search.searchSessionMessages({ + query: "needle", + limit: 100, + chunkBytes, + budgetMs: TEST_BUDGET_MS, + sessions: files, + }); + assert.deepEqual(page.results.map((hit) => hit.entryId), newestFirst, `chunk size ${chunkBytes}`); + assert.equal(page.partial, false); + } + + // Same file, tiny pages: every hit exactly once and every cursor on a line start. + const seen = []; + let cursor; + let pages = 0; + do { + const page = await search.searchSessionMessages({ + query: "needle", + limit: 3, + ...(cursor ? { cursor } : {}), + chunkBytes: STRIDE * 256, + budgetMs: TEST_BUDGET_MS, + sessions: files, + }); + seen.push(...page.results.map((hit) => hit.entryId)); + cursor = page.cursor ?? undefined; + if (cursor) { + const decoded = search.decodeSearchCursor(cursor); + assert.ok(decoded); + assert.ok(decoded.offset === 0 || raw[decoded.offset - 1] === 0x0a, "cursor must point at a line start"); + } + pages++; + assert.ok(pages < 40, "pagination must terminate"); + } while (cursor); + assert.deepEqual(seen, newestFirst); +}); + +test("a message line spanning several chunks is still found", async (t) => { + const dir = mkdtempSync(join(tmpdir(), "omp-web-search-long-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + const longText = `needle ${"y".repeat(3000)}`; + const filePath = writeSession(dir, "long.jsonl", sessionFile("s-long", "/w", [ + message("short-1", "user", "needle first"), + message("long-1", "user", longText), + message("short-2", "user", "needle last"), + ]), 1000); + const files = [{ path: filePath, id: "s-long", cwd: "/w", title: "", size: statSync(filePath).size, modifiedMs: 1000 }]; + + for (const chunkBytes of [512, 1024, 4096]) { + const page = await search.searchSessionMessages({ query: "needle", chunkBytes, budgetMs: TEST_BUDGET_MS, sessions: files }); + assert.deepEqual( + page.results.map((hit) => hit.entryId), + ["short-2", "long-1", "short-1"], + `chunk size ${chunkBytes}`, + ); + } +}); + +test("match offsets stay on the original text when lowercasing would change its length", async (t) => { + const dir = mkdtempSync(join(tmpdir(), "omp-web-search-case-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + // "İ".toLowerCase() is two code units, so a lowercase index would slice the + // wrong part of the original string. + const filePath = writeSession(dir, "case.jsonl", sessionFile("s-case", "/w", [ + message("case-1", "user", "İstanbul ist schön, needle hier"), + ]), 1000); + const files = [{ path: filePath, id: "s-case", cwd: "/w", title: "", size: statSync(filePath).size, modifiedMs: 1000 }]; + + const page = await search.searchSessionMessages({ query: "needle", budgetMs: TEST_BUDGET_MS, sessions: files }); + assert.equal(page.results.length, 1); + + const hit = page.results[0]; + assert.equal(hit.snippet.slice(hit.matchStart, hit.matchEnd), "needle"); +}); + +test("a cursor survives deleting one of two files with the same mtime", async (t) => { + const dir = mkdtempSync(join(tmpdir(), "omp-web-search-tie-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + const pathA = writeSession(dir, "a.jsonl", sessionFile("s-a", "/w/a", [ + message("a-1", "user", "needle a one"), + message("a-2", "user", "needle a two"), + ]), 1000); + const pathB = writeSession(dir, "b.jsonl", sessionFile("s-b", "/w/b", [ + message("b-1", "user", "needle b one"), + ]), 1000); + const files = [ + { path: pathA, id: "s-a", cwd: "/w/a", title: "", size: statSync(pathA).size, modifiedMs: 1000 }, + { path: pathB, id: "s-b", cwd: "/w/b", title: "", size: statSync(pathB).size, modifiedMs: 1000 }, + ]; + + // The tie is broken by path, so a.jsonl (one hit left after the page) comes first. + const first = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS, sessions: files }); + assert.deepEqual(first.results.map((hit) => hit.entryId), ["a-2"]); + assert.ok(first.cursor); + + rmSync(pathA); + const resumed = await search.searchSessionMessages({ + query: "needle", + cursor: first.cursor, + sessions: [files[1]], + }); + // a-1 was still unscanned but its file is gone; b.jsonl has the same mtime + // and comes after it, so it must not be skipped. + assert.deepEqual(resumed.results.map((hit) => hit.entryId), ["b-1"]); +}); + +test("production listing finds sessions through the omp agent dir", async () => { + await withAgentDir(async (projectDir) => { + writeSession(projectDir, "one.jsonl", sessionFile("prod-1", "/work/prod", [ + message("p-1", "user", "production needle one"), + message("p-2", "assistant", "production needle two"), + ]), 1_000); + const page = await search.searchSessionMessages({ query: "production needle", budgetMs: TEST_BUDGET_MS }); + assert.deepEqual(page.results.map((hit) => hit.entryId), ["p-2", "p-1"]); + assert.equal(page.results[0].sessionId, "prod-1"); + assert.equal(page.results[0].cwd, "/work/prod"); + }); +}); + +test("route rejects missing/oversized input and reports search pages", async () => { + const get = (query) => route.GET(new Request(`http://localhost/api/sessions/messages/search${query}`)); + + let response = await get(""); + assert.equal(response.status, 400); + assert.equal((await response.json()).code, "query_required"); + + response = await get("?q=needle&limit=0"); + assert.equal(response.status, 400); + assert.equal((await response.json()).code, "invalid_limit"); + + response = await get("?q=needle&limit=101"); + assert.equal(response.status, 400); + + response = await get("?q=needle&cursor=not-a-cursor"); + assert.equal(response.status, 400); + assert.equal((await response.json()).code, "invalid_cursor"); + + await withAgentDir(async (projectDir) => { + writeSession(projectDir, "route.jsonl", sessionFile("route-1", "/work/route", [ + message("r-1", "user", "route needle first"), + message("r-2", "toolResult", "route needle tool"), + message("r-3", "assistant", "route needle last"), + ]), 1_000); + + response = await get("?q=needle&limit=5"); + assert.equal(response.status, 200); + assert.equal(response.headers.get("cache-control"), "no-store"); + let body = await response.json(); + // Tool results are not searchable, even though the fixture has one. + assert.deepEqual(body.results.map((hit) => hit.entryId), ["r-3", "r-1"]); + assert.equal(body.partial, false); + assert.equal(body.cursor, null); + + body = await (await get("?q=needle&limit=1")).json(); + assert.deepEqual(body.results.map((hit) => hit.entryId), ["r-3"]); + assert.equal(body.partial, true); + assert.ok(body.cursor); + const firstCursor = body.cursor; + + response = await get(`?q=needle&limit=1&cursor=${encodeURIComponent(firstCursor)}`); + body = await response.json(); + assert.deepEqual(body.results.map((hit) => hit.entryId), ["r-1"]); + assert.ok(body.cursor); + // The last page only proves the corpus is exhausted. + response = await get(`?q=needle&limit=1&cursor=${encodeURIComponent(body.cursor)}`); + body = await response.json(); + assert.deepEqual(body.results, []); + assert.equal(body.cursor, null); + + response = await get(`?q=other&cursor=${encodeURIComponent(firstCursor)}`); + assert.equal(response.status, 400); + assert.equal((await response.json()).code, "cursor_query_mismatch"); + }); +}); + +test("route answers 429 while the scan slots are taken and recovers after release", { timeout: 30_000 }, async (t) => { + const get = (query) => route.GET(new Request(`http://localhost/api/sessions/messages/search${query}`)); + t.after(() => { + // Never leak slots into another test if an assertion above throws. + search.releaseSearchSlot(); + search.releaseSearchSlot(); + }); + + assert.equal(search.tryAcquireSearchSlot(), true); + assert.equal(search.tryAcquireSearchSlot(), true); + assert.equal(search.tryAcquireSearchSlot(), false); + + const busy = await get("?q=whatever"); + assert.equal(busy.status, 429); + assert.equal(busy.headers.get("retry-after"), "1"); + assert.equal(busy.headers.get("cache-control"), "no-store"); + assert.equal((await busy.json()).code, "search_busy"); + + search.releaseSearchSlot(); + search.releaseSearchSlot(); + + // A real (but empty) agent dir: the probe must not scan this machine's multi-GB corpus. + await withAgentDir(async () => { + const done = await get("?q=whatever"); + assert.notEqual(done.status, 429); + }); + // The successful request released its slot again. + assert.equal(search.tryAcquireSearchSlot(), true); + search.releaseSearchSlot(); +}); diff --git a/lib/session-message-search.ts b/lib/session-message-search.ts new file mode 100644 index 000000000..b77404f4c --- /dev/null +++ b/lib/session-message-search.ts @@ -0,0 +1,610 @@ +import { createHash } from "crypto"; +import { open } from "fs/promises"; +import { isRecord } from "./type-guards"; +import { listAllSessionInfos, type OmpSessionInfo } from "./omp/session-files"; + +/** + * Full-text search over the on-disk omp session files. + * + * The corpus is several gigabytes, so the scan is deliberately bounded: + * sessions are opened newest-first and each file is read **backwards** (the + * newest lines are at the end), one chunk at a time. Every request stops at + * whichever limit trips first — result count, per-file bytes, total bytes or + * the wall-clock budget — and returns an opaque cursor that resumes at the next + * unread line. Only a line above 1 MiB is skipped, and just that case can leave + * a cursor inside the skipped line. `partial:true` therefore means + * "more sessions/lines remain", not "the answer is incomplete". + * + * Only `message` entries are considered: user and assistant text blocks. + * Thinking blocks, tool results and tool-call arguments are not searchable, + * matching what the web transcript actually shows. + */ + +export const SEARCH_TIME_BUDGET_MS = 5_000; +export const SEARCH_DEFAULT_LIMIT = 20; +export const SEARCH_MAX_LIMIT = 100; +export const SEARCH_MAX_QUERY_LENGTH = 200; +/** Files above this size are skipped: reading them would blow the budget. */ +export const SEARCH_LARGE_FILE_BYTES = 64 * 1024 * 1024; +const DEFAULT_FILE_SCAN_BYTES = 16 * 1024 * 1024; +const DEFAULT_TOTAL_SCAN_BYTES = 64 * 1024 * 1024; +/** Longest physical line we try to parse; larger lines are tool payloads. */ +const MAX_LINE_BYTES = 1024 * 1024; +const READ_CHUNK_BYTES = 256 * 1024; +const SNIPPET_CONTEXT_CHARS = 80; +/** + * Maximum extra bytes read after a budget stop to finish the partial line the + * reader is standing in, so a cursor always points at a line start. + */ +const MAX_LINE_COMPLETION_BYTES = MAX_LINE_BYTES; +const LF = 0x0a; + +/** + * Process-wide ceiling for simultaneous scans. A single scan may spend its + * whole 5 s budget parsing JSON on the event-loop thread, so unbounded + * concurrency would starve the SSE stream and every other API call. + */ +export const SEARCH_MAX_CONCURRENT = 2; +// Kept on `globalThis` so every module instance of this file (bundler graphs, +// `bun --hot` re-evaluation) shares one process-wide counter. +interface SearchSlotHost { + __ompActiveSessionSearches?: number; +} +const searchSlotHost = globalThis as unknown as SearchSlotHost; + +/** Reserve a scan slot; the caller MUST call `releaseSearchSlot` afterwards. */ +export function tryAcquireSearchSlot(): boolean { + const active = searchSlotHost.__ompActiveSessionSearches ?? 0; + if (active >= SEARCH_MAX_CONCURRENT) return false; + searchSlotHost.__ompActiveSessionSearches = active + 1; + return true; +} + +export function releaseSearchSlot(): void { + const active = searchSlotHost.__ompActiveSessionSearches ?? 0; + if (active > 0) searchSlotHost.__ompActiveSessionSearches = active - 1; +} + +export type SessionSearchRole = "user" | "assistant"; + +export interface SessionSearchHit { + sessionId: string; + title: string; + cwd: string; + entryId: string; + role: SessionSearchRole; + timestamp: string; + /** A single-line excerpt around the match. */ + snippet: string; + /** Match offsets inside `snippet` (UTF-16 code units, like Kotlin strings). */ + matchStart: number; + matchEnd: number; +} + +export interface SessionSearchCursor { + v: 1; + /** Fingerprint of the query/option set the cursor belongs to. */ + q: string; + path: string; + /** + * Resume scanning bytes strictly below this offset. It is a line start, + * except after a >1 MiB line was skipped mid-way. + */ + offset: number; + /** Used only when the cursor's file vanished: continue with older files. */ + modifiedMs: number; +} + +export interface SessionSearchPage { + results: SessionSearchHit[]; + /** True when the scan stopped before the corpus was exhausted. */ + partial: boolean; + /** Opaque token for the next page; null when the scan is complete. */ + cursor: string | null; + scannedFiles: number; + scannedBytes: number; + skippedFiles: number; +} + +/** One session file the scan can visit; keeps the core testable without omp. */ +export interface SessionSearchFile { + path: string; + id: string; + cwd: string; + title?: string; + size: number; + modifiedMs: number; +} + +export interface SessionSearchOptions { + query: string; + limit?: number; + cursor?: string; + /** Test hooks; production uses the defaults. */ + now?: () => number; + budgetMs?: number; + chunkBytes?: number; + maxFileScanBytes?: number; + maxTotalScanBytes?: number; + sessions?: readonly SessionSearchFile[]; + /** Listing stand-in; production uses `loadSessionSearchFiles`. */ + listSessions?: () => Promise; +} + +/** A cursor that does not belong to this query (or was tampered with). */ +export class SearchCursorError extends Error { + constructor(message: string) { + super(message); + this.name = "SearchCursorError"; + } +} + +/** Query fingerprint so a cursor cannot be replayed against another search. */ +export function searchQueryKey(query: string): string { + return createHash("sha1") + .update(`chat\0${query.trim().toLowerCase()}`) + .digest("hex") + .slice(0, 16); +} + +export function encodeSearchCursor(cursor: SessionSearchCursor): string { + return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url"); +} + +export function decodeSearchCursor(raw: string): SessionSearchCursor | undefined { + let value: unknown; + try { + value = JSON.parse(Buffer.from(raw, "base64url").toString("utf8")); + } catch { + return undefined; + } + if (!isRecord(value)) return undefined; + if (value.v !== 1) return undefined; + if (typeof value.q !== "string" || !value.q) return undefined; + if (typeof value.path !== "string" || !value.path) return undefined; + if (typeof value.offset !== "number" || !Number.isSafeInteger(value.offset) || value.offset < 0) return undefined; + if (typeof value.modifiedMs !== "number" || !Number.isFinite(value.modifiedMs)) return undefined; + return { + v: 1, + q: value.q, + path: value.path, + offset: value.offset, + modifiedMs: value.modifiedMs, + }; +} + +/** Production file list: the same newest-first metadata the sidebar uses. */ +export async function loadSessionSearchFiles(): Promise { + const infos: OmpSessionInfo[] = await listAllSessionInfos(); + return infos.map((info) => ({ + path: info.path, + id: info.id, + cwd: info.cwd, + ...(info.title ? { title: info.title } : {}), + size: info.size, + modifiedMs: info.modified.getTime(), + })); +} + +interface Segment { + /** Byte offset of the segment's first byte inside the file. */ + start: number; + bytes: Buffer; +} + +interface ScanOutcome { + hits: SessionSearchHit[]; + bytes: number; + cursor?: { offset: number }; + /** The file was read down to byte 0. */ + done: boolean; +} + +export async function searchSessionMessages(options: SessionSearchOptions): Promise { + const query = options.query.trim(); + const limit = Math.min(Math.max(options.limit ?? SEARCH_DEFAULT_LIMIT, 1), SEARCH_MAX_LIMIT); + const now = options.now ?? Date.now; + const chunkBytes = Math.max(1, options.chunkBytes ?? READ_CHUNK_BYTES); + const fileScanBytes = Math.max(chunkBytes, options.maxFileScanBytes ?? DEFAULT_FILE_SCAN_BYTES); + const totalScanBytes = Math.max(chunkBytes, options.maxTotalScanBytes ?? DEFAULT_TOTAL_SCAN_BYTES); + const key = searchQueryKey(query); + + if (!query) { + return { results: [], partial: false, cursor: null, scannedFiles: 0, scannedBytes: 0, skippedFiles: 0 }; + } + + // Case-insensitive substring search without `toLowerCase()` on the haystack: + // a lowercasing pass changes the length for some characters (e.g. "İ"), so + // an offset found there would slice the wrong part of the original text. + const matcher = new RegExp(escapeRegExp(query), "i"); + // Equal mtimes are ordered by path so the vanished-file fallback below can + // tell "older" from "same age but already handled" deterministically. + // The deadline is armed *after* the listing: enumerating a large session + // directory must not consume the scan budget, or the first page would come + // back empty with a cursor that never advances. + const files = (options.sessions + ? [...options.sessions] + : await (options.listSessions ?? loadSessionSearchFiles)()) + .sort((a, b) => b.modifiedMs - a.modifiedMs || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + const deadline = now() + Math.max(1, options.budgetMs ?? SEARCH_TIME_BUDGET_MS); + + let startIndex = 0; + let startOffset: number | undefined; + let remainingResults = limit; + + if (options.cursor) { + const cursor = decodeSearchCursor(options.cursor); + if (!cursor) throw new SearchCursorError("invalid_cursor"); + if (cursor.q !== key) throw new SearchCursorError("cursor_query_mismatch"); + const index = files.findIndex((file) => file.path === cursor.path); + if (index >= 0) { + startIndex = index; + startOffset = cursor.offset; + } else { + // The session file disappeared between pages: everything older than it + // is still unscanned, so continue there instead of failing the page. + // "Older" follows the sort order above (mtime, then path). + const fallback = files.findIndex( + (file) => + file.modifiedMs < cursor.modifiedMs || + (file.modifiedMs === cursor.modifiedMs && file.path > cursor.path), + ); + if (fallback < 0) { + return { results: [], partial: false, cursor: null, scannedFiles: 0, scannedBytes: 0, skippedFiles: 0 }; + } + startIndex = fallback; + } + } + + const results: SessionSearchHit[] = []; + let scannedFiles = 0; + let scannedBytes = 0; + let skippedFiles = 0; + let nextCursor: SessionSearchCursor | null = null; + let partial = false; + + const cursorFor = (file: SessionSearchFile, offset: number): SessionSearchCursor => ({ + v: 1, + q: key, + path: file.path, + offset, + modifiedMs: file.modifiedMs, + }); + + for (let index = startIndex; index < files.length; index++) { + const file = files[index]; + const resuming = index === startIndex && startOffset !== undefined; + const boundary = Math.min(resuming ? startOffset! : file.size, file.size); + + if (file.size > SEARCH_LARGE_FILE_BYTES) { + skippedFiles++; + continue; + } + if (boundary <= 0) continue; + if (now() >= deadline || scannedBytes >= totalScanBytes) { + partial = true; + nextCursor = cursorFor(file, boundary); + break; + } + + const outcome = await scanFileBackwards({ + file, + boundary, + matcher, + remainingResults, + deadline, + now, + chunkBytes, + byteCap: fileScanBytes, + totalByteCap: totalScanBytes - scannedBytes, + }); + scannedFiles++; + scannedBytes += outcome.bytes; + results.push(...outcome.hits); + remainingResults -= outcome.hits.length; + + if (outcome.cursor) { + partial = true; + nextCursor = cursorFor(file, outcome.cursor.offset); + break; + } + + if (remainingResults <= 0) { + // The file itself is exhausted (outcome.done); continue with the next + // older session if one exists, otherwise the search is complete. + const nextFile = files[index + 1]; + if (nextFile) { + partial = true; + nextCursor = cursorFor(nextFile, nextFile.size); + } + break; + } + } + + return { + results, + partial, + cursor: nextCursor ? encodeSearchCursor(nextCursor) : null, + scannedFiles, + scannedBytes, + skippedFiles, + }; +} + +interface ScanFileOptions { + file: SessionSearchFile; + boundary: number; + matcher: RegExp; + remainingResults: number; + deadline: number; + now: () => number; + chunkBytes: number; + byteCap: number; + totalByteCap: number; +} + +/** A physical line that crosses the current chunk boundary. */ +type CarryState = "none" | "partial" | "oversized"; + +/** + * Read one session file newest-line-first and collect matching messages. + * + * A cursor is returned only when unread bytes remain (byte cap, time budget + * or the result limit). `offset` is always a line start, so a resumed scan + * neither skips nor duplicates a line. Lines that cross a chunk edge are + * carried as bytes until their start is reached; a page ends only after the + * line it stands in has been finished (bounded by `MAX_LINE_COMPLETION_BYTES`), + * which keeps the cursor small and independent of the line length. + */ +async function scanFileBackwards(options: ScanFileOptions): Promise { + const { file, matcher, now, deadline } = options; + const hits: SessionSearchHit[] = []; + let boundary = options.boundary; + let bytesRead = 0; + let remainingResults = options.remainingResults; + const byteCap = Math.min(options.byteCap, options.totalByteCap); + /** Cursor offsets produced here are line starts; so is the incoming one. */ + let atLineStart = true; + let carry: Buffer | undefined; + let carryState: CarryState = "none"; + let completionBytes = 0; + /** The budget tripped inside a line: read on until that line is finished. */ + let completingLine = false; + + let handle; + try { + handle = await open(file.path, "r"); + } catch { + return { hits, bytes: 0, done: true }; + } + + try { + const stat = await handle.stat(); + const size = stat.size; + if (boundary > size) boundary = size; + + while (boundary > 0) { + let chunkLength = Math.min( + options.chunkBytes, + boundary, + byteCap - bytesRead, + options.totalByteCap - bytesRead, + ); + if (chunkLength <= 0 || now() >= deadline) { + if (atLineStart || completionBytes >= MAX_LINE_COMPLETION_BYTES) { + return { hits, bytes: bytesRead, done: false, cursor: { offset: boundary } }; + } + // The budget ran out inside a line: finish that line so the next page + // can resume at a line start instead of carrying bytes in the cursor. + chunkLength = Math.min(options.chunkBytes, boundary); + completionBytes += chunkLength; + completingLine = true; + } + + const windowStart = boundary - chunkLength; + // Read up to two bytes below the window: the byte before the window + // decides whether it splits a line, and the byte before that decides + // whether the included piece starts a line itself. + const lookbehind = Math.min(2, windowStart); + const readStart = windowStart - lookbehind; + const raw = Buffer.allocUnsafe(boundary - readStart); + const { bytesRead: read } = await handle.read(raw, 0, raw.length, readStart); + if (read <= 0 || (read <= lookbehind && read < raw.length)) { + // The file shrank under us: treat the remaining range as read so the + // scan cannot spin on a stale size. + boundary = readStart + Math.max(0, read); + atLineStart = true; + carry = undefined; + carryState = "none"; + continue; + } + bytesRead += read; + const window = raw.subarray(0, read); + const windowEnd = readStart + read; + if (read < raw.length) { + // Short read (truncated file): what we have no longer meets the + // boundary, so a carried tail cannot be trusted. + carry = undefined; + carryState = "none"; + } + // A byte before the window that is not a LF means the window starts + // inside a line; include it so that line is not split at the edge. + const splitsLine = lookbehind > 0 && window[lookbehind - 1] !== LF; + const dataOffset = splitsLine ? lookbehind - 1 : lookbehind; + const windowAtLineStart = splitsLine ? lookbehind < 2 || window[lookbehind - 2] === LF : true; + const data = window.subarray(dataOffset); + // Absolute offset of data[0]. + const chunkStart = windowEnd - data.length; + const segments = splitLines(data, chunkStart); + const endsWithNewline = data.length > 0 && data[data.length - 1] === LF; + let last = segments.length - 1; + if (endsWithNewline) last--; + const first = windowAtLineStart ? 0 : 1; + // The carried line's start is in this window when a LF splits it from + // the window's top segment, or when the window itself starts a line. + const carryLineCompletes = + carryState !== "none" && (windowAtLineStart || segments.length > 1); + + for (let segmentIndex = last; segmentIndex >= first; segmentIndex--) { + const segment = segments[segmentIndex]; + let lineBytes: Buffer | undefined = segment.bytes; + if (segmentIndex === last && carryLineCompletes) { + // Oversized lines are unsearchable by design; never hand them on. + lineBytes = + carryState === "oversized" || !carry ? undefined : Buffer.concat([segment.bytes, carry]); + } + if (lineBytes && lineBytes.length <= MAX_LINE_BYTES) { + const hit = matchLine(lineBytes.toString("utf8"), file, matcher); + if (hit) { + hits.push(hit); + remainingResults--; + } + } + if (remainingResults <= 0 || now() >= deadline) { + // Resume at this line's start: the lines below it are unscanned. + return { hits, bytes: bytesRead, done: false, cursor: { offset: segment.start } }; + } + } + + if (completingLine && carryLineCompletes && first <= last) { + // The line the budget stopped in is now matched; resume below the + // lowest line this window processed, so nothing is scanned twice. + return { hits, bytes: bytesRead, done: false, cursor: { offset: segments[first].start } }; + } + + atLineStart = windowAtLineStart; + if (windowAtLineStart) { + carry = undefined; + carryState = "none"; + } else if (segments.length === 1) { + // No LF in the window: it is one piece of the carried line, so the + // pieces have to be joined across chunks until the line start arrives. + const piece = segments[0].bytes; + if (carryState === "oversized") { + carry = undefined; + } else if (carry && piece.length + carry.length > MAX_LINE_BYTES) { + carry = undefined; + carryState = "oversized"; + } else if (carry) { + carry = Buffer.concat([piece, carry]); + } else { + // Resumed mid-line without the upper part (oversized-line bail): + // keep the bytes so the parse below at least sees one piece. + carry = piece; + carryState = "partial"; + } + } else { + // A LF ends the carried line above; the top segment now belongs to the + // line that crosses chunkStart. + carry = segments[0].bytes; + carryState = carry.length > MAX_LINE_BYTES ? "oversized" : "partial"; + } + boundary = chunkStart; + } + + return { hits, bytes: bytesRead, done: true }; + } catch { + // Unreadable file (permissions, deleted mid-scan): skip it, like the list. + return { hits, bytes: bytesRead, done: true }; + } finally { + await handle.close().catch(() => undefined); + } +} + +/** Escape a literal string so it can be used as a RegExp pattern. */ +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** Split a byte window at LF; each segment carries its absolute file offset. */ +function splitLines(buffer: Buffer, chunkStart: number): Segment[] { + const segments: Segment[] = []; + let start = 0; + for (let index = 0; index < buffer.length; index++) { + if (buffer[index] === 0x0a) { + segments.push({ start: chunkStart + start, bytes: buffer.subarray(start, index) }); + start = index + 1; + } + } + segments.push({ start: chunkStart + start, bytes: buffer.subarray(start) }); + return segments; +} + +/** Parse one physical line and return a hit for a matching message entry. */ +function matchLine( + line: string, + file: SessionSearchFile, + matcher: RegExp, +): SessionSearchHit | undefined { + if (!line.includes('"type"')) return undefined; + // Cheap reject before the JSON parser: entries omp writes always carry + // `"type":"message"`; other entry types (model changes, labels, titles) + // cannot match a message search. + if (!/"type"\s*:\s*"message"/.test(line)) return undefined; + let entry: unknown; + try { + entry = JSON.parse(line); + } catch { + return undefined; + } + if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message)) return undefined; + const entryId = typeof entry.id === "string" ? entry.id : ""; + if (!entryId) return undefined; + const message = entry.message; + const role = message.role; + let hitRole: SessionSearchRole; + if (role === "user") hitRole = "user"; + else if (role === "assistant") hitRole = "assistant"; + else return undefined; + + const text = messageText(message.content); + if (!text) return undefined; + // Search the original string: lowercasing first can change its length and + // would shift every offset after such a character. + const found = matcher.exec(text); + if (!found) return undefined; + + const index = found.index; + const matched = found[0]; + const end = index + matched.length; + const before = text.slice(Math.max(0, index - SNIPPET_CONTEXT_CHARS), index).replace(/\s+/g, " "); + const after = text.slice(end, end + SNIPPET_CONTEXT_CHARS).replace(/\s+/g, " "); + const matchText = matched.replace(/\s+/g, " "); + const leading = index > 0 ? "…" : ""; + const trailing = end < text.length ? "…" : ""; + const snippet = `${leading}${before}${matchText}${after}${trailing}`; + const matchStart = leading.length + before.length; + + return { + sessionId: file.id, + title: file.title ?? "", + cwd: file.cwd, + entryId, + role: hitRole, + timestamp: timestampOf(entry), + snippet, + matchStart, + matchEnd: matchStart + matchText.length, + }; +} + +function messageText(content: unknown): string { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + const parts: string[] = []; + for (const block of content) { + if (isRecord(block) && block.type === "text" && typeof block.text === "string" && block.text) { + parts.push(block.text); + } + } + return parts.join("\n"); +} + +function timestampOf(entry: Record): string { + if (typeof entry.timestamp === "string" && entry.timestamp) return entry.timestamp; + const message = entry.message; + if (isRecord(message) && typeof message.timestamp === "number" && Number.isFinite(message.timestamp)) { + return new Date(message.timestamp).toISOString(); + } + return ""; +} diff --git a/server/routes.ts b/server/routes.ts index c87c165e4..8008fc211 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -63,6 +63,7 @@ import * as sessionsId from "@/app/api/sessions/[id]/route"; import * as sessionsIdState from "@/app/api/sessions/[id]/state/route"; import * as sessionsIdSubagentsSubagentId from "@/app/api/sessions/[id]/subagents/[subagentId]/route"; import * as sessionsIdSubagents from "@/app/api/sessions/[id]/subagents/route"; +import * as sessionsMessagesSearch from "@/app/api/sessions/messages/search/route"; import * as sessionsArchive from "@/app/api/sessions/archive/route"; import * as sessionsImport from "@/app/api/sessions/import/route"; import * as sessions from "@/app/api/sessions/route"; @@ -167,6 +168,7 @@ export const ROUTE_MODULES: Record = { "sessions/[id]/state": sessionsIdState, "sessions/[id]/subagents/[subagentId]": sessionsIdSubagentsSubagentId, "sessions/[id]/subagents": sessionsIdSubagents, + "sessions/messages/search": sessionsMessagesSearch, "sessions/archive": sessionsArchive, "sessions/import": sessionsImport, "sessions": sessions, From bf0165152bb5e249c3f46b30ad69a525059caec1 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:04:36 +0100 Subject: [PATCH 2/7] fix(search): honour aborts, cache the listing, and cursor by session id Maintainer triage of #410 asked for four operational boundaries; each one is fixed at the boundary the probe exercised: - `req.signal` is passed into the scan. An aborted request stops at the next chunk (and between files) with `SearchAbortedError`, the route releases its slot and answers 499 instead of holding both slots for a scan nobody reads. - The session listing is memoized per sessions-root mtime (plus a TTL for NTFS, where a write inside a project subdirectory does not bump the root). Only cursor pages reuse it, so a fresh search still sees a session created a second ago, and a pagination run no longer pays ~300 ms of synchronous directory walking per page before its time budget even starts. - The cursor carries the session id instead of the absolute session-file path, so it discloses nothing the hits do not already contain. Ties in mtime are broken by id for the same reason. - The module documents what the answer does and does not cover: this machine only (`scope: "local"` in the response), files above 64 MiB skipped, two concurrent scans per process, and a cursor as a snapshot of the corpus. Also from the inline review: `limit` is parsed as strict decimal digits (`0x10`/`1e2` are now 400, not 16/100), and the 500 path logs the error message instead of the error object, whose stack and `path` property carry absolute paths. --- app/api/sessions/messages/search/route.ts | 43 ++++-- lib/session-message-search.test.mjs | 135 ++++++++++++++++- lib/session-message-search.ts | 168 +++++++++++++++++++--- 3 files changed, 317 insertions(+), 29 deletions(-) diff --git a/app/api/sessions/messages/search/route.ts b/app/api/sessions/messages/search/route.ts index 5bcc4e137..db613aaca 100644 --- a/app/api/sessions/messages/search/route.ts +++ b/app/api/sessions/messages/search/route.ts @@ -2,6 +2,7 @@ import { decodeSearchCursor, releaseSearchSlot, searchSessionMessages, + SearchAbortedError, SearchCursorError, SEARCH_DEFAULT_LIMIT, SEARCH_MAX_LIMIT, @@ -15,16 +16,33 @@ function badRequest(error: string, code: string): Response { return Response.json({ error, code }, { status: 400, headers: NO_STORE }); } +/** + * Strict decimal integer: `Number("0x10")` and `Number("1e2")` would accept + * hex and exponent notation, which a `limit` query parameter never means. + */ +function parseLimit(raw: string | null): number | null { + if (raw === null) return SEARCH_DEFAULT_LIMIT; + if (!/^\d{1,3}$/.test(raw)) return null; + return Number(raw); +} + /** * GET /api/sessions/messages/search?q=&limit=&cursor= * - * Read-only full-text search across the session files of this machine. The + * Read-only full-text search across the session files **of this machine**. The * scan is bounded: results are newest-first, `partial:true` plus `cursor` mean * "call again for the next slice". Authentication is the normal omp-web gate * in `proxy.ts`, because this lives under `/api/`. * - * At most `SEARCH_MAX_CONCURRENT` scans run per process; further requests get - * `429` + `Retry-After` instead of starving the event loop. + * `scope: "local"` is part of the answer: sessions of linked hosts are not + * searched, and a client must not present an empty page as a global result. + * Files above 64 MiB and lines above 1 MiB are skipped (`skippedFiles` counts + * the former). At most `SEARCH_MAX_CONCURRENT` scans run per process; further + * requests get `429` + `Retry-After` instead of starving the event loop, so a + * client that paginates while another search runs can see that answer. + * + * A client that disconnects aborts `req.signal`; the scan stops at the next + * chunk boundary, the slot is released, and no response body is written. */ export async function GET(req: Request): Promise { const url = new URL(req.url); @@ -34,9 +52,8 @@ export async function GET(req: Request): Promise { return badRequest(`Search query is too long (max ${SEARCH_MAX_QUERY_LENGTH})`, "query_too_long"); } - const rawLimit = url.searchParams.get("limit"); - const limit = rawLimit === null ? SEARCH_DEFAULT_LIMIT : Number(rawLimit); - if (!Number.isSafeInteger(limit) || limit < 1 || limit > SEARCH_MAX_LIMIT) { + const limit = parseLimit(url.searchParams.get("limit")); + if (limit === null || limit < 1 || limit > SEARCH_MAX_LIMIT) { return badRequest(`limit must be an integer between 1 and ${SEARCH_MAX_LIMIT}`, "invalid_limit"); } @@ -56,10 +73,12 @@ export async function GET(req: Request): Promise { const page = await searchSessionMessages({ query, limit, + signal: req.signal, ...(rawCursor !== null ? { cursor: rawCursor } : {}), }); return Response.json({ query, + scope: "local", results: page.results, partial: page.partial, cursor: page.cursor, @@ -68,14 +87,22 @@ export async function GET(req: Request): Promise { skippedFiles: page.skippedFiles, }, { headers: NO_STORE }); } catch (error) { + if (error instanceof SearchAbortedError) { + // The client is gone; nobody reads this, but the slot must be free. + return new Response(null, { status: 499, headers: NO_STORE }); + } if (error instanceof SearchCursorError) { return badRequest( error.message === "cursor_query_mismatch" ? "Cursor belongs to another search" : "Invalid search cursor", error.message, ); } - // fs/parse failures can carry absolute paths; keep them server-side. - console.error("[api/sessions/messages/search]", error); + // fs/parse failures can carry absolute paths; log the message only, never + // the error object (its stack and `path` property would reach the log). + console.error( + "[api/sessions/messages/search] search failed:", + error instanceof Error ? error.message : String(error), + ); return Response.json({ error: "Search failed", code: "internal_error" }, { status: 500, headers: NO_STORE }); } finally { releaseSearchSlot(); diff --git a/lib/session-message-search.test.mjs b/lib/session-message-search.test.mjs index 4f9c1f0f3..a8f6804aa 100644 --- a/lib/session-message-search.test.mjs +++ b/lib/session-message-search.test.mjs @@ -89,12 +89,14 @@ async function withAgentDir(run) { const previous = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = agentDir; invalidateSessionListCache(); + search.invalidateSessionSearchListing(); try { await run(projectDir); } finally { if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previous; invalidateSessionListCache(); + search.invalidateSessionSearchListing(); rmSync(agentDir, { recursive: true, force: true }); } } @@ -349,6 +351,9 @@ test("lines that start exactly at a chunk boundary are matched exactly once", as const decoded = search.decodeSearchCursor(cursor); assert.ok(decoded); assert.ok(decoded.offset === 0 || raw[decoded.offset - 1] === 0x0a, "cursor must point at a line start"); + // The cursor names the session, never the server's file path. + assert.equal(decoded.sessionId, "s-uniform"); + assert.equal(JSON.stringify(decoded).includes(filePath), false, "the cursor must not disclose the file path"); } pages++; assert.ok(pages < 40, "pagination must terminate"); @@ -412,7 +417,7 @@ test("a cursor survives deleting one of two files with the same mtime", async (t { path: pathB, id: "s-b", cwd: "/w/b", title: "", size: statSync(pathB).size, modifiedMs: 1000 }, ]; - // The tie is broken by path, so a.jsonl (one hit left after the page) comes first. + // The tie is broken by session id, so s-a (one hit left after the page) comes first. const first = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS, sessions: files }); assert.deepEqual(first.results.map((hit) => hit.entryId), ["a-2"]); assert.ok(first.cursor); @@ -423,8 +428,8 @@ test("a cursor survives deleting one of two files with the same mtime", async (t cursor: first.cursor, sessions: [files[1]], }); - // a-1 was still unscanned but its file is gone; b.jsonl has the same mtime - // and comes after it, so it must not be skipped. + // a-1 was still unscanned but its session is gone; s-b has the same mtime + // and sorts after it, so it must not be skipped. assert.deepEqual(resumed.results.map((hit) => hit.entryId), ["b-1"]); }); @@ -527,3 +532,127 @@ test("route answers 429 while the scan slots are taken and recovers after releas assert.equal(search.tryAcquireSearchSlot(), true); search.releaseSearchSlot(); }); + +test("an aborted scan stops and reports SearchAbortedError instead of finishing", async (t) => { + const { dir, files } = fixture(); + t.after(() => rmSync(dir, { recursive: true, force: true })); + + // Already aborted: the scan must not even list. + let listed = false; + await assert.rejects( + () => search.searchSessionMessages({ + query: "needle", + signal: AbortSignal.abort(), + listSessions: async () => { listed = true; return files; }, + }), + (error) => error.name === "SearchAbortedError", + ); + assert.equal(listed, false, "an aborted request must not start the listing"); + + // Aborted while the listing runs: the check after it must stop the scan. + const afterListing = new AbortController(); + await assert.rejects( + () => search.searchSessionMessages({ + query: "needle", + signal: afterListing.signal, + listSessions: async () => { afterListing.abort(); return files; }, + budgetMs: TEST_BUDGET_MS, + }), + (error) => error.name === "SearchAbortedError", + ); + + // Aborted mid-file: the per-chunk check must stop the read loop. One large + // file means no per-file check can rescue it, and the clock count proves the + // scan stopped early instead of reading the rest of the file. + const abortDir = mkdtempSync(join(tmpdir(), "omp-web-search-abort-")); + t.after(() => rmSync(abortDir, { recursive: true, force: true })); + const lines = []; + for (let index = 0; index < 400; index++) lines.push(message(`ab-${index}`, "user", `needle abort filler ${index}`)); + const abortPath = writeSession(abortDir, "abort.jsonl", sessionFile("s-abort", "/w", lines), 1000); + const abortFiles = [{ path: abortPath, id: "s-abort", cwd: "/w", title: "", size: statSync(abortPath).size, modifiedMs: 1000 }]; + assert.ok(abortFiles[0].size > 64 * 100, "the fixture must need many chunks"); + + const midScan = new AbortController(); + let clockCalls = 0; + await assert.rejects( + () => search.searchSessionMessages({ + query: "needle", + signal: midScan.signal, + sessions: abortFiles, + chunkBytes: 64, + budgetMs: TEST_BUDGET_MS, + now: () => { + clockCalls++; + if (clockCalls === 3) midScan.abort(); + return 0; + }, + }), + (error) => error.name === "SearchAbortedError", + ); + assert.ok(clockCalls < 20, `the scan must stop at the abort, not read the whole file (${clockCalls} chunks)`); +}); + +test("the route releases its slot and answers 499 when the client aborted", async (t) => { + t.after(() => { + search.releaseSearchSlot(); + search.releaseSearchSlot(); + }); + const controller = new AbortController(); + controller.abort(); + const response = await route.GET(new Request("http://localhost/api/sessions/messages/search?q=needle", { + signal: controller.signal, + })); + assert.equal(response.status, 499); + assert.equal(response.headers.get("cache-control"), "no-store"); + // Both slots are free again: the aborted request released the one it took. + assert.equal(search.tryAcquireSearchSlot(), true); + assert.equal(search.tryAcquireSearchSlot(), true); + assert.equal(search.tryAcquireSearchSlot(), false); +}); + +test("the route reports local scope and rejects non-decimal limits", async () => { + const get = (query) => route.GET(new Request(`http://localhost/api/sessions/messages/search${query}`)); + for (const raw of ["0x10", "1e2", " 5", "5.0", "1000"]) { + const response = await get(`?q=needle&limit=${encodeURIComponent(raw)}`); + assert.equal(response.status, 400, `limit=${raw} must be rejected`); + assert.equal((await response.json()).code, "invalid_limit"); + } + + await withAgentDir(async (projectDir) => { + writeSession(projectDir, "scope.jsonl", sessionFile("scope-1", "/work/scope", [ + message("sc-1", "user", "scope needle"), + ]), 1_000); + const body = await (await get("?q=needle")).json(); + // Sessions of linked hosts are not searched; the answer says so. + assert.equal(body.scope, "local"); + }); +}); + +test("paginated searches reuse the listing instead of walking the directory per page", async () => { + await withAgentDir(async (projectDir) => { + writeSession(projectDir, "one.jsonl", sessionFile("cache-1", "/work/cache", [ + message("c-1", "user", "cache needle one"), + message("c-2", "user", "cache needle two"), + ]), 1_000); + search.invalidateSessionSearchListing(); + + const first = await search.loadSessionSearchFilesForPage(Date.now); + assert.deepEqual(first.map((file) => file.id), ["cache-1"]); + + // Unchanged root: the same listing object, i.e. no second directory walk. + const second = await search.loadSessionSearchFilesForPage(Date.now); + assert.equal(second, first, "a page must reuse the cached listing"); + + // A new session bumps the sessions root's mtime on every platform, which + // must invalidate the cache (otherwise a new session stays invisible). + writeSession(projectDir, "two.jsonl", sessionFile("cache-2", "/work/cache", [ + message("c-3", "user", "cache needle three"), + ]), 2_000); + const root = join(projectDir, ".."); + const now = Date.now() / 1000; + utimesSync(root, now, now); + const third = await search.loadSessionSearchFilesForPage(Date.now); + assert.notEqual(third, first); + assert.deepEqual(third.map((file) => file.id).sort(), ["cache-1", "cache-2"]); + }); +}); diff --git a/lib/session-message-search.ts b/lib/session-message-search.ts index b77404f4c..247b7f238 100644 --- a/lib/session-message-search.ts +++ b/lib/session-message-search.ts @@ -1,7 +1,8 @@ import { createHash } from "crypto"; -import { open } from "fs/promises"; +import { open, stat } from "fs/promises"; import { isRecord } from "./type-guards"; import { listAllSessionInfos, type OmpSessionInfo } from "./omp/session-files"; +import { getSessionsDir } from "./omp/paths"; /** * Full-text search over the on-disk omp session files. @@ -18,6 +19,28 @@ import { listAllSessionInfos, type OmpSessionInfo } from "./omp/session-files"; * Only `message` entries are considered: user and assistant text blocks. * Thinking blocks, tool results and tool-call arguments are not searchable, * matching what the web transcript actually shows. + * + * Scope and limits, so a client never reads more into an empty page than it + * proves: + * + * - **This machine only.** The scan reads the session directory of the + * omp-web process. Sessions of linked hosts (the daemon on another + * machine) are not searched and cannot be; the route reports + * `scope: "local"` so a native client does not present an empty answer as + * a global search. + * - **Files above 64 MiB are skipped** and counted in `skippedFiles`; their + * messages are not searchable. Lines above 1 MiB are skipped too. + * - **Two scans per process.** A third concurrent request is refused with + * 429 `search_busy` + `Retry-After`; a client that paginates while another + * search runs can see that answer. + * - **A cursor is a snapshot.** Sessions created after the first page are + * not included, and a session that grows between pages is scanned only + * below the cursor offset, so lines appended in the meantime are not + * returned by that pagination run. + * + * A request may carry an `AbortSignal`; an aborted scan stops at the next + * chunk/line boundary and throws `SearchAbortedError`, so the caller's slot is + * released instead of being held by work nobody reads. */ export const SEARCH_TIME_BUDGET_MS = 5_000; @@ -52,7 +75,12 @@ interface SearchSlotHost { } const searchSlotHost = globalThis as unknown as SearchSlotHost; -/** Reserve a scan slot; the caller MUST call `releaseSearchSlot` afterwards. */ +/** Reserve a scan slot; the caller MUST call `releaseSearchSlot` afterwards. + * + * The read-check-write below is safe because it runs to completion without an + * `await`: JavaScript is single-threaded, so no other request can observe the + * counter between the read and the write. Keep it that way — an `await` (or a + * move to a worker) would need an `Atomics`-backed counter instead. */ export function tryAcquireSearchSlot(): boolean { const active = searchSlotHost.__ompActiveSessionSearches ?? 0; if (active >= SEARCH_MAX_CONCURRENT) return false; @@ -85,13 +113,18 @@ export interface SessionSearchCursor { v: 1; /** Fingerprint of the query/option set the cursor belongs to. */ q: string; - path: string; + /** + * Session id the scan resumes at. The id — not the session file path — is + * what the cursor carries: a path would disclose the server's home + * directory for no benefit, and the id is already in every hit. + */ + sessionId: string; /** * Resume scanning bytes strictly below this offset. It is a line start, * except after a >1 MiB line was skipped mid-way. */ offset: number; - /** Used only when the cursor's file vanished: continue with older files. */ + /** Used only when the cursor's session vanished: continue with older ones. */ modifiedMs: number; } @@ -120,6 +153,8 @@ export interface SessionSearchOptions { query: string; limit?: number; cursor?: string; + /** Aborted by the HTTP layer when the client disconnects. */ + signal?: AbortSignal; /** Test hooks; production uses the defaults. */ now?: () => number; budgetMs?: number; @@ -139,6 +174,19 @@ export class SearchCursorError extends Error { } } +/** The request went away; the scan stopped early and its slot was released. */ +export class SearchAbortedError extends Error { + constructor() { + super("search_aborted"); + this.name = "SearchAbortedError"; + } +} + +/** Throw when the caller's request has been aborted. */ +function throwIfAborted(signal: AbortSignal | undefined): void { + if (signal?.aborted) throw new SearchAbortedError(); +} + /** Query fingerprint so a cursor cannot be replayed against another search. */ export function searchQueryKey(query: string): string { return createHash("sha1") @@ -161,18 +209,55 @@ export function decodeSearchCursor(raw: string): SessionSearchCursor | undefined if (!isRecord(value)) return undefined; if (value.v !== 1) return undefined; if (typeof value.q !== "string" || !value.q) return undefined; - if (typeof value.path !== "string" || !value.path) return undefined; + if (typeof value.sessionId !== "string" || !value.sessionId) return undefined; if (typeof value.offset !== "number" || !Number.isSafeInteger(value.offset) || value.offset < 0) return undefined; if (typeof value.modifiedMs !== "number" || !Number.isFinite(value.modifiedMs)) return undefined; return { v: 1, q: value.q, - path: value.path, + sessionId: value.sessionId, offset: value.offset, modifiedMs: value.modifiedMs, }; } +/** + * Cached session listing for the pages of one pagination run. + * + * `listAllSessionInfos()` walks the session directory and stats every file + * synchronously. On a 4,000-file corpus that is ~300 ms of blocked event loop + * per call — paid again on every page of one pagination run, and *before* the + * time budget starts, so the advertised budget covered only the cheap part. + * + * The cache is used only when a cursor is present: a fresh search always lists + * from disk, so a session created a second ago is found. Pages of a run reuse + * the listing the first page saw, which is what the cursor's snapshot + * semantics already promise. It is keyed by the sessions root and that + * directory's mtime — creating or deleting a session bumps it — and bounded by + * a TTL for filesystems where a write inside a project subdirectory leaves the + * root mtime alone (Windows/NTFS; see `listSessionFiles`). One entry, on + * `globalThis` so `bun --hot` re-evaluations share it. + */ +const SEARCH_LISTING_CACHE_TTL_MS = 5 * 60_000; + +interface SearchListingCacheEntry { + root: string; + rootMtimeMs: number; + at: number; + files: SessionSearchFile[]; +} + +interface SearchListingCacheHost { + __ompSessionSearchListing?: SearchListingCacheEntry; +} + +const listingCacheHost = globalThis as unknown as SearchListingCacheHost; + +/** Drop the pagination listing cache (tests and explicit invalidation). */ +export function invalidateSessionSearchListing(): void { + listingCacheHost.__ompSessionSearchListing = undefined; +} + /** Production file list: the same newest-first metadata the sidebar uses. */ export async function loadSessionSearchFiles(): Promise { const infos: OmpSessionInfo[] = await listAllSessionInfos(); @@ -186,6 +271,36 @@ export async function loadSessionSearchFiles(): Promise { })); } +/** + * Listing for a paginated search: the cached one when it still describes this + * sessions root, otherwise a fresh walk that becomes the new cache entry. + */ +export async function loadSessionSearchFilesForPage( + now: () => number, +): Promise { + const root = getSessionsDir(); + let rootMtimeMs: number; + try { + rootMtimeMs = (await stat(root)).mtimeMs; + } catch { + // No sessions directory: an empty corpus, and nothing to cache. + invalidateSessionSearchListing(); + return []; + } + const cached = listingCacheHost.__ompSessionSearchListing; + if ( + cached && + cached.root === root && + cached.rootMtimeMs === rootMtimeMs && + now() - cached.at < SEARCH_LISTING_CACHE_TTL_MS + ) { + return cached.files; + } + const files = await loadSessionSearchFiles(); + listingCacheHost.__ompSessionSearchListing = { root, rootMtimeMs, at: now(), files }; + return files; +} + interface Segment { /** Byte offset of the segment's first byte inside the file. */ start: number; @@ -208,24 +323,30 @@ export async function searchSessionMessages(options: SessionSearchOptions): Prom const fileScanBytes = Math.max(chunkBytes, options.maxFileScanBytes ?? DEFAULT_FILE_SCAN_BYTES); const totalScanBytes = Math.max(chunkBytes, options.maxTotalScanBytes ?? DEFAULT_TOTAL_SCAN_BYTES); const key = searchQueryKey(query); + const signal = options.signal; if (!query) { return { results: [], partial: false, cursor: null, scannedFiles: 0, scannedBytes: 0, skippedFiles: 0 }; } + throwIfAborted(signal); // Case-insensitive substring search without `toLowerCase()` on the haystack: // a lowercasing pass changes the length for some characters (e.g. "İ"), so // an offset found there would slice the wrong part of the original text. const matcher = new RegExp(escapeRegExp(query), "i"); - // Equal mtimes are ordered by path so the vanished-file fallback below can - // tell "older" from "same age but already handled" deterministically. + // Equal mtimes are ordered by session id so the vanished-session fallback + // below can tell "older" from "same age but already handled" without the + // cursor having to carry a file path. // The deadline is armed *after* the listing: enumerating a large session // directory must not consume the scan budget, or the first page would come - // back empty with a cursor that never advances. + // back empty with a cursor that never advances. `loadSessionSearchFilesForPage` + // memoizes that listing per sessions-root mtime, so a pagination run pays + // for the walk once instead of on every page. const files = (options.sessions ? [...options.sessions] - : await (options.listSessions ?? loadSessionSearchFiles)()) - .sort((a, b) => b.modifiedMs - a.modifiedMs || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + : await (options.listSessions ?? (options.cursor ? () => loadSessionSearchFilesForPage(now) : loadSessionSearchFiles))()) + .sort((a, b) => b.modifiedMs - a.modifiedMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); + throwIfAborted(signal); const deadline = now() + Math.max(1, options.budgetMs ?? SEARCH_TIME_BUDGET_MS); let startIndex = 0; @@ -236,18 +357,18 @@ export async function searchSessionMessages(options: SessionSearchOptions): Prom const cursor = decodeSearchCursor(options.cursor); if (!cursor) throw new SearchCursorError("invalid_cursor"); if (cursor.q !== key) throw new SearchCursorError("cursor_query_mismatch"); - const index = files.findIndex((file) => file.path === cursor.path); + const index = files.findIndex((file) => file.id === cursor.sessionId); if (index >= 0) { startIndex = index; startOffset = cursor.offset; } else { - // The session file disappeared between pages: everything older than it - // is still unscanned, so continue there instead of failing the page. - // "Older" follows the sort order above (mtime, then path). + // The session disappeared between pages: everything older than it is + // still unscanned, so continue there instead of failing the page. + // "Older" follows the sort order above (mtime, then session id). const fallback = files.findIndex( (file) => file.modifiedMs < cursor.modifiedMs || - (file.modifiedMs === cursor.modifiedMs && file.path > cursor.path), + (file.modifiedMs === cursor.modifiedMs && file.id > cursor.sessionId), ); if (fallback < 0) { return { results: [], partial: false, cursor: null, scannedFiles: 0, scannedBytes: 0, skippedFiles: 0 }; @@ -266,12 +387,14 @@ export async function searchSessionMessages(options: SessionSearchOptions): Prom const cursorFor = (file: SessionSearchFile, offset: number): SessionSearchCursor => ({ v: 1, q: key, - path: file.path, + sessionId: file.id, offset, modifiedMs: file.modifiedMs, }); for (let index = startIndex; index < files.length; index++) { + // A client that hung up must not keep a slot while its page is built. + throwIfAborted(signal); const file = files[index]; const resuming = index === startIndex && startOffset !== undefined; const boundary = Math.min(resuming ? startOffset! : file.size, file.size); @@ -297,6 +420,7 @@ export async function searchSessionMessages(options: SessionSearchOptions): Prom chunkBytes, byteCap: fileScanBytes, totalByteCap: totalScanBytes - scannedBytes, + ...(signal ? { signal } : {}), }); scannedFiles++; scannedBytes += outcome.bytes; @@ -341,6 +465,7 @@ interface ScanFileOptions { chunkBytes: number; byteCap: number; totalByteCap: number; + signal?: AbortSignal; } /** A physical line that crosses the current chunk boundary. */ @@ -384,6 +509,10 @@ async function scanFileBackwards(options: ScanFileOptions): Promise if (boundary > size) boundary = size; while (boundary > 0) { + // Checked per chunk (the read below is the only await in this loop), so + // an abandoned request stops within one read instead of scanning the + // rest of the file while holding its slot. + throwIfAborted(options.signal); let chunkLength = Math.min( options.chunkBytes, boundary, @@ -503,7 +632,10 @@ async function scanFileBackwards(options: ScanFileOptions): Promise } return { hits, bytes: bytesRead, done: true }; - } catch { + } catch (error) { + // An abandoned request is not an unreadable file: let the caller release + // its slot and answer nothing. + if (error instanceof SearchAbortedError) throw error; // Unreadable file (permissions, deleted mid-scan): skip it, like the list. return { hits, bytes: bytesRead, done: true }; } finally { From a3322b08dbe9f79dbcfe5237edb52e31c4446d86 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:33:16 +0100 Subject: [PATCH 3/7] fix(search): a fresh search installs the listing its cursor pages use A continuation could page a listing older than the search that issued its cursor: only cursor pages touched the shared pagination cache, so a fresh search's own walk was never installed. If another search had warmed the cache with an older corpus, page 2 fell back to it, silently skipping the new session's remaining hits (s-new page 1, then s-old on page 2). Every search now walks and installs its listing, and a cursor page reuses the installed one, so a continuation always pages the corpus its first page saw and a run pays for the walk once even when the cache starts empty. Entries carry a sequence number claimed before their walk: a walk that began earlier can finish later, and it no longer replaces a newer listing another search installed. Regressions at the real searchSessionMessages boundary: an s-old/s-new warm cache with a pinned sessions-root mtime (page 1 new-2, page 2 must be new-1, not old-2), a walk counter proving one walk per run, and an overlapping-walk case where the older walk finishes last. --- lib/session-message-search.test.mjs | 151 ++++++++++++++++++++++++++++ lib/session-message-search.ts | 122 ++++++++++++++++++---- 2 files changed, 251 insertions(+), 22 deletions(-) diff --git a/lib/session-message-search.test.mjs b/lib/session-message-search.test.mjs index a8f6804aa..1f2650c17 100644 --- a/lib/session-message-search.test.mjs +++ b/lib/session-message-search.test.mjs @@ -656,3 +656,154 @@ test("paginated searches reuse the listing instead of walking the directory per assert.deepEqual(third.map((file) => file.id).sort(), ["cache-1", "cache-2"]); }); }); + +/** + * The sessions root's mtime is the only thing the pagination cache keys on, so + * a session written into an existing project directory can leave it untouched + * (Windows/NTFS, and any filesystem where a subdirectory write does not reach + * the parent). Pin it, so these fixtures model exactly that case. + */ +function pinRootMtime(projectDir) { + const root = join(projectDir, ".."); + const seconds = 1_000; + utimesSync(root, seconds, seconds); +} + +test("a fresh search establishes the listing its cursor pages continue from", async () => { + await withAgentDir(async (projectDir) => { + // An older pagination run warms the shared cache with a corpus that only + // knows s-old; s-new then appears without the sessions root's mtime moving. + writeSession(projectDir, "old.jsonl", sessionFile("s-old", "/work/old", [ + message("old-1", "user", "needle in the old session"), + message("old-2", "user", "another needle in the old session"), + ]), 1_000); + pinRootMtime(projectDir); + + const warmFirst = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS }); + assert.deepEqual(warmFirst.results.map((hit) => hit.sessionId), ["s-old"]); + assert.ok(warmFirst.cursor); + // Page 2 of that run installs the s-old-only listing in the shared cache. + const warmSecond = await search.searchSessionMessages({ + query: "needle", + cursor: warmFirst.cursor, + limit: 1, + budgetMs: TEST_BUDGET_MS, + }); + assert.deepEqual(warmSecond.results.map((hit) => hit.entryId), ["old-1"]); + + writeSession(projectDir, "new.jsonl", sessionFile("s-new", "/work/new", [ + message("new-1", "user", "needle in the new session"), + message("new-2", "user", "second needle in the new session"), + ]), 2_000); + pinRootMtime(projectDir); + // Session mutations invalidate the ordinary list cache, not the search one. + invalidateSessionListCache(); + + // A fresh search must page its OWN listing: page 1 finds s-new, so page 2 + // must continue inside s-new instead of falling back to the older corpus. + const first = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS }); + assert.deepEqual(first.results.map((hit) => hit.entryId), ["new-2"]); + assert.ok(first.cursor, "a limit=1 page over two hits must return a cursor"); + + const seen = [...first.results.map((hit) => hit.entryId)]; + let cursor = first.cursor; + for (let page = 0; cursor && page < 10; page++) { + const next = await search.searchSessionMessages({ + query: "needle", + cursor, + limit: 1, + budgetMs: TEST_BUDGET_MS, + }); + seen.push(...next.results.map((hit) => hit.entryId)); + cursor = next.cursor; + } + assert.equal(cursor, null, "the run must terminate"); + // The whole corpus in newest-first order. The defect this guards against + // skipped new-1: page 2 fell back to the older listing and answered + // old-2, so the sequence was ["new-2", "old-2", "old-1"]. + assert.deepEqual(seen, ["new-2", "new-1", "old-2", "old-1"]); + }); +}); + +test("a pagination run walks the corpus once even when the cache starts empty", async () => { + await withAgentDir(async (projectDir) => { + const path = writeSession(projectDir, "one.jsonl", sessionFile("run-1", "/work/run", [ + message("r-1", "user", "run needle one"), + message("r-2", "user", "run needle two"), + message("r-3", "user", "run needle three"), + ]), 1_000); + pinRootMtime(projectDir); + search.invalidateSessionSearchListing(); + + // Count the real walks: an initially empty cache must not pay for the + // fresh search's walk AND another one on the first continuation. + let walks = 0; + const countingWalk = async () => { + walks++; + return [{ path, id: "run-1", cwd: "/work/run", title: "", size: statSync(path).size, modifiedMs: 1_000 }]; + }; + + const first = await search.searchSessionMessages({ + query: "needle", + limit: 1, + listSessions: countingWalk, + budgetMs: TEST_BUDGET_MS, + }); + assert.deepEqual(first.results.map((hit) => hit.entryId), ["r-3"]); + assert.ok(first.cursor); + assert.equal(walks, 1, "the fresh search walks once"); + + const second = await search.searchSessionMessages({ + query: "needle", + cursor: first.cursor, + limit: 1, + listSessions: countingWalk, + budgetMs: TEST_BUDGET_MS, + }); + // Page 2 reuses the installed listing: no second walk. + assert.equal(walks, 1, "a continuation must not walk the corpus again"); + assert.deepEqual(second.results.map((hit) => hit.entryId), ["r-2"]); + }); +}); + +test("a slower walk that started earlier never replaces the newer listing", async () => { + await withAgentDir(async (projectDir) => { + writeSession(projectDir, "one.jsonl", sessionFile("seq-1", "/work/seq", [ + message("s-1", "user", "seq needle one"), + ]), 1_000); + pinRootMtime(projectDir); + search.invalidateSessionSearchListing(); + + // Two fresh searches overlap: the second one's walk finishes first, the + // first one's walk (which saw an older corpus) finishes last. + const slow = search.searchSessionMessages({ + query: "needle", + listSessions: async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + return [{ + path: join(projectDir, "one.jsonl"), + id: "seq-1", + cwd: "/work/seq", + title: "", + size: statSync(join(projectDir, "one.jsonl")).size, + modifiedMs: 1_000, + }]; + }, + budgetMs: TEST_BUDGET_MS, + }); + // Give the slow walk a head start so its sequence number is claimed first. + await new Promise((resolve) => setTimeout(resolve, 5)); + + writeSession(projectDir, "two.jsonl", sessionFile("seq-2", "/work/seq", [ + message("s-2", "user", "seq needle two"), + ]), 2_000); + pinRootMtime(projectDir); + const fast = await search.searchSessionMessages({ query: "needle", budgetMs: TEST_BUDGET_MS }); + assert.deepEqual(fast.results.map((hit) => hit.sessionId), ["seq-2", "seq-1"]); + + await slow; + // The newer listing survives: a cursor page still sees seq-2. + const files = await search.loadSessionSearchFilesForPage(Date.now); + assert.deepEqual(files.map((file) => file.id).sort(), ["seq-1", "seq-2"]); + }); +}); diff --git a/lib/session-message-search.ts b/lib/session-message-search.ts index 247b7f238..add1e95cc 100644 --- a/lib/session-message-search.ts +++ b/lib/session-message-search.ts @@ -229,18 +229,26 @@ export function decodeSearchCursor(raw: string): SessionSearchCursor | undefined * per call — paid again on every page of one pagination run, and *before* the * time budget starts, so the advertised budget covered only the cheap part. * - * The cache is used only when a cursor is present: a fresh search always lists - * from disk, so a session created a second ago is found. Pages of a run reuse - * the listing the first page saw, which is what the cursor's snapshot - * semantics already promise. It is keyed by the sessions root and that - * directory's mtime — creating or deleting a session bumps it — and bounded by - * a TTL for filesystems where a write inside a project subdirectory leaves the - * root mtime alone (Windows/NTFS; see `listSessionFiles`). One entry, on - * `globalThis` so `bun --hot` re-evaluations share it. + * Every search installs the listing it scanned, and a cursor page reuses the + * installed one. A continuation therefore always pages the same corpus its + * first page saw — never a listing older than the search that issued the + * cursor — and a run pays for the walk once instead of on every page. A fresh + * search still walks unconditionally, so a session created a second ago is + * found even where a write inside a project subdirectory leaves the sessions + * root's mtime alone (Windows/NTFS; see `listSessionFiles`). + * + * The entry is keyed by the sessions root and that directory's mtime, and + * bounded by a TTL for filesystems where a session write leaves the root mtime + * alone. Each entry carries the sequence number claimed *before* its walk: a + * walk that started earlier can finish later, and it must not replace a newer + * listing another search installed meanwhile. One entry, on `globalThis` so + * `bun --hot` re-evaluations share it. */ const SEARCH_LISTING_CACHE_TTL_MS = 5 * 60_000; interface SearchListingCacheEntry { + /** Claimed before this entry's walk started; a higher number is newer. */ + seq: number; root: string; rootMtimeMs: number; at: number; @@ -249,6 +257,7 @@ interface SearchListingCacheEntry { interface SearchListingCacheHost { __ompSessionSearchListing?: SearchListingCacheEntry; + __ompSessionSearchListingSeq?: number; } const listingCacheHost = globalThis as unknown as SearchListingCacheHost; @@ -258,8 +267,31 @@ export function invalidateSessionSearchListing(): void { listingCacheHost.__ompSessionSearchListing = undefined; } +/** + * Claim the next listing sequence number. Called *before* a walk starts, so + * two overlapping walks are ordered by when they began rather than when they + * happened to finish. + */ +function claimListingSeq(): number { + const next = (listingCacheHost.__ompSessionSearchListingSeq ?? 0) + 1; + listingCacheHost.__ompSessionSearchListingSeq = next; + return next; +} + +/** + * Install a walked listing. A walk that began earlier (`seq` lower) must not + * replace a newer listing another search installed while it was running: the + * newer one describes a corpus at least as recent, and a cursor page may only + * ever see a listing at least as new as the search that issued its cursor. + */ +function installSessionSearchListing(entry: Omit, seq: number): void { + const current = listingCacheHost.__ompSessionSearchListing; + if (current && current.seq > seq) return; + listingCacheHost.__ompSessionSearchListing = { seq, ...entry }; +} + /** Production file list: the same newest-first metadata the sidebar uses. */ -export async function loadSessionSearchFiles(): Promise { +async function loadSessionSearchFiles(): Promise { const infos: OmpSessionInfo[] = await listAllSessionInfos(); return infos.map((info) => ({ path: info.path, @@ -272,18 +304,49 @@ export async function loadSessionSearchFiles(): Promise { } /** - * Listing for a paginated search: the cached one when it still describes this + * Walk the corpus and install it as the listing for this search's pages. + * + * The root mtime is sampled *before* the walk: a session created while the + * walk runs then leaves the recorded mtime behind the real one, so the next + * page re-walks instead of trusting a listing that predates the new session. + */ +async function walkAndInstallSessionSearchListing( + now: () => number, + walk: () => Promise, + knownRootMtimeMs?: number, +): Promise { + const root = getSessionsDir(); + let rootMtimeMs = knownRootMtimeMs; + if (rootMtimeMs === undefined) { + try { + rootMtimeMs = (await stat(root)).mtimeMs; + } catch { + // No sessions directory: an empty corpus, and nothing to cache. + } + } + const seq = claimListingSeq(); + const files = await walk(); + if (rootMtimeMs !== undefined) { + installSessionSearchListing({ root, rootMtimeMs, at: now(), files }, seq); + } + return files; +} + +/** + * Listing for a cursor page: the installed one when it still describes this * sessions root, otherwise a fresh walk that becomes the new cache entry. + * Either answer is at least as new as the search that issued the cursor, + * because the fresh search installed its own listing before answering. */ export async function loadSessionSearchFilesForPage( now: () => number, + walk: () => Promise = loadSessionSearchFiles, ): Promise { const root = getSessionsDir(); let rootMtimeMs: number; try { rootMtimeMs = (await stat(root)).mtimeMs; } catch { - // No sessions directory: an empty corpus, and nothing to cache. invalidateSessionSearchListing(); return []; } @@ -296,9 +359,7 @@ export async function loadSessionSearchFilesForPage( ) { return cached.files; } - const files = await loadSessionSearchFiles(); - listingCacheHost.__ompSessionSearchListing = { root, rootMtimeMs, at: now(), files }; - return files; + return walkAndInstallSessionSearchListing(now, walk, rootMtimeMs); } interface Segment { @@ -334,17 +395,37 @@ export async function searchSessionMessages(options: SessionSearchOptions): Prom // a lowercasing pass changes the length for some characters (e.g. "İ"), so // an offset found there would slice the wrong part of the original text. const matcher = new RegExp(escapeRegExp(query), "i"); + + // Decode before listing: a cursor that does not belong to this query must + // not cost a directory walk. + let cursor: SessionSearchCursor | undefined; + if (options.cursor) { + cursor = decodeSearchCursor(options.cursor); + if (!cursor) throw new SearchCursorError("invalid_cursor"); + if (cursor.q !== key) throw new SearchCursorError("cursor_query_mismatch"); + } + // Equal mtimes are ordered by session id so the vanished-session fallback // below can tell "older" from "same age but already handled" without the // cursor having to carry a file path. // The deadline is armed *after* the listing: enumerating a large session // directory must not consume the scan budget, or the first page would come - // back empty with a cursor that never advances. `loadSessionSearchFilesForPage` - // memoizes that listing per sessions-root mtime, so a pagination run pays - // for the walk once instead of on every page. + // back empty with a cursor that never advances. + // + // A fresh search walks the corpus and installs it as the listing its cursor + // pages will reuse, so a run pays for the walk once. Installing here — not + // only when a page asks for a listing — is what keeps a continuation from + // paging a listing older than the search that issued its cursor. + const listSessions = options.listSessions; const files = (options.sessions ? [...options.sessions] - : await (options.listSessions ?? (options.cursor ? () => loadSessionSearchFilesForPage(now) : loadSessionSearchFiles))()) + : await (listSessions + ? () => (cursor + ? loadSessionSearchFilesForPage(now, listSessions) + : walkAndInstallSessionSearchListing(now, listSessions)) + : cursor + ? () => loadSessionSearchFilesForPage(now) + : () => walkAndInstallSessionSearchListing(now, loadSessionSearchFiles))()) .sort((a, b) => b.modifiedMs - a.modifiedMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); throwIfAborted(signal); const deadline = now() + Math.max(1, options.budgetMs ?? SEARCH_TIME_BUDGET_MS); @@ -353,10 +434,7 @@ export async function searchSessionMessages(options: SessionSearchOptions): Prom let startOffset: number | undefined; let remainingResults = limit; - if (options.cursor) { - const cursor = decodeSearchCursor(options.cursor); - if (!cursor) throw new SearchCursorError("invalid_cursor"); - if (cursor.q !== key) throw new SearchCursorError("cursor_query_mismatch"); + if (cursor) { const index = files.findIndex((file) => file.id === cursor.sessionId); if (index >= 0) { startIndex = index; From 1bd026e5e4431295c36195f052cb9988ff70b74e Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:06:08 +0100 Subject: [PATCH 4/7] fix(search): bind pagination to the run's listing and yield the walk A cursor page resolved its resume index against whatever the shared listing cache held at that moment. Another client's search re-walked the same directory and replaced that entry, so a continuation could page a corpus its first page never saw: a session that received a message and sorted above the cursor was skipped entirely (probe: a-1, b-2, b-1, c-1 answered a-1, c-1 and reported the run complete), and a session whose mtime dropped below the cursor was scanned twice (x-1, y-2, y-1, x-1). Every run now owns its listing. The first page walks once and installs the result under a fresh monotonic id, the cursor carries that id, and each continuation resolves exactly that snapshot, so nothing another search does can reorder the run. Snapshots expire after five idle minutes (sliding, so an actively paginated run never expires) or when newer runs evict them (four stay addressable); a continuation whose snapshot is gone answers 409 cursor_expired instead of guessing, because re-walking would silently skip or repeat hits. The listing walk is also off the critical path now: listAllSessionInfos yields to the event loop every few milliseconds. On a real 4,000-file corpus the cold walk held the loop for 526-695 ms with zero timer ticks and a fresh search stalled 501-554 ms; afterwards the same walk lets 34-39 ticks through with a 26-28 ms maximum stall, and a fresh search stalls 24-27 ms. The walk is charged to the same 5 s budget as the scan, so a page's total time is bounded too. Also: a CHANGELOG entry for the new route, and the listing-seq counter that invalidateSessionSearchListing left behind is gone with the old single-entry cache. --- CHANGELOG.md | 4 + app/api/sessions/messages/search/route.ts | 14 + lib/omp/session-files.ts | 32 ++- lib/session-message-search.test.mjs | 320 ++++++++++++++++++---- lib/session-message-search.ts | 268 ++++++++++-------- 5 files changed, 475 insertions(+), 163 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 548e9ad55..4c83cb6e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Added + +- **Native clients can search the messages of every session on this machine.** `GET /api/sessions/messages/search?q=&limit=&cursor=` scans the session transcripts of the omp-web server's own machine newest-first and answers `{ results, partial, cursor, scannedFiles, scannedBytes, skippedFiles }` plus `scope: "local"`, so a client never presents an empty answer as a global result. Sessions of linked hosts are not searched. Each request is bounded — result count, per-file and total bytes, and a 5-second budget that now also covers the session listing — and answers `partial: true` with an opaque cursor for the next slice. A cursor belongs to the listing snapshot its first page installed, so a pagination run neither skips nor repeats a session when the corpus changes underneath it or another client searches at the same time; a run whose snapshot expired (idle for five minutes, or evicted by newer runs) answers `409 cursor_expired` and the client starts over. Files above 64 MiB and lines above 1 MiB are skipped, and at most two scans run per process (`429` + `Retry-After` beyond that). The capability flag `messageSearch` is advertised by `GET /api/app-info` together with the route. + ## [v0.7.4] - 2026-11-20 ### Fixed diff --git a/app/api/sessions/messages/search/route.ts b/app/api/sessions/messages/search/route.ts index db613aaca..92b82e6f1 100644 --- a/app/api/sessions/messages/search/route.ts +++ b/app/api/sessions/messages/search/route.ts @@ -41,6 +41,11 @@ function parseLimit(raw: string | null): number | null { * requests get `429` + `Retry-After` instead of starving the event loop, so a * client that paginates while another search runs can see that answer. * + * A cursor belongs to the listing snapshot its first page installed. When that + * snapshot is gone (the run was idle for five minutes, or newer runs evicted + * it), the route answers `409 cursor_expired` rather than paging a re-walked + * corpus that could skip or repeat hits; the client restarts the search. + * * A client that disconnects aborts `req.signal`; the scan stops at the next * chunk boundary, the slot is released, and no response body is written. */ @@ -92,6 +97,15 @@ export async function GET(req: Request): Promise { return new Response(null, { status: 499, headers: NO_STORE }); } if (error instanceof SearchCursorError) { + // An expired snapshot is not a bad request: the cursor was valid, the + // run just outlived its listing. 409 tells the client to start over + // instead of "fix your cursor". + if (error.message === "cursor_expired") { + return Response.json( + { error: "Search cursor expired, start the search again", code: "cursor_expired" }, + { status: 409, headers: NO_STORE }, + ); + } return badRequest( error.message === "cursor_query_mismatch" ? "Cursor belongs to another search" : "Invalid search cursor", error.message, diff --git a/lib/omp/session-files.ts b/lib/omp/session-files.ts index 2524beccb..88cfce20c 100644 --- a/lib/omp/session-files.ts +++ b/lib/omp/session-files.ts @@ -1090,6 +1090,21 @@ function scanSessionInfoCached(filePath: string): OmpSessionInfo | undefined { return info; } +/** + * Longest stretch of scanning before {@link listAllSessionInfos} hands the + * event loop back. A per-file scan is one stat plus two small window reads, so + * a slice of a few files stays well inside this; the point is that a 4,000-file + * corpus no longer blocks the loop for seconds (measured: 4.8 s cold, 0 ticks). + */ +const SESSION_LIST_SLICE_MS = 8; + +/** Let queued I/O and timers run before the next slice. */ +function yieldToEventLoop(): Promise { + const { promise, resolve } = Promise.withResolvers(); + setImmediate(resolve); + return promise; +} + /** * List all sessions across all project subdirectories (newest first). Only * `//*.jsonl` files are scanned — per-session @@ -1101,15 +1116,28 @@ function scanSessionInfoCached(filePath: string): OmpSessionInfo | undefined { * invalidates for free on every add/remove while turning repeated listing * requests (sidebar poll, page loads) into a single stat. Per-file scanning is * still memoized by scanSessionInfoCached on (size, mtimeMs). + * + * The per-file scan is synchronous (statSync + readSync + JSON parse), so the + * loop yields to the event loop every {@link SESSION_LIST_SLICE_MS}: a cold + * 4,000-file walk used to hold the loop for ~4.8 s, starving every other + * request (the message search measured exactly that). Yielding between files + * bounds the stall to one slice plus one file instead of the whole corpus. */ export async function listAllSessionInfos(): Promise { const sessionsRoot = getSessionsDir(); const files = await listSessionFiles(sessionsRoot); const sessions: OmpSessionInfo[] = []; - for (const file of files) { - const info = scanSessionInfoCached(file); + let sliceStart = Date.now(); + for (let index = 0; index < files.length; index++) { + const info = scanSessionInfoCached(files[index]); if (info) sessions.push(info); + // Checked every few files: Date.now() per file would be wasted work, and a + // slice of four still keeps the stall at a few milliseconds. + if ((index & 3) === 3 && Date.now() - sliceStart >= SESSION_LIST_SLICE_MS) { + await yieldToEventLoop(); + sliceStart = Date.now(); + } } sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime()); return sessions; diff --git a/lib/session-message-search.test.mjs b/lib/session-message-search.test.mjs index 1f2650c17..8bd11da01 100644 --- a/lib/session-message-search.test.mjs +++ b/lib/session-message-search.test.mjs @@ -9,6 +9,7 @@ const search = await import("./session-message-search.ts"); const TEST_BUDGET_MS = 120_000; const route = await import("../app/api/sessions/messages/search/route.ts"); const { invalidateSessionListCache } = await import("./session-reader.ts"); +const sessionFiles = await import("./omp/session-files.ts"); function message(id, role, text, timestamp = "2026-01-01T00:00:00.000Z") { const content = role === "toolResult" @@ -216,12 +217,13 @@ test("a time/size budget stops the scan with a resumable cursor", async (t) => { assert.deepEqual(seen, ["a-user-2", "a-user-1", "b-assistant", "b-user"]); }); -test("the time budget starts after the session listing", async (t) => { +test("the listing walk is charged to the budget and yields the event loop", async (t) => { const { dir, files } = fixture(); t.after(() => rmSync(dir, { recursive: true, force: true })); - // A slow directory listing must not eat the scan budget: otherwise the very - // first page comes back empty with a cursor that never advances. + // The walk is inside the budget now: a walk that consumes it must leave the + // page partial with a cursor pointing at the first file, instead of the old + // behaviour where a slow listing was free and the page then scanned 5 s more. let clock = 0; const page = await search.searchSessionMessages({ query: "needle", @@ -232,9 +234,27 @@ test("the time budget starts after the session listing", async (t) => { }, budgetMs: 5_000, }); - assert.equal(page.partial, false); - assert.equal(page.cursor, null); - assert.deepEqual(page.results.map((hit) => hit.entryId), ["a-user-2", "a-user-1", "b-assistant", "b-user"]); + assert.equal(page.partial, true); + assert.ok(page.cursor, "an exhausted budget must still hand back a resumable cursor"); + assert.deepEqual(page.results, []); + assert.equal(page.scannedFiles, 0, "no file may be scanned once the budget is gone"); + + // The continuation is not stuck: it resolves the run's snapshot and makes + // progress with a fresh budget, so the run terminates rather than looping on + // an empty page forever. + const seen = []; + let cursor = page.cursor; + for (let pages = 0; cursor && pages < 20; pages++) { + const next = await search.searchSessionMessages({ + query: "needle", + cursor, + now: () => clock, + budgetMs: TEST_BUDGET_MS, + }); + seen.push(...next.results.map((hit) => hit.entryId)); + cursor = next.cursor; + } + assert.deepEqual(seen, ["a-user-2", "a-user-1", "b-assistant", "b-user"]); }); test("very large files are skipped", async (t) => { @@ -628,7 +648,7 @@ test("the route reports local scope and rejects non-decimal limits", async () => }); }); -test("paginated searches reuse the listing instead of walking the directory per page", async () => { +test("a pagination run resolves its own listing snapshot, not the shared directory", async () => { await withAgentDir(async (projectDir) => { writeSession(projectDir, "one.jsonl", sessionFile("cache-1", "/work/cache", [ message("c-1", "user", "cache needle one"), @@ -636,24 +656,28 @@ test("paginated searches reuse the listing instead of walking the directory per ]), 1_000); search.invalidateSessionSearchListing(); - const first = await search.loadSessionSearchFilesForPage(Date.now); - assert.deepEqual(first.map((file) => file.id), ["cache-1"]); + const first = await search.startSessionSearchListing(Date.now); + assert.deepEqual(first.files.map((file) => file.id), ["cache-1"]); - // Unchanged root: the same listing object, i.e. no second directory walk. - const second = await search.loadSessionSearchFilesForPage(Date.now); - assert.equal(second, first, "a page must reuse the cached listing"); + // The same id resolves the identical snapshot object: no second walk. + const second = search.resumeSessionSearchListing(first.id, Date.now); + assert.equal(second, first.files, "a page must reuse its run's snapshot"); - // A new session bumps the sessions root's mtime on every platform, which - // must invalidate the cache (otherwise a new session stays invisible). + // A new session changes the directory, but the run's snapshot does not move: + // that is the point of binding the listing to the run. writeSession(projectDir, "two.jsonl", sessionFile("cache-2", "/work/cache", [ message("c-3", "user", "cache needle three"), ]), 2_000); const root = join(projectDir, ".."); const now = Date.now() / 1000; utimesSync(root, now, now); - const third = await search.loadSessionSearchFilesForPage(Date.now); - assert.notEqual(third, first); - assert.deepEqual(third.map((file) => file.id).sort(), ["cache-1", "cache-2"]); + const third = search.resumeSessionSearchListing(first.id, Date.now); + assert.equal(third, first.files, "another search's walk must not change this run's listing"); + + // A *new* run does see the new session. + const fresh = await search.startSessionSearchListing(Date.now); + assert.notEqual(fresh.id, first.id); + assert.deepEqual(fresh.files.map((file) => file.id).sort(), ["cache-1", "cache-2"]); }); }); @@ -735,8 +759,7 @@ test("a pagination run walks the corpus once even when the cache starts empty", pinRootMtime(projectDir); search.invalidateSessionSearchListing(); - // Count the real walks: an initially empty cache must not pay for the - // fresh search's walk AND another one on the first continuation. + // Count the real walks: a run must pay for exactly one, on its first page. let walks = 0; const countingWalk = async () => { walks++; @@ -760,50 +783,249 @@ test("a pagination run walks the corpus once even when the cache starts empty", listSessions: countingWalk, budgetMs: TEST_BUDGET_MS, }); - // Page 2 reuses the installed listing: no second walk. + // Page 2 resolves the run's snapshot: no second walk. assert.equal(walks, 1, "a continuation must not walk the corpus again"); assert.deepEqual(second.results.map((hit) => hit.entryId), ["r-2"]); }); }); -test("a slower walk that started earlier never replaces the newer listing", async () => { +test("the session listing walk yields the event loop instead of blocking it", async (t) => { + const agentDir = mkdtempSync(join(tmpdir(), "omp-web-search-yield-")); + const sessionsRoot = join(agentDir, "sessions"); + const projectDir = join(sessionsRoot, "-project"); + mkdirSync(projectDir, { recursive: true }); + t.after(() => rmSync(agentDir, { recursive: true, force: true })); + + // A real corpus: the per-file scan is statSync + readSync + JSON.parse, so + // this is the same synchronous work a production walk does. 1,000 files is + // ~1.2 s cold here, i.e. far more than one slice on any machine. + const FILE_COUNT = 1000; + for (let index = 0; index < FILE_COUNT; index++) { + writeFileSync( + join(projectDir, `yield-${index}.jsonl`), + sessionFile(`yield-${index}`, "/work/yield", [message(`y-${index}`, "user", `needle ${index}`)]), + "utf8", + ); + } + + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = agentDir; + try { + sessionFiles.invalidateAllSessionScanCaches(); + sessionFiles.invalidateSessionFileListCache(); + + let ticks = 0; + let maxGapMs = 0; + let last = performance.now(); + const timer = setInterval(() => { + const now = performance.now(); + maxGapMs = Math.max(maxGapMs, now - last); + last = now; + ticks++; + }, 10); + const started = performance.now(); + const infos = await sessionFiles.listAllSessionInfos(); + const durationMs = performance.now() - started; + clearInterval(timer); + + assert.equal(infos.length, FILE_COUNT); + // Before the fix this walk held the loop for its whole duration: 0 ticks, + // whatever the machine's speed. The assertion is relative to the walk's + // own duration, so it holds on a fast Linux CI box as well as on a loaded + // Windows host: the loop must get several turns, and no single stall may + // cover the walk. + assert.ok(ticks >= 2, `the walk must let timers run (${ticks} ticks in ${Math.round(durationMs)} ms)`); + assert.ok( + maxGapMs < durationMs / 2, + `no single stall may cover the walk (${Math.round(maxGapMs)} ms of ${Math.round(durationMs)} ms)`, + ); + } finally { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + sessionFiles.invalidateAllSessionScanCaches(); + sessionFiles.invalidateSessionFileListCache(); + } +}); + +test("a run keeps paging its own listing when another search re-walks the corpus", async () => { await withAgentDir(async (projectDir) => { - writeSession(projectDir, "one.jsonl", sessionFile("seq-1", "/work/seq", [ - message("s-1", "user", "seq needle one"), + // Corpus, newest first: a-1, b-2, b-1, c-1. + const aPath = writeSession(projectDir, "a.jsonl", sessionFile("s-a", "/w/a", [ + message("a-1", "user", "needle a one"), + ]), 4_000); + const bPath = writeSession(projectDir, "b.jsonl", sessionFile("s-b", "/w/b", [ + message("b-1", "user", "needle b one"), + message("b-2", "user", "needle b two"), + ]), 3_000); + const cPath = writeSession(projectDir, "c.jsonl", sessionFile("s-c", "/w/c", [ + message("c-1", "user", "needle c one"), + ]), 2_000); + pinRootMtime(projectDir); + search.invalidateSessionSearchListing(); + + const first = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS }); + assert.deepEqual(first.results.map((hit) => hit.entryId), ["a-1"]); + assert.ok(first.cursor); + + // Another client's fresh search re-walks the shared directory while an + // older session (s-b) receives a message, so s-b now sorts *above* the + // cursor session. A page that re-resolved an index in that new listing + // would start at s-b's new position and skip b-2/b-1 entirely. + writeSession(projectDir, "b.jsonl", sessionFile("s-b", "/w/b", [ + message("b-1", "user", "needle b one"), + message("b-2", "user", "needle b two"), + message("b-3", "user", "needle b three"), + ]), 5_000); + pinRootMtime(projectDir); + invalidateSessionListCache(); + const other = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS }); + assert.deepEqual(other.results.map((hit) => hit.entryId), ["b-3"], "the other search sees the new order"); + + const seen = [...first.results.map((hit) => hit.entryId)]; + let cursor = first.cursor; + for (let page = 0; cursor && page < 20; page++) { + const next = await search.searchSessionMessages({ + query: "needle", + cursor, + limit: 1, + budgetMs: TEST_BUDGET_MS, + }); + seen.push(...next.results.map((hit) => hit.entryId)); + cursor = next.cursor; + } + assert.equal(cursor, null, "the run must terminate"); + // Exactly the run's own snapshot, in its own order: b-2 and b-1 are not + // skipped, and nothing is returned twice. The defect this guards against + // answered ["a-1", "c-1"] and reported the run complete. + assert.deepEqual(seen, ["a-1", "b-2", "b-1", "c-1"]); + + // The paths exist so the fixture above is a real corpus, not just stubs. + for (const path of [aPath, bPath, cPath]) assert.ok(statSync(path).size > 0); + }); +}); + +test("a session that moves below the cursor is never returned twice", async () => { + await withAgentDir(async (projectDir) => { + // Corpus, newest first: x-1, y-2, y-1. + writeSession(projectDir, "x.jsonl", sessionFile("s-x", "/w/x", [ + message("x-1", "user", "needle x one"), + ]), 3_000); + writeSession(projectDir, "y.jsonl", sessionFile("s-y", "/w/y", [ + message("y-1", "user", "needle y one"), + message("y-2", "user", "needle y two"), + ]), 2_000); + pinRootMtime(projectDir); + search.invalidateSessionSearchListing(); + + const first = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS }); + assert.deepEqual(first.results.map((hit) => hit.entryId), ["x-1"]); + assert.ok(first.cursor); + + // s-x's mtime drops below the cursor session: in a re-walked listing the + // already-scanned s-x would sort after the cursor and be scanned again. + writeSession(projectDir, "x.jsonl", sessionFile("s-x", "/w/x", [ + message("x-1", "user", "needle x one"), + ]), 1_000); + pinRootMtime(projectDir); + invalidateSessionListCache(); + await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS }); + + const seen = [...first.results.map((hit) => hit.entryId)]; + let cursor = first.cursor; + for (let page = 0; cursor && page < 20; page++) { + const next = await search.searchSessionMessages({ + query: "needle", + cursor, + limit: 1, + budgetMs: TEST_BUDGET_MS, + }); + seen.push(...next.results.map((hit) => hit.entryId)); + cursor = next.cursor; + } + assert.deepEqual(seen, ["x-1", "y-2", "y-1"], "x-1 must not appear twice"); + }); +}); + +test("a continuation whose snapshot expired is refused instead of re-walking", async () => { + await withAgentDir(async (projectDir) => { + writeSession(projectDir, "one.jsonl", sessionFile("exp-1", "/w/exp", [ + message("e-1", "user", "needle expired one"), + message("e-2", "user", "needle expired two"), ]), 1_000); pinRootMtime(projectDir); search.invalidateSessionSearchListing(); - // Two fresh searches overlap: the second one's walk finishes first, the - // first one's walk (which saw an older corpus) finishes last. - const slow = search.searchSessionMessages({ + const first = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS }); + assert.ok(first.cursor); + + // Explicit invalidation models the TTL/LRU eviction: the run's listing is + // gone, and paging a fresh corpus could skip or repeat hits. + search.invalidateSessionSearchListing(); + await assert.rejects( + () => search.searchSessionMessages({ query: "needle", cursor: first.cursor, budgetMs: TEST_BUDGET_MS }), + (error) => error.name === "SearchCursorError" && error.message === "cursor_expired", + ); + + // The route reports it as a restart instruction, not as a broken cursor. + const response = await route.GET(new Request( + `http://localhost/api/sessions/messages/search?q=needle&cursor=${encodeURIComponent(first.cursor)}`, + )); + assert.equal(response.status, 409); + assert.equal((await response.json()).code, "cursor_expired"); + }); +}); + +test("a run's snapshot expires after five idle minutes and is evicted by newer runs", async () => { + await withAgentDir(async (projectDir) => { + writeSession(projectDir, "one.jsonl", sessionFile("ttl-1", "/w/ttl", [ + message("t-1", "user", "needle ttl one"), + ]), 1_000); + pinRootMtime(projectDir); + search.invalidateSessionSearchListing(); + + // A fake clock makes the TTL deterministic: five minutes is a real wait. + let clock = 1_000_000; + const first = await search.searchSessionMessages({ query: "needle", - listSessions: async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - return [{ - path: join(projectDir, "one.jsonl"), - id: "seq-1", - cwd: "/work/seq", - title: "", - size: statSync(join(projectDir, "one.jsonl")).size, - modifiedMs: 1_000, - }]; - }, + limit: 1, + now: () => clock, + listSessions: async () => [{ + path: join(projectDir, "one.jsonl"), + id: "ttl-1", + cwd: "/w/ttl", + title: "", + size: statSync(join(projectDir, "one.jsonl")).size, + modifiedMs: 1_000, + }], budgetMs: TEST_BUDGET_MS, }); - // Give the slow walk a head start so its sequence number is claimed first. - await new Promise((resolve) => setTimeout(resolve, 5)); + assert.ok(first.cursor); - writeSession(projectDir, "two.jsonl", sessionFile("seq-2", "/work/seq", [ - message("s-2", "user", "seq needle two"), - ]), 2_000); - pinRootMtime(projectDir); - const fast = await search.searchSessionMessages({ query: "needle", budgetMs: TEST_BUDGET_MS }); - assert.deepEqual(fast.results.map((hit) => hit.sessionId), ["seq-2", "seq-1"]); + // The TTL is sliding, not absolute: a run that keeps paginating every four + // minutes stays alive for far longer than five minutes in total. + const listingId = search.decodeSearchCursor(first.cursor).l; + for (let page = 0; page < 5; page++) { + clock += 4 * 60_000; + assert.ok( + search.resumeSessionSearchListing(listingId, () => clock), + `page ${page + 1} of an active run must not expire (${(page + 1) * 4} minutes after page 1)`, + ); + } + + // Five idle minutes after the last use: gone. + clock += 5 * 60_000; + assert.equal(search.resumeSessionSearchListing(listingId, () => clock), undefined); - await slow; - // The newer listing survives: a cursor page still sees seq-2. - const files = await search.loadSessionSearchFilesForPage(Date.now); - assert.deepEqual(files.map((file) => file.id).sort(), ["seq-1", "seq-2"]); + // Eviction: five live runs, the oldest is dropped. + search.invalidateSessionSearchListing(); + const ids = []; + for (let index = 0; index < 5; index++) { + const installed = search.installSessionSearchListing(() => clock, []); + ids.push(installed.id); + } + assert.equal(search.resumeSessionSearchListing(ids[0], () => clock), undefined, "the oldest run is evicted"); + for (const id of ids.slice(1)) { + assert.ok(search.resumeSessionSearchListing(id, () => clock), `${id} stays addressable`); + } }); }); diff --git a/lib/session-message-search.ts b/lib/session-message-search.ts index add1e95cc..70142978b 100644 --- a/lib/session-message-search.ts +++ b/lib/session-message-search.ts @@ -1,5 +1,5 @@ import { createHash } from "crypto"; -import { open, stat } from "fs/promises"; +import { open } from "fs/promises"; import { isRecord } from "./type-guards"; import { listAllSessionInfos, type OmpSessionInfo } from "./omp/session-files"; import { getSessionsDir } from "./omp/paths"; @@ -36,7 +36,17 @@ import { getSessionsDir } from "./omp/paths"; * - **A cursor is a snapshot.** Sessions created after the first page are * not included, and a session that grows between pages is scanned only * below the cursor offset, so lines appended in the meantime are not - * returned by that pagination run. + * returned by that pagination run. The first page's session listing is + * bound to the run: every page resolves the same snapshot, so a session + * that another client's search re-walked into a different position can + * neither be skipped nor returned twice. A run whose snapshot expired + * (idle for five minutes, or evicted by newer runs) is refused with + * `cursor_expired`; the client restarts the search instead of receiving a + * silently incomplete answer. + * - **The budget covers the whole page.** The listing walk is charged to the + * same 5 s budget as the scan, and the walk yields to the event loop every + * few milliseconds, so a cold 4,000-file corpus no longer blocks other + * requests or hides its cost from the budget. * * A request may carry an `AbortSignal`; an aborted scan stops at the next * chunk/line boundary and throws `SearchAbortedError`, so the caller's slot is @@ -113,6 +123,13 @@ export interface SessionSearchCursor { v: 1; /** Fingerprint of the query/option set the cursor belongs to. */ q: string; + /** + * Id of the listing snapshot this run's first page installed. Every page of + * the run resolves this id, so a continuation can never page a corpus other + * than the one page 1 scanned — not even after another search re-walked the + * shared directory. + */ + l: string; /** * Session id the scan resumes at. The id — not the session file path — is * what the cursor carries: a path would disclose the server's home @@ -209,12 +226,14 @@ export function decodeSearchCursor(raw: string): SessionSearchCursor | undefined if (!isRecord(value)) return undefined; if (value.v !== 1) return undefined; if (typeof value.q !== "string" || !value.q) return undefined; + if (typeof value.l !== "string" || !value.l) return undefined; if (typeof value.sessionId !== "string" || !value.sessionId) return undefined; if (typeof value.offset !== "number" || !Number.isSafeInteger(value.offset) || value.offset < 0) return undefined; if (typeof value.modifiedMs !== "number" || !Number.isFinite(value.modifiedMs)) return undefined; return { v: 1, q: value.q, + l: value.l, sessionId: value.sessionId, offset: value.offset, modifiedMs: value.modifiedMs, @@ -222,72 +241,79 @@ export function decodeSearchCursor(raw: string): SessionSearchCursor | undefined } /** - * Cached session listing for the pages of one pagination run. + * Listing snapshots, one per pagination run. * - * `listAllSessionInfos()` walks the session directory and stats every file - * synchronously. On a 4,000-file corpus that is ~300 ms of blocked event loop - * per call — paid again on every page of one pagination run, and *before* the - * time budget starts, so the advertised budget covered only the cheap part. + * A page must never resolve its cursor against a listing other than the one + * its first page scanned. The corpus moves underneath a run — sessions are + * created, renamed and rewritten, and another client's search walks the same + * directory — so a page that re-walked (or reused a shared, re-walked entry) + * would answer from a *different* ordering: sessions between the two orderings + * are skipped, and a session that moved below the cursor is scanned twice. + * Both were reproducible with a real listing and scanner before this design. * - * Every search installs the listing it scanned, and a cursor page reuses the - * installed one. A continuation therefore always pages the same corpus its - * first page saw — never a listing older than the search that issued the - * cursor — and a run pays for the walk once instead of on every page. A fresh - * search still walks unconditionally, so a session created a second ago is - * found even where a write inside a project subdirectory leaves the sessions - * root's mtime alone (Windows/NTFS; see `listSessionFiles`). + * The first page therefore walks once and installs the result under a fresh + * id; the cursor carries that id, and every continuation resolves it. Nothing + * another search does can replace or invalidate a run's snapshot. A snapshot + * is dropped only when it is evicted (LRU, {@link SEARCH_LISTING_SNAPSHOTS} + * runs) or unused for {@link SEARCH_LISTING_TTL_MS} — the TTL is sliding, so + * an actively paginated run never expires. A continuation whose snapshot is + * gone is refused with `cursor_expired` instead of guessing: walking a fresh + * corpus would silently skip or repeat hits, and an explicit restart is the + * only honest answer. * - * The entry is keyed by the sessions root and that directory's mtime, and - * bounded by a TTL for filesystems where a session write leaves the root mtime - * alone. Each entry carries the sequence number claimed *before* its walk: a - * walk that started earlier can finish later, and it must not replace a newer - * listing another search installed meanwhile. One entry, on `globalThis` so - * `bun --hot` re-evaluations share it. + * A fresh search still walks unconditionally, so a session created a second + * ago is found even where a write inside a project subdirectory leaves the + * sessions root's mtime alone (Windows/NTFS; see `listSessionFiles`). The map + * lives on `globalThis` so `bun --hot` re-evaluations share it. */ -const SEARCH_LISTING_CACHE_TTL_MS = 5 * 60_000; +const SEARCH_LISTING_TTL_MS = 5 * 60_000; +/** Concurrent pagination runs whose snapshots stay addressable. */ +const SEARCH_LISTING_SNAPSHOTS = 4; -interface SearchListingCacheEntry { - /** Claimed before this entry's walk started; a higher number is newer. */ - seq: number; +interface SearchListingSnapshot { + id: string; + /** Sessions root the walk saw; a snapshot never crosses roots. */ root: string; - rootMtimeMs: number; + /** Last use, for the sliding TTL and the LRU order. */ at: number; - files: SessionSearchFile[]; + files: readonly SessionSearchFile[]; } interface SearchListingCacheHost { - __ompSessionSearchListing?: SearchListingCacheEntry; - __ompSessionSearchListingSeq?: number; + __ompSessionSearchListings?: Map; + /** + * Monotonic id generator. Deliberately NOT reset by + * {@link invalidateSessionSearchListing}: ids must never be reused, or a + * cursor from a dropped run could resolve a later run's snapshot and page a + * corpus it never scanned. Only the id counter survives an invalidation, and + * it carries no corpus state. + */ + __ompSessionSearchListingIds?: number; } const listingCacheHost = globalThis as unknown as SearchListingCacheHost; -/** Drop the pagination listing cache (tests and explicit invalidation). */ +/** Drop every pagination listing snapshot (tests and explicit invalidation). */ export function invalidateSessionSearchListing(): void { - listingCacheHost.__ompSessionSearchListing = undefined; + listingCacheHost.__ompSessionSearchListings?.clear(); } -/** - * Claim the next listing sequence number. Called *before* a walk starts, so - * two overlapping walks are ordered by when they began rather than when they - * happened to finish. - */ -function claimListingSeq(): number { - const next = (listingCacheHost.__ompSessionSearchListingSeq ?? 0) + 1; - listingCacheHost.__ompSessionSearchListingSeq = next; - return next; +function getListingSnapshots(): Map { + if (!listingCacheHost.__ompSessionSearchListings) { + listingCacheHost.__ompSessionSearchListings = new Map(); + } + return listingCacheHost.__ompSessionSearchListings; } /** - * Install a walked listing. A walk that began earlier (`seq` lower) must not - * replace a newer listing another search installed while it was running: the - * newer one describes a corpus at least as recent, and a cursor page may only - * ever see a listing at least as new as the search that issued its cursor. + * Newest first, equal mtimes ordered by session id. One order for the whole + * run: it is applied once, when the snapshot is installed, so every page of + * the run sees the identical sequence. */ -function installSessionSearchListing(entry: Omit, seq: number): void { - const current = listingCacheHost.__ompSessionSearchListing; - if (current && current.seq > seq) return; - listingCacheHost.__ompSessionSearchListing = { seq, ...entry }; +function sortSessionSearchFiles(files: SessionSearchFile[]): SessionSearchFile[] { + return files.sort( + (a, b) => b.modifiedMs - a.modifiedMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0), + ); } /** Production file list: the same newest-first metadata the sidebar uses. */ @@ -303,63 +329,69 @@ async function loadSessionSearchFiles(): Promise { })); } +/** Evict expired snapshots, then the oldest beyond the run cap. */ +function pruneListingSnapshots(map: Map, now: number): void { + for (const [id, snapshot] of map) { + if (now - snapshot.at >= SEARCH_LISTING_TTL_MS) map.delete(id); + } + while (map.size > SEARCH_LISTING_SNAPSHOTS) { + const oldest = map.keys().next().value; + if (oldest === undefined) break; + map.delete(oldest); + } +} + /** - * Walk the corpus and install it as the listing for this search's pages. - * - * The root mtime is sampled *before* the walk: a session created while the - * walk runs then leaves the recorded mtime behind the real one, so the next - * page re-walks instead of trusting a listing that predates the new session. + * Install a corpus as a new run's listing and return its id. The array is + * sorted here, once, and stored as-is: pages read it, never mutate it. */ -async function walkAndInstallSessionSearchListing( +export function installSessionSearchListing( now: () => number, - walk: () => Promise, - knownRootMtimeMs?: number, -): Promise { - const root = getSessionsDir(); - let rootMtimeMs = knownRootMtimeMs; - if (rootMtimeMs === undefined) { - try { - rootMtimeMs = (await stat(root)).mtimeMs; - } catch { - // No sessions directory: an empty corpus, and nothing to cache. - } - } - const seq = claimListingSeq(); - const files = await walk(); - if (rootMtimeMs !== undefined) { - installSessionSearchListing({ root, rootMtimeMs, at: now(), files }, seq); - } - return files; + files: SessionSearchFile[], +): { id: string; files: readonly SessionSearchFile[] } { + const map = getListingSnapshots(); + const next = (listingCacheHost.__ompSessionSearchListingIds ?? 0) + 1; + listingCacheHost.__ompSessionSearchListingIds = next; + const id = `l${next}`; + const sorted = sortSessionSearchFiles(files); + map.set(id, { id, root: getSessionsDir(), at: now(), files: sorted }); + pruneListingSnapshots(map, now()); + return { id, files: sorted }; } /** - * Listing for a cursor page: the installed one when it still describes this - * sessions root, otherwise a fresh walk that becomes the new cache entry. - * Either answer is at least as new as the search that issued the cursor, - * because the fresh search installed its own listing before answering. + * Walk the corpus and install it as a new run's listing. The walk itself is + * the caller's: production passes {@link loadSessionSearchFiles}, tests pass a + * stub, and both end up as one immutable snapshot. */ -export async function loadSessionSearchFilesForPage( +export async function startSessionSearchListing( now: () => number, walk: () => Promise = loadSessionSearchFiles, -): Promise { - const root = getSessionsDir(); - let rootMtimeMs: number; - try { - rootMtimeMs = (await stat(root)).mtimeMs; - } catch { - invalidateSessionSearchListing(); - return []; - } - const cached = listingCacheHost.__ompSessionSearchListing; - if ( - cached && - cached.root === root && - cached.rootMtimeMs === rootMtimeMs && - now() - cached.at < SEARCH_LISTING_CACHE_TTL_MS - ) { - return cached.files; +): Promise<{ id: string; files: readonly SessionSearchFile[] }> { + return installSessionSearchListing(now, await walk()); +} + +/** + * The listing a continuation pages: exactly the snapshot its first page + * installed, or `undefined` when that snapshot is gone. Never a re-walk. + */ +export function resumeSessionSearchListing( + id: string, + now: () => number, +): readonly SessionSearchFile[] | undefined { + const map = getListingSnapshots(); + const snapshot = map.get(id); + if (!snapshot) return undefined; + if (snapshot.root !== getSessionsDir() || now() - snapshot.at >= SEARCH_LISTING_TTL_MS) { + map.delete(id); + return undefined; } - return walkAndInstallSessionSearchListing(now, walk, rootMtimeMs); + // Re-insert as the most recently used entry: the sliding TTL and the LRU + // order both follow actual pagination, not the walk that started the run. + map.delete(id); + snapshot.at = now(); + map.set(id, snapshot); + return snapshot.files; } interface Segment { @@ -408,27 +440,38 @@ export async function searchSessionMessages(options: SessionSearchOptions): Prom // Equal mtimes are ordered by session id so the vanished-session fallback // below can tell "older" from "same age but already handled" without the // cursor having to carry a file path. - // The deadline is armed *after* the listing: enumerating a large session - // directory must not consume the scan budget, or the first page would come - // back empty with a cursor that never advances. // - // A fresh search walks the corpus and installs it as the listing its cursor - // pages will reuse, so a run pays for the walk once. Installing here — not - // only when a page asks for a listing — is what keeps a continuation from - // paging a listing older than the search that issued its cursor. + // The corpus is bound to the run: a first page walks once and installs the + // result under a fresh listing id, the cursor carries that id, and every + // continuation resolves exactly that snapshot. Nothing another search does + // to the shared directory can change what this run pages, so a page can + // neither skip a session that was reordered above it nor rescan one that + // moved below it. + // + // The deadline is armed *before* the walk. The walk itself is bounded by the + // yielding listing (see `listAllSessionInfos`), so it no longer blocks the + // event loop for seconds; charging it to the budget keeps the page's total + // time bounded too, and the first page still returns hits instead of an + // empty page with a cursor that never advances. + const deadline = now() + Math.max(1, options.budgetMs ?? SEARCH_TIME_BUDGET_MS); const listSessions = options.listSessions; - const files = (options.sessions - ? [...options.sessions] - : await (listSessions - ? () => (cursor - ? loadSessionSearchFilesForPage(now, listSessions) - : walkAndInstallSessionSearchListing(now, listSessions)) - : cursor - ? () => loadSessionSearchFilesForPage(now) - : () => walkAndInstallSessionSearchListing(now, loadSessionSearchFiles))()) - .sort((a, b) => b.modifiedMs - a.modifiedMs || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); + let files: readonly SessionSearchFile[]; + let listingId: string; + if (options.sessions) { + const installed = installSessionSearchListing(now, [...options.sessions]); + files = installed.files; + listingId = installed.id; + } else if (cursor) { + const resumed = resumeSessionSearchListing(cursor.l, now); + if (!resumed) throw new SearchCursorError("cursor_expired"); + files = resumed; + listingId = cursor.l; + } else { + const installed = await startSessionSearchListing(now, listSessions ?? loadSessionSearchFiles); + files = installed.files; + listingId = installed.id; + } throwIfAborted(signal); - const deadline = now() + Math.max(1, options.budgetMs ?? SEARCH_TIME_BUDGET_MS); let startIndex = 0; let startOffset: number | undefined; @@ -465,6 +508,7 @@ export async function searchSessionMessages(options: SessionSearchOptions): Prom const cursorFor = (file: SessionSearchFile, offset: number): SessionSearchCursor => ({ v: 1, q: key, + l: listingId, sessionId: file.id, offset, modifiedMs: file.modifiedMs, From a493cee14ca4cb87ada53ef8964e93c8aae716e0 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:50:28 +0100 Subject: [PATCH 5/7] fix(search): scope listing ids to the process and bound the yield test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A listing id was `l` from a counter that restarts at 0 with the process, so a cursor minted before a server restart could name a number a new run had just claimed. The old cursor then resolved the new run's snapshot and paged a corpus its first page never scanned: a session that received a message and sorted between the two walks was skipped while the continuation reported the run complete. Ids now carry a per-process nonce (`l-`), so a cursor from a previous process resolves nothing and is refused with 409 cursor_expired — the honest answer, since its snapshot died with that process. The regression drops the snapshot map and the counter, imports a fresh module instance to model the restarted process, lets a session sort above the old cursor, and asserts the old cursor is refused. Mutation: reverting the id to `l` fails it with "Missing expected rejection" — the old cursor silently pages the new corpus instead. The yield regression asserted only that no stall covered half the walk, which a 431 ms stall inside a 7,738 ms walk passes, so it could not back the commit's numeric claim. It now asserts an absolute 500 ms stall bound plus a tick floor scaled to the walk's own duration. Measured here on 1,000 files: 25-53 ticks, worst stall 165 ms cold (79-83 ms warm), against 0 ticks and a 0.75-3.4 s block before the fix. The CHANGELOG entry now names the restart case among the reasons a cursor expires. --- CHANGELOG.md | 2 +- lib/session-message-search.test.mjs | 102 +++++++++++++++++++++++++--- lib/session-message-search.ts | 30 ++++++-- 3 files changed, 119 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c83cb6e5..1905fd04b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added -- **Native clients can search the messages of every session on this machine.** `GET /api/sessions/messages/search?q=&limit=&cursor=` scans the session transcripts of the omp-web server's own machine newest-first and answers `{ results, partial, cursor, scannedFiles, scannedBytes, skippedFiles }` plus `scope: "local"`, so a client never presents an empty answer as a global result. Sessions of linked hosts are not searched. Each request is bounded — result count, per-file and total bytes, and a 5-second budget that now also covers the session listing — and answers `partial: true` with an opaque cursor for the next slice. A cursor belongs to the listing snapshot its first page installed, so a pagination run neither skips nor repeats a session when the corpus changes underneath it or another client searches at the same time; a run whose snapshot expired (idle for five minutes, or evicted by newer runs) answers `409 cursor_expired` and the client starts over. Files above 64 MiB and lines above 1 MiB are skipped, and at most two scans run per process (`429` + `Retry-After` beyond that). The capability flag `messageSearch` is advertised by `GET /api/app-info` together with the route. +- **Native clients can search the messages of every session on this machine.** `GET /api/sessions/messages/search?q=&limit=&cursor=` scans the session transcripts of the omp-web server's own machine newest-first and answers `{ results, partial, cursor, scannedFiles, scannedBytes, skippedFiles }` plus `scope: "local"`, so a client never presents an empty answer as a global result. Sessions of linked hosts are not searched. Each request is bounded — result count, per-file and total bytes, and a 5-second budget that now also covers the session listing — and answers `partial: true` with an opaque cursor for the next slice. A cursor belongs to the listing snapshot its first page installed, so a pagination run neither skips nor repeats a session when the corpus changes underneath it or another client searches at the same time; a run whose snapshot expired (idle for five minutes, evicted by newer runs, or issued before a server restart) answers `409 cursor_expired` and the client starts over. Files above 64 MiB and lines above 1 MiB are skipped, and at most two scans run per process (`429` + `Retry-After` beyond that). The capability flag `messageSearch` is advertised by `GET /api/app-info` together with the route. ## [v0.7.4] - 2026-11-20 diff --git a/lib/session-message-search.test.mjs b/lib/session-message-search.test.mjs index 8bd11da01..be4e7b2d4 100644 --- a/lib/session-message-search.test.mjs +++ b/lib/session-message-search.test.mjs @@ -829,15 +829,30 @@ test("the session listing walk yields the event loop instead of blocking it", as clearInterval(timer); assert.equal(infos.length, FILE_COUNT); - // Before the fix this walk held the loop for its whole duration: 0 ticks, - // whatever the machine's speed. The assertion is relative to the walk's - // own duration, so it holds on a fast Linux CI box as well as on a loaded - // Windows host: the loop must get several turns, and no single stall may - // cover the walk. - assert.ok(ticks >= 2, `the walk must let timers run (${ticks} ticks in ${Math.round(durationMs)} ms)`); + // Before the fix this walk held the loop for its whole duration: zero + // timer ticks, whatever the machine's speed, and one stall as long as the + // walk. The assertions are therefore about the loop turning at all and + // about the worst single stall, not about a fraction of the walk: a walk + // that blocks for half its length would pass a relative bound while still + // being the stall this fix removes. + // + // Measured on this Windows host with this corpus: 25-53 ticks and a worst + // stall of 165 ms cold (79-83 ms warm), against 0 ticks and a 0.75-3.4 s + // block before. The tick floor scales with the walk's own duration so a + // fast Linux CI box is not asked for ticks it had no time to receive, + // while a walk that stops handing the loop back still fails: the pre-fix + // walk answers 0 ticks here on every platform. + const minimumTicks = Math.max(4, Math.floor(durationMs / 250)); assert.ok( - maxGapMs < durationMs / 2, - `no single stall may cover the walk (${Math.round(maxGapMs)} ms of ${Math.round(durationMs)} ms)`, + ticks >= minimumTicks, + `the walk must let timers run (${ticks} ticks in ${Math.round(durationMs)} ms, ${minimumTicks} required)`, + ); + // The absolute promise of the fix: no stretch of the walk holds the loop + // for half a second. A 10 ms timer is coalesced by the OS, so this is a + // stall bound, not a latency measurement. + assert.ok( + maxGapMs < 500, + `no single stall may reach 500 ms (${Math.round(maxGapMs)} ms of ${Math.round(durationMs)} ms)`, ); } finally { if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; @@ -1029,3 +1044,74 @@ test("a run's snapshot expires after five idle minutes and is evicted by newer r } }); }); + +test("a cursor from before a restart is refused instead of paging the new run's listing", async () => { + await withAgentDir(async (projectDir) => { + // Corpus, newest first: a-1, b-1, c-1. + writeSession(projectDir, "a.jsonl", sessionFile("s-a", "/w/a", [ + message("a-1", "user", "needle a one"), + ]), 4_000); + writeSession(projectDir, "b.jsonl", sessionFile("s-b", "/w/b", [ + message("b-1", "user", "needle b one"), + ]), 3_000); + writeSession(projectDir, "c.jsonl", sessionFile("s-c", "/w/c", [ + message("c-1", "user", "needle c one"), + ]), 2_000); + pinRootMtime(projectDir); + + // The run must be the first one in its process, or its id would be a + // number a restarted process never mints and the collision below could not + // happen. Resetting the counter models exactly that: a server that has + // just started. + delete globalThis.__ompSessionSearchListingIds; + const first = await search.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS }); + assert.deepEqual(first.results.map((hit) => hit.entryId), ["a-1"]); + assert.ok(first.cursor); + const oldListing = search.decodeSearchCursor(first.cursor).l; + + // A restart: the snapshot map and the id counter died with the old + // process, and the code answering the next request is a fresh module + // instance — a new nonce, a counter that starts at 0 again. + delete globalThis.__ompSessionSearchListings; + delete globalThis.__ompSessionSearchListingIds; + const restarted = await import("./session-message-search.ts?restart=1"); + + // s-b receives a message and sorts above the old cursor's session, so the + // new process's first page is a different corpus under the same numbering. + writeSession(projectDir, "b.jsonl", sessionFile("s-b", "/w/b", [ + message("b-1", "user", "needle b one"), + message("b-2", "user", "needle b two"), + ]), 5_000); + pinRootMtime(projectDir); + invalidateSessionListCache(); + + const fresh = await restarted.searchSessionMessages({ query: "needle", limit: 1, budgetMs: TEST_BUDGET_MS }); + assert.deepEqual(fresh.results.map((hit) => hit.entryId), ["b-2"], "the new process sees the new order"); + assert.ok(fresh.cursor); + const newListing = restarted.decodeSearchCursor(fresh.cursor).l; + + // The old cursor is refused, so the client restarts instead of receiving + // a page from a corpus it never saw. Without the nonce this resolves the + // new run's snapshot instead, and the continuation silently pages a + // corpus its first page never scanned — answering a-1, c-1 and skipping + // b-2/b-1 while reporting the run complete. + await assert.rejects( + () => restarted.searchSessionMessages({ query: "needle", cursor: first.cursor, budgetMs: TEST_BUDGET_MS }), + (error) => error.name === "SearchCursorError" && error.message === "cursor_expired", + ); + + // Why it is refused: listing ids are process-scoped, so the new run never + // claims the number the old cursor still names. + assert.notEqual(newListing, oldListing, "a restarted process must not reuse a listing id"); + + // The new run's own cursor still pages its own snapshot: the nonce + // separates processes, it does not break pagination inside one. + const second = await restarted.searchSessionMessages({ + query: "needle", + cursor: fresh.cursor, + limit: 1, + budgetMs: TEST_BUDGET_MS, + }); + assert.deepEqual(second.results.map((hit) => hit.entryId), ["b-1"]); + }); +}); diff --git a/lib/session-message-search.ts b/lib/session-message-search.ts index 70142978b..1ba5630ea 100644 --- a/lib/session-message-search.ts +++ b/lib/session-message-search.ts @@ -1,4 +1,4 @@ -import { createHash } from "crypto"; +import { createHash, randomUUID } from "crypto"; import { open } from "fs/promises"; import { isRecord } from "./type-guards"; import { listAllSessionInfos, type OmpSessionInfo } from "./omp/session-files"; @@ -265,6 +265,11 @@ export function decodeSearchCursor(raw: string): SessionSearchCursor | undefined * ago is found even where a write inside a project subdirectory leaves the * sessions root's mtime alone (Windows/NTFS; see `listSessionFiles`). The map * lives on `globalThis` so `bun --hot` re-evaluations share it. + * + * Snapshot ids are unique across processes, not just within one: the counter + * restarts at 0 after a restart, so ids carry {@link LISTING_ID_NONCE}. A + * cursor from before a restart therefore resolves nothing and is refused, + * instead of resolving a new run's snapshot that happens to reuse its number. */ const SEARCH_LISTING_TTL_MS = 5 * 60_000; /** Concurrent pagination runs whose snapshots stay addressable. */ @@ -283,16 +288,29 @@ interface SearchListingCacheHost { __ompSessionSearchListings?: Map; /** * Monotonic id generator. Deliberately NOT reset by - * {@link invalidateSessionSearchListing}: ids must never be reused, or a - * cursor from a dropped run could resolve a later run's snapshot and page a - * corpus it never scanned. Only the id counter survives an invalidation, and - * it carries no corpus state. + * {@link invalidateSessionSearchListing}: ids must never be reused within a + * process, or a cursor from a dropped run could resolve a later run's + * snapshot and page a corpus it never scanned. Only the id counter survives + * an invalidation, and it carries no corpus state. */ __ompSessionSearchListingIds?: number; } const listingCacheHost = globalThis as unknown as SearchListingCacheHost; +/** + * Distinguishes this process's listing ids from those of an earlier one. + * + * The counter above restarts at 0 after a server restart, so `l1` minted by a + * new process would collide with an `l1` an old cursor still names. A cursor + * is only meaningful against the snapshot it was issued for, and that snapshot + * died with the old process: without the nonce a new run's first page would + * claim the recycled id and an old cursor would silently page the new corpus, + * skipping every session that sorted between the two walks. The nonce makes + * such a cursor resolve nothing, which the caller reports as `cursor_expired`. + */ +const LISTING_ID_NONCE = randomUUID().slice(0, 8); + /** Drop every pagination listing snapshot (tests and explicit invalidation). */ export function invalidateSessionSearchListing(): void { listingCacheHost.__ompSessionSearchListings?.clear(); @@ -352,7 +370,7 @@ export function installSessionSearchListing( const map = getListingSnapshots(); const next = (listingCacheHost.__ompSessionSearchListingIds ?? 0) + 1; listingCacheHost.__ompSessionSearchListingIds = next; - const id = `l${next}`; + const id = `l${LISTING_ID_NONCE}-${next}`; const sorted = sortSessionSearchFiles(files); map.set(id, { id, root: getSessionsDir(), at: now(), files: sorted }); pruneListingSnapshots(map, now()); From 0d2b9d20ca7d3d6e24bbdced34d608b708f62b2e Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:18:13 +0100 Subject: [PATCH 6/7] test(search): count loop turns instead of timer ticks for the walk's yield --- lib/session-message-search.test.mjs | 38 +++++++++++++++++------------ 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/lib/session-message-search.test.mjs b/lib/session-message-search.test.mjs index be4e7b2d4..d2a66434a 100644 --- a/lib/session-message-search.test.mjs +++ b/lib/session-message-search.test.mjs @@ -823,29 +823,37 @@ test("the session listing walk yields the event loop instead of blocking it", as last = now; ticks++; }, 10); + // A setImmediate chain runs once per loop turn: it counts the walk's + // hand-backs exactly, independent of how fast the machine walks. + let yields = 0; + let walking = true; + const countTurn = () => { + if (!walking) return; + yields++; + setImmediate(countTurn); + }; + setImmediate(countTurn); const started = performance.now(); const infos = await sessionFiles.listAllSessionInfos(); const durationMs = performance.now() - started; + walking = false; clearInterval(timer); assert.equal(infos.length, FILE_COUNT); - // Before the fix this walk held the loop for its whole duration: zero - // timer ticks, whatever the machine's speed, and one stall as long as the - // walk. The assertions are therefore about the loop turning at all and - // about the worst single stall, not about a fraction of the walk: a walk - // that blocks for half its length would pass a relative bound while still - // being the stall this fix removes. + // Before the fix this walk held the loop for its whole duration: no loop + // turn at all until it returned, and one stall as long as the walk. The + // assertions are therefore about the loop turning at all and about the + // worst single stall, not about a fraction of the walk: a walk that blocks + // for half its length would pass a relative bound while still being the + // stall this fix removes. // - // Measured on this Windows host with this corpus: 25-53 ticks and a worst - // stall of 165 ms cold (79-83 ms warm), against 0 ticks and a 0.75-3.4 s - // block before. The tick floor scales with the walk's own duration so a - // fast Linux CI box is not asked for ticks it had no time to receive, - // while a walk that stops handing the loop back still fails: the pre-fix - // walk answers 0 ticks here on every platform. - const minimumTicks = Math.max(4, Math.floor(durationMs / 250)); + // Counting loop turns with a setImmediate chain is exact on any machine + // speed (a timer-tick floor is not: a fast walk may legitimately see fewer + // 10 ms ticks than a floor demands). The pre-fix walk turns the loop 0 + // times here on every platform. assert.ok( - ticks >= minimumTicks, - `the walk must let timers run (${ticks} ticks in ${Math.round(durationMs)} ms, ${minimumTicks} required)`, + yields >= 1, + `the walk must hand the loop back (${yields} turns, ${ticks} timer ticks in ${Math.round(durationMs)} ms)`, ); // The absolute promise of the fix: no stretch of the walk holds the loop // for half a second. A 10 ms timer is coalesced by the OS, so this is a From 66b2ab6143fbdbe911f000b0d5f8448bf02f77e1 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:46:29 +0100 Subject: [PATCH 7/7] feat(api): advertise the messageSearch capability with the search route #407 merged with only heartbeatParam: its body says sibling PRs add their own flag together with their implementation. The search route now exists here, so /api/app-info lists messageSearch next to it and the app-info test pins the exact capability set. --- app/api/app-info/route.ts | 2 ++ lib/app-info-route.test.mjs | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/app/api/app-info/route.ts b/app/api/app-info/route.ts index 3bf97adac..3f1986966 100644 --- a/app/api/app-info/route.ts +++ b/app/api/app-info/route.ts @@ -17,6 +17,8 @@ export function GET(): Response { capabilities: { /** `GET /api/events?heartbeat=<15..110>` chooses this connection's keep-alive. */ heartbeatParam: true, + /** `GET /api/sessions/messages/search?q=&limit=&cursor=` searches this machine's transcripts. */ + messageSearch: true, }, }, { headers: { "Cache-Control": "no-store" } }); } diff --git a/lib/app-info-route.test.mjs b/lib/app-info-route.test.mjs index e1da07862..f9fddf0f4 100644 --- a/lib/app-info-route.test.mjs +++ b/lib/app-info-route.test.mjs @@ -13,5 +13,5 @@ test("app-info identifies ompweb, its version and every capability it serves", a assert.equal(body.name, "ompweb"); assert.equal(body.version, pkg.version); assert.equal(body.api, 1); - assert.deepEqual(body.capabilities, { heartbeatParam: true }); + assert.deepEqual(body.capabilities, { heartbeatParam: true, messageSearch: true }); });