diff --git a/CHANGELOG.md b/CHANGELOG.md index 548e9ad55..1905fd04b 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, 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 ### Fixed 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/app/api/sessions/messages/search/route.ts b/app/api/sessions/messages/search/route.ts new file mode 100644 index 000000000..92b82e6f1 --- /dev/null +++ b/app/api/sessions/messages/search/route.ts @@ -0,0 +1,124 @@ +import { + decodeSearchCursor, + releaseSearchSlot, + searchSessionMessages, + SearchAbortedError, + 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 }); +} + +/** + * 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 + * 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/`. + * + * `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 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. + */ +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 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"); + } + + 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, + signal: req.signal, + ...(rawCursor !== null ? { cursor: rawCursor } : {}), + }); + return Response.json({ + query, + scope: "local", + 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 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) { + // 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, + ); + } + // 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/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 }); }); 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 new file mode 100644 index 000000000..d2a66434a --- /dev/null +++ b/lib/session-message-search.test.mjs @@ -0,0 +1,1125 @@ +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"); +const sessionFiles = await import("./omp/session-files.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(); + 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 }); + } +} + +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 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 })); + + // 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", + now: () => clock, + listSessions: async () => { + clock += 10_000; + return files; + }, + budgetMs: 5_000, + }); + 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) => { + 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"); + // 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"); + } 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 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); + + rmSync(pathA); + const resumed = await search.searchSessionMessages({ + query: "needle", + cursor: first.cursor, + sessions: [files[1]], + }); + // 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"]); +}); + +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(); +}); + +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("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"), + message("c-2", "user", "cache needle two"), + ]), 1_000); + search.invalidateSessionSearchListing(); + + const first = await search.startSessionSearchListing(Date.now); + assert.deepEqual(first.files.map((file) => file.id), ["cache-1"]); + + // 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 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 = 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"]); + }); +}); + +/** + * 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: a run must pay for exactly one, on its first page. + 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 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("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); + // 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: 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. + // + // 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( + 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 + // 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; + 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) => { + // 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(); + + 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", + 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, + }); + assert.ok(first.cursor); + + // 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); + + // 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`); + } + }); +}); + +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 new file mode 100644 index 000000000..1ba5630ea --- /dev/null +++ b/lib/session-message-search.ts @@ -0,0 +1,882 @@ +import { createHash, randomUUID } from "crypto"; +import { open } 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. + * + * 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. + * + * 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. 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 + * released instead of being held by work nobody reads. + */ + +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. + * + * 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; + 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; + /** + * 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 + * 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 session vanished: continue with older ones. */ + 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; + /** Aborted by the HTTP layer when the client disconnects. */ + signal?: AbortSignal; + /** 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"; + } +} + +/** 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") + .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.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, + }; +} + +/** + * Listing snapshots, one per pagination run. + * + * 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. + * + * 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. + * + * 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. + * + * 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. */ +const SEARCH_LISTING_SNAPSHOTS = 4; + +interface SearchListingSnapshot { + id: string; + /** Sessions root the walk saw; a snapshot never crosses roots. */ + root: string; + /** Last use, for the sliding TTL and the LRU order. */ + at: number; + files: readonly SessionSearchFile[]; +} + +interface SearchListingCacheHost { + __ompSessionSearchListings?: Map; + /** + * Monotonic id generator. Deliberately NOT reset by + * {@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(); +} + +function getListingSnapshots(): Map { + if (!listingCacheHost.__ompSessionSearchListings) { + listingCacheHost.__ompSessionSearchListings = new Map(); + } + return listingCacheHost.__ompSessionSearchListings; +} + +/** + * 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 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. */ +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(), + })); +} + +/** 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); + } +} + +/** + * 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. + */ +export function installSessionSearchListing( + now: () => number, + files: SessionSearchFile[], +): { id: string; files: readonly SessionSearchFile[] } { + const map = getListingSnapshots(); + const next = (listingCacheHost.__ompSessionSearchListingIds ?? 0) + 1; + listingCacheHost.__ompSessionSearchListingIds = 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()); + return { id, files: sorted }; +} + +/** + * 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 startSessionSearchListing( + now: () => number, + walk: () => Promise = loadSessionSearchFiles, +): 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; + } + // 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 { + /** 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); + 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"); + + // 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 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; + 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); + + let startIndex = 0; + let startOffset: number | undefined; + let remainingResults = limit; + + if (cursor) { + const index = files.findIndex((file) => file.id === cursor.sessionId); + if (index >= 0) { + startIndex = index; + startOffset = cursor.offset; + } else { + // 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.id > cursor.sessionId), + ); + 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, + l: listingId, + 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); + + 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, + ...(signal ? { signal } : {}), + }); + 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; + signal?: AbortSignal; +} + +/** 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) { + // 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, + 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 (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 { + 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,