From 77f80d4278e06bee8d9bcb8538d0b1bc1b03e57b Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:19:21 +0100 Subject: [PATCH 1/3] feat(sessions): navigation-only reads, context ETag and a prompt-less state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `GET /api/sessions/{id}?meta=1` answers the navigation shape — tree, leaf and info with model, thinking level and last message time — without the second transcript copy; the transcript stays on `/context`. The host result validator accepts that shape, so a daemon answers it too. `GET /api/sessions/{id}/context` sends a strong ETag over the exact bytes it serialized and answers `304` on a matching `If-None-Match`, so a client that already holds a transcript does not download it again. `GET /api/agent/{id}?systemPrompt=0` drops the ~13 KB system prompt from the 15 s state poll; any other value keeps the full shape. --- app/api/agent/[id]/route.ts | 13 +- app/api/sessions/[id]/context/route.ts | 31 ++- app/api/sessions/[id]/route.ts | 34 ++- lib/api-utils.ts | 18 ++ lib/hosts/hub.ts | 8 +- lib/hosts/session-ops.ts | 64 +++++- lib/omp/session-files.ts | 2 +- lib/pi-types.ts | 3 +- lib/rpc-manager.ts | 7 +- lib/session-reader.ts | 41 ++++ lib/session-routes.test.mjs | 296 +++++++++++++++++++++++++ 11 files changed, 484 insertions(+), 33 deletions(-) diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index c7ee93199..0b80b43a1 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -37,10 +37,13 @@ export async function POST( // GET /api/agent/[id] - Get current agent state export async function GET( - _req: Request, + req: Request, { params }: { params: Promise<{ id: string }> } ) { const { id } = await params; + // Default stays the full shape; `?systemPrompt=0` drops the ~13 KB prompt + // from the 15 s state poll. Any other value (including "1") keeps it. + const includeSystemPrompt = new URL(req.url).searchParams.get("systemPrompt") !== "0"; try { const session = getRpcSession(id); @@ -48,7 +51,13 @@ export async function GET( return Response.json({ running: false }); } try { - const state = await session.send({ type: "get_state" }); + // Through the wrapper's command path, not a dedicated method: that is + // the contract every wrapper fake implements, and `dispatchCommand` + // already honors `systemPrompt: false`. + const state = await session.send({ + type: "get_state", + ...(includeSystemPrompt ? {} : { systemPrompt: false }), + }); return Response.json({ running: true, state }); } catch (error) { if (error instanceof WebRpcError && error.code === "session_unresponsive") { diff --git a/app/api/sessions/[id]/context/route.ts b/app/api/sessions/[id]/context/route.ts index 713155f91..e263cd8ce 100644 --- a/app/api/sessions/[id]/context/route.ts +++ b/app/api/sessions/[id]/context/route.ts @@ -1,8 +1,27 @@ import { buildSessionContext } from "@/lib/session-reader"; -import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; +import { apiErrorResponse, ifNoneMatchSatisfied, opErrorResponse, resolveSessionHostOr404, strongEtag } from "@/lib/api-utils"; import { getRpcSession } from "@/lib/rpc-manager"; import { MAX_SYNC_MESSAGES, parseHistoryCursor, selectSessionHistory, type SessionHistoryCursor, type SessionHistoryPage, type SessionSyncResponse } from "@/lib/session-sync"; +/** + * Serialize once, key the validator on those exact bytes: the ETag cannot + * disagree with the body, and it covers everything that shapes it (branch, + * options, live stream snapshot) without this route needing the file's + * identity — which a remote host would not expose to this process. + */ +function jsonBodyResponse(req: Request, body: unknown, cacheControl: "no-store" | null = null): Response { + const text = JSON.stringify(body); + const etag = strongEtag(text); + const headers: Record = { ETag: etag }; + if (cacheControl) headers["Cache-Control"] = cacheControl; + if (ifNoneMatchSatisfied(req.headers.get("if-none-match"), etag)) { + return new Response(null, { status: 304, headers }); + } + return new Response(text, { + headers: { "Content-Type": "application/json", "Content-Length": String(Buffer.byteLength(text)), ...headers }, + }); +} + export async function GET( req: Request, { params }: { params: Promise<{ id: string }> } @@ -63,7 +82,7 @@ export async function GET( const session = notFound && (boundary === "1" || (sync === "1" && !cursor?.lastEntryId && leafId === undefined)) ? getRpcSession(id) : undefined; if (session?.isAlive() && !(await session.host.sessionFileExists(session.sessionFile))) { if (boundary === "1") { - return Response.json({ entryIds: [] }, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, { entryIds: [] }, "no-store"); } const response: SessionSyncResponse = { ...selectSessionHistory(buildSessionContext([]), cursor, limit), @@ -71,12 +90,12 @@ export async function GET( leafId: null, live: session.getStreamSnapshot(), }; - return Response.json(response, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, response, "no-store"); } return "response" in result ? result.response : opErrorResponse(result); } if (boundary === "1") { - return Response.json(result.value, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, result.value, "no-store"); } if (sync === "1") { const page = result.value as { history: SessionHistoryPage; leafId: string | null; tipId: string | null }; @@ -87,9 +106,9 @@ export async function GET( ? session.getStreamSnapshot() : null; const response: SessionSyncResponse = { ...page.history, sessionId: id, leafId: page.leafId, live }; - return Response.json(response, { headers: { "Cache-Control": "no-store" } }); + return jsonBodyResponse(req, response, "no-store"); } - return Response.json(result.value); + return jsonBodyResponse(req, result.value); } catch (error) { return apiErrorResponse(error); } diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index d3099a237..e964031da 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -6,6 +6,7 @@ import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-fo import { clearExitedRpcSession, getLiveRpcSessionIds, getRpcSession, WebRpcError } from "@/lib/rpc-manager"; import { forgetSessionReplacementMappings } from "@/lib/message-outbox"; import { removeSessionWatches } from "@/lib/github/watch-store"; +import { RpcCommandError } from "@/lib/omp/rpc-process"; /** Stable, client-safe error body for catch-all handlers: details go to the * server log only, never to the browser. */ @@ -13,6 +14,11 @@ function sessionsErrorResponse(error: unknown): Response { if (error instanceof WebRpcError && error.code === "session_busy") { return Response.json({ error: error.message, code: error.code }, { status: 409 }); } + // omp is busy, not gone: the session keeps running, so a client retries + // instead of treating the rename as applied (docs/android/protocol.md §3.5). + if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { + return Response.json({ error: error.message, code: "session_slow" }, { status: 503 }); + } if (error instanceof RequestBodyTooLargeError) { return Response.json({ error: "Request body is too large", code: "request_too_large" }, { status: 413 }); } @@ -35,10 +41,12 @@ export async function GET( if ("response" in resolved) return resolved.response; const searchParams = new URL(req.url).searchParams; + const meta = searchParams.get("meta") === "1"; const includeState = searchParams.has("includeState"); const read = await resolved.host.sessionOps.readSession(id, { deferThinking: searchParams.has("deferThinking"), deferMedia: searchParams.has("deferMedia"), + meta, }); if (!read.ok) return opErrorResponse(read); @@ -46,23 +54,32 @@ export async function GET( // GET /api/agent/[id]) so the client's post-turn refresh is one request // instead of two. On a get_state failure the field is omitted entirely — // callers treat a missing `agent` as "fetch it separately". - let agent: { running: boolean; state?: unknown } | undefined; + let agent: { running: boolean; alive: boolean; state?: unknown } | undefined; if (includeState) { const rpc = getRpcSession(id); if (rpc?.isAlive()) { try { - agent = { running: true, state: await rpc.send({ type: "get_state" }) }; + // Sample `running` after the state read, like the state route: the + // reply (and frames it flushed) is what makes the answer authoritative. + const state = await rpc.send({ type: "get_state" }); + agent = { running: rpc.isRunning(), alive: true, state }; } catch { // Leave agent unset; the session payload is still valid without it. } } else { - agent = { running: false }; + agent = { running: false, alive: false }; } } + // ?meta=1 is the navigation shape: the tree and leaf the native client + // reads from this route, without a second transcript copy. `context` is + // omitted entirely (not null) so clients keyed on its presence keep their + // historical shape; the transcript comes from /api/sessions/[id]/context. + const { context, ...navigation } = read.value; return Response.json({ sessionId: id, - ...read.value, + ...navigation, + ...(context ? { context } : {}), ...(agent ? { agent } : {}), }); } catch (error) { @@ -92,8 +109,13 @@ export async function PATCH( await rpc.send({ type: "set_session_name", name: name.trim() }); renamed = true; } catch (error) { - if (error instanceof WebRpcError && error.code === "session_busy") throw error; - // Fall back to the on-disk title slot below. + // The file fallback is only for "nothing was applied": omp rejected the + // command outright, or the child died before answering. A timeout means + // omp is busy and still writes the file itself, so a slot write here + // would race its next flush — answer 503 and write nothing + // (docs/android/protocol.md §3.5). + if (error instanceof WebRpcError) throw error; + if (!(error instanceof RpcCommandError) && rpc.isAlive?.()) throw error; } } if (!renamed) { diff --git a/lib/api-utils.ts b/lib/api-utils.ts index e68b322c6..748ac387d 100644 --- a/lib/api-utils.ts +++ b/lib/api-utils.ts @@ -1,3 +1,4 @@ +import { createHash } from "crypto"; import { pooledWorkspaceForSession } from "./hosts/pool-starts"; import { isValidSessionId } from "./session-file-references-core"; import { isLinkUp, type Host } from "./hosts/host"; @@ -87,6 +88,23 @@ export function opErrorResponse(result: Extract, { ok: false } return Response.json({ error: result.error, code: result.code }, { status: result.status }); } +/** Strong, quoted ETag from the inputs that identify one response body. */ +export function strongEtag(identity: string): string { + return `"${createHash("sha256").update(identity).digest("hex").slice(0, 32)}"`; +} + +/** Whether an `If-None-Match` header covers `etag` (`*` always does). Uses the + * weak comparison RFC 9110 §13.1.2 requires, so a proxy that weakens our + * strong tag (`W/"…"`) still gets its 304. */ +export function ifNoneMatchSatisfied(header: string | null, etag: string): boolean { + if (!header) return false; + const expected = etag.replace(/^W\//, ""); + return header.split(",").some((candidate) => { + const value = candidate.trim(); + return value === "*" || value.replace(/^W\//, "") === expected; + }); +} + /** Uniform JSON error body used by most API routes. A host link failure keeps * its status (503 offline, 504 timeout) and code; a session whose host is * offline answers 503 `{hostOffline: true}`, plus its `delivery` for an agent diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 279017aaa..274db4c07 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -1115,8 +1115,12 @@ function validResult(op: keyof SessionOps, result: unknown, args: unknown[]): bo && typeof value.baseCommit === "string" && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(value.baseCommit); case "exportSession": return isRecord(value) && typeof value.html === "string" && typeof value.fileName === "string"; - case "readSession": - return isRecord(value) && isRecord(value.info) && isRecord(value.context); + case "readSession": { + // `?meta=1` is the navigation shape: no transcript, so `context` is null. + const options = isRecord(args[1]) ? args[1] : {}; + return isRecord(value) && isRecord(value.info) + && (isRecord(value.context) || (options.meta === true && value.context === null)); + } case "readContext": { // The context route reads a different shape per mode. const options = isRecord(args[2]) ? args[2] : {}; diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index faf72495a..66580dc17 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -25,6 +25,7 @@ import { MAX_SESSION_LOAD_BYTES, parseTitleSlotLine, readSessionHeaderSync, + scanSessionInfoCached, setSessionTitle, writeSessionFileAtomicSync, } from "../omp/session-files"; @@ -42,6 +43,7 @@ import { } from "../project-registry"; import { buildSessionContext, + buildSessionContextSummary, getSessionContextBoundary, getSessionEntries, getSessionEntriesForDisplayAsync, @@ -68,6 +70,9 @@ export type OpResult = { ok: true; value: T } | { ok: false; status: number; export interface SessionReadOptions { deferThinking: boolean; deferMedia: boolean; + /** Navigation-only shape (`?meta=1`): `context` is null and `info` carries + * the branch's model/thinking level and the conversation's activity time. */ + meta?: boolean; } export interface ContextReadOptions extends SessionReadOptions { @@ -82,10 +87,15 @@ export interface ContextReadOptions extends SessionReadOptions { /** `GET /api/sessions/[id]` minus the route's `sessionId` and live `agent`. */ export interface SessionReadValue { filePath: string; - info: Omit; + info: Omit & { + /** `?meta=1` only: the branch's model choice and reasoning level. */ + model?: SessionContext["model"]; + thinkingLevel?: string; + }; leafId: string | null; tree: unknown[]; - context: SessionContext; + /** null in the `?meta=1` navigation shape. */ + context: SessionContext | null; } export interface ProjectUpdate { @@ -189,6 +199,27 @@ function branchPreviewForEntry(entry: { id?: string; type?: string; message?: un return { ...(role ? { role } : {}), text }; } +/** First `{type:"text"}` block's text in a message content array ("" when none). */ +function textBlockText(content: readonly unknown[]): string { + for (const block of content) { + if (block && typeof block === "object" && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") { + return block.text; + } + } + return ""; +} + +/** `info.firstMessage`: the first user message's text, with the "(no messages)" fallback. */ +function firstUserMessageText(messages: ReadonlyArray<{ role?: string; content?: unknown }>): string { + const message = messages.find((entry) => entry.role === "user"); + if (!message) return "(no messages)"; + const content = message.content; + const text = typeof content === "string" + ? content + : Array.isArray(content) ? textBlockText(content) : ""; + return text || "(no messages)"; +} + /** * Project the session tree into the shallow navigation tree sent to the client. * Keeps roots, branch points, and leaves while contracting single-child chains @@ -329,7 +360,7 @@ export const sessionOps: SessionOps = { }, listSessionIdsForRestore: async () => listSessionIdsForRestore(), - async readSession(id, { deferThinking, deferMedia: deferToolResultImages }) { + async readSession(id, { deferThinking, deferMedia: deferToolResultImages, meta }) { const filePath = await resolveSessionPath(id); if (!filePath) return sessionNotFound(); try { @@ -341,14 +372,21 @@ export const sessionOps: SessionOps = { const displayEntries = await getSessionEntriesForDisplayAsync(filePath, { skipToolResultImages: deferToolResultImages }); const leafId = getLeafEntryId(displayEntries); const tree = projectTreeForResponse(buildSessionTree(displayEntries)); - const context = buildSessionContext(displayEntries, leafId, { deferThinking, deferToolResultImages }); + // ?meta=1 is the navigation shape: the tree and leaf the native client + // reads from this route, without the second transcript copy. The context + // stays on /api/sessions/[id]/context, which defers media/thinking and + // answers 304. Without the parameter the historical shape is unchanged. + const context = meta ? null : buildSessionContext(displayEntries, leafId, { deferThinking, deferToolResultImages }); + const summary = meta ? buildSessionContextSummary(displayEntries, leafId, { deferThinking, deferToolResultImages }) : null; + // Same scan the session list uses (memoized on size+mtime), so the + // detail's activity time cannot diverge from the sidebar's. + const lastMessageAt = meta ? scanSessionInfoCached(filePath)?.lastMessageAt?.toISOString() : undefined; let modified = header.timestamp ?? new Date().toISOString(); try { modified = statSync(filePath).mtime.toISOString(); } catch { /* use header timestamp */ } const parentSessionId = header.parentSession ? await resolveParentSessionId(header.parentSession) : undefined; - const firstUser = context.messages.find((m) => m.role === "user"); const info = { path: filePath, id: header.id, @@ -356,14 +394,16 @@ export const sessionOps: SessionOps = { name: header.title, created: header.timestamp, modified, - messageCount: context.messages.length, - firstMessage: firstUser - ? (() => { - const c = (firstUser as { content: unknown }).content; - return typeof c === "string" ? c : (Array.isArray(c) ? (c.find((b: { type: string }) => b.type === "text") as { text: string } | undefined)?.text ?? "" : "") || "(no messages)"; - })() - : "(no messages)", + messageCount: context ? context.messages.length : summary!.messageCount, + firstMessage: context ? firstUserMessageText(context.messages) : summary!.firstMessage, parentSessionId, + // The meta shape has no `context`, so the branch's model/thinking + // level and the conversation's activity time ride in `info` instead. + ...(summary ? { + model: summary.model, + thinkingLevel: summary.thinkingLevel, + ...(lastMessageAt ? { lastMessageAt } : {}), + } : {}), }; return ok({ filePath, info, leafId, tree, context }); } catch (error) { diff --git a/lib/omp/session-files.ts b/lib/omp/session-files.ts index 2524beccb..a7e2cce65 100644 --- a/lib/omp/session-files.ts +++ b/lib/omp/session-files.ts @@ -1060,7 +1060,7 @@ export function invalidateAllSessionScanCaches(): void { /** scanSessionInfo memoized on (path, size, mtimeMs). Callers must treat the * returned info as immutable — cache hits share one object. */ -function scanSessionInfoCached(filePath: string): OmpSessionInfo | undefined { +export function scanSessionInfoCached(filePath: string): OmpSessionInfo | undefined { let stat: { size: number; mtime: Date; mtimeMs: number }; try { stat = statSync(filePath); diff --git a/lib/pi-types.ts b/lib/pi-types.ts index 495d116dc..6ffe13679 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -142,7 +142,8 @@ export interface WebSessionState { queuedMessages: QueuedMessages; supportsClientMessageIds?: boolean; contextUsage: ContextUsage | null; - systemPrompt: string; + /** Absent when the client asked for the prompt-less shape (`?systemPrompt=0`). */ + systemPrompt?: string; thinkingLevel: string; fastModeEnabled: boolean; fastModeActive?: boolean; diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index fcff6ac53..78210f49d 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -2141,7 +2141,7 @@ export class AgentSessionWrapper { notifyRunningChange(); } } - private buildWebState(state: RpcSessionState): WebSessionState { + private buildWebState(state: RpcSessionState, includeSystemPrompt = true): WebSessionState { const wasRunning = this.isRunning(); // Reconcile process-side flags with authoritative child state. @@ -2202,7 +2202,8 @@ export class AgentSessionWrapper { ...(state.supportsClientMessageIds === true ? { supportsClientMessageIds: true } : {}), tokensPerSecond: state.tokensPerSecond ?? null, contextUsage: state.contextUsage ?? null, - systemPrompt: state.systemPrompt?.join("\n\n") ?? "", + // `?systemPrompt=0` drops the ~13 KB prompt from the 15 s state poll. + ...(includeSystemPrompt ? { systemPrompt: state.systemPrompt?.join("\n\n") ?? "" } : {}), thinkingLevel: state.thinkingLevel ?? "off", // The child's per-family tier map is authoritative: it changes when the // model switches families (isFastModeEnabled is family-scoped) or when @@ -2745,7 +2746,7 @@ export class AgentSessionWrapper { case "get_state": { try { const state = await this.proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS); - return this.buildWebState(state); + return this.buildWebState(state, command.systemPrompt !== false); } catch (error) { if (error instanceof RpcCommandTimeoutError) { // This is only an observer poll. A busy event loop or delayed RPC diff --git a/lib/session-reader.ts b/lib/session-reader.ts index e2bbe5c16..6e784329d 100644 --- a/lib/session-reader.ts +++ b/lib/session-reader.ts @@ -866,6 +866,47 @@ export function buildSessionContext( }; } +/** First `{type:"text"}` block's text in a message content array ("" when none). */ +function textBlockText(content: readonly unknown[]): string { + for (const block of content) { + if (block && typeof block === "object" && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") { + return block.text; + } + } + return ""; +} + +/** + * The two `info` fields derived from the active context — `messageCount` and + * `firstMessage` — without converting a whole transcript into UI messages, + * plus the branch's `model`/`thinkingLevel` (the meta shape carries them in + * `info` because it has no `context`). `GET /api/sessions/[id]?meta=1` needs + * them for a navigation-only response, where building (and then dropping) a + * multi-megabyte context would defeat the point of the meta shape. + */ +export function buildSessionContextSummary( + entries: SessionEntry[], + leafId?: string | null, + options: { deferThinking?: boolean; deferToolResultImages?: boolean; includePreCompaction?: boolean } = {}, +): { messageCount: number; firstMessage: string; model: SessionContext["model"]; thinkingLevel: string } { + const { selected, model, thinkingLevel } = selectSessionContext(entries, leafId, options); + let firstMessage = "(no messages)"; + for (const entry of selected) { + const userMessage = entry.type === "branch_summary" + ? Boolean(entry.summary) + : entry.type === "message" && isRecord(entry.message) && entry.message.role === "user"; + if (!userMessage) continue; + const message = entryToUiMessage(entry, options); + const content = message && "content" in message ? message.content : undefined; + const text = typeof content === "string" + ? content + : Array.isArray(content) ? textBlockText(content) : ""; + firstMessage = text || "(no messages)"; + break; + } + return { messageCount: selected.length, firstMessage, model, thinkingLevel }; +} + /** Select ordering and branch metadata without converting message bodies. */ function selectSessionContext( entries: SessionEntry[], diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 80e75c16d..58f72deb9 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -19,6 +19,7 @@ const sessionsListRoute = await import("../app/api/sessions/route.ts"); const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await import("./session-reader.ts"); const { allowFileRoot, normalizeSlashes } = await import("./file-access.ts"); const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); +const { RpcCommandError } = await import("./omp/rpc-process.ts"); const { closeHostLink, getHost, linkTimings } = await import("./hosts/hub.ts"); const { HostOpError } = await import("./hosts/link-protocol.ts"); const { revokeHost } = await import("./hosts/registry.ts"); @@ -201,6 +202,210 @@ test("session and context routes map a missing session to 404, not 413", async ( const ctxRes = await contextRoute.GET(ctxReq, { params: Promise.resolve({ id: "no-such-session" }) }); assert.equal(ctxRes.status, 404); }); + +test("?meta=1 answers the navigation shape and leaves the transcript to /context", async () => { + await withAgentDir(async (dir) => { + writeSessionFile(dir, "2026-01-01_meta.jsonl", { + id: "0a000000-0000-4000-8000-000000000030", + cwd: join(tmpdir(), "omp-web-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello meta" } }, + { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "world" } }, + { type: "model_change", id: "m1", parentId: "a1", timestamp: "2026-01-01T00:00:02.000Z", model: "test/model", role: "default" }, + { type: "thinking_level_change", id: "t1", parentId: "m1", timestamp: "2026-01-01T00:00:03.000Z", thinkingLevel: "high" }, + ]); + + const fullRes = await sessionRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000030"), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000030" }) }, + ); + const full = await fullRes.json(); + assert.equal(fullRes.status, 200); + assert.ok(Array.isArray(full.context.messages)); + + const metaRes = await sessionRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000030?meta=1"), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000030" }) }, + ); + const meta = await metaRes.json(); + assert.equal(metaRes.status, 200, JSON.stringify(meta)); + assert.deepEqual(Object.keys(meta).sort(), ["filePath", "info", "leafId", "sessionId", "tree"]); + assert.equal(Object.hasOwn(meta, "context"), false, "the transcript must not ride along"); + assert.deepEqual(meta.tree, full.tree, "the navigation tree is identical"); + assert.equal(meta.leafId, full.leafId); + const { model, thinkingLevel, lastMessageAt, ...metaBase } = meta.info; + assert.deepEqual(metaBase, full.info, "info derives the same count and first message"); + assert.equal(metaBase.messageCount, 2); + assert.equal(metaBase.firstMessage, "hello meta"); + // The meta shape has no context, so the fields its consumers need ride in info. + assert.deepEqual(model, { provider: "test", modelId: "model" }); + assert.deepEqual(model, full.context.model, "same value the full response exposes"); + assert.equal(thinkingLevel, "high"); + assert.equal(thinkingLevel, full.context.thinkingLevel); + assert.equal(lastMessageAt, "2026-01-01T00:00:01.000Z", "same scan the sidebar uses"); + + // Any other value (including meta=0) keeps the historical shape. + const untouched = await sessionRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000030?meta=0"), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000030" }) }, + ); + assert.ok(Array.isArray((await untouched.json()).context.messages)); + }); +}); + +test("?includeState=1 embeds the live agent shape with alive", async (t) => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000032"; + writeSessionFile(dir, "2026-01-01_state.jsonl", { + id, + cwd: join(tmpdir(), "omp-web-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + ]); + const previousSessions = globalThis.__ompSessions; + const wrapper = { + isAlive: () => true, + isRunning: () => true, + send: async (command) => { + assert.equal(command.type, "get_state"); + return { sessionId: id, isStreaming: true }; + }, + host: getHost("local"), + }; + globalThis.__ompSessions = new Map([[id, wrapper]]); + t.after(() => { globalThis.__ompSessions = previousSessions; }); + + const live = await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?includeState=1`), + { params: Promise.resolve({ id }) }, + ); + assert.equal(live.status, 200); + assert.deepEqual((await live.json()).agent, { + running: true, + alive: true, + state: { sessionId: id, isStreaming: true }, + }); + }); +}); + +test("?includeState=1 without a live wrapper answers running:false, alive:false", async (t) => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000033"; + writeSessionFile(dir, "2026-01-01_no-wrapper.jsonl", { + id, + cwd: join(tmpdir(), "omp-web-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + ]); + const previousSessions = globalThis.__ompSessions; + globalThis.__ompSessions = new Map(); + t.after(() => { globalThis.__ompSessions = previousSessions; }); + + const res = await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?includeState=1`), + { params: Promise.resolve({ id }) }, + ); + assert.equal(res.status, 200); + const agent = (await res.json()).agent; + assert.equal(agent.running, false); + assert.equal(agent.alive, false); + assert.equal(Object.hasOwn(agent, "state"), false, "no child, no state"); + }); +}); + +test("context sends a strong ETag, answers 304, and re-keys it when the body changes", async () => { + await withAgentDir(async (dir) => { + const filePath = writeSessionFile(dir, "2026-01-01_etag.jsonl", { + id: "0a000000-0000-4000-8000-000000000031", + cwd: join(tmpdir(), "omp-web-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "world" } }, + ]); + + const first = await getContext("0a000000-0000-4000-8000-000000000031"); + assert.equal(first.status, 200); + const etag = first.headers.get("etag"); + assert.match(etag, /^"[0-9a-f]{32}"$/, "a quoted strong ETag"); + const firstText = await first.text(); + assert.equal(first.headers.get("content-length"), String(Buffer.byteLength(firstText)), "content-length describes these exact bytes"); + + const cached = await getContext("0a000000-0000-4000-8000-000000000031"); + const cachedEtag = cached.headers.get("etag"); + assert.equal(cachedEtag, etag, "an unchanged body reuses the validator"); + await cached.json(); + + const notModified = await contextRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000031/context", { headers: { "If-None-Match": cachedEtag } }), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000031" }) }, + ); + assert.equal(notModified.status, 304); + assert.equal(await notModified.text(), ""); + assert.equal(notModified.headers.get("etag"), cachedEtag, "304 repeats the validator"); + + // If-None-Match uses the weak comparison function: a proxy that weakened + // our strong tag must still get its 304. + const weak = await contextRoute.GET( + new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000031/context", { headers: { "If-None-Match": `W/${cachedEtag}` } }), + { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000031" }) }, + ); + assert.equal(weak.status, 304); + assert.equal(await weak.text(), ""); + + // A different body input is a different validator, never a 304. + const branch = await getContext("0a000000-0000-4000-8000-000000000031", "leafId=u1"); + assert.equal(branch.status, 200); + assert.notEqual(branch.headers.get("etag"), cachedEtag); + await branch.json(); + + // Same options, file content changed: the body hash changes with the body. + writeSessionFile(dir, "2026-01-01_etag.jsonl", { + id: "0a000000-0000-4000-8000-000000000031", + cwd: join(tmpdir(), "omp-web-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "world" } }, + { type: "message", id: "a2", parentId: "a1", timestamp: "2026-01-01T00:00:02.000Z", message: { role: "assistant", content: "again" } }, + ]); + assert.ok(existsSync(filePath)); + const changed = await getContext("0a000000-0000-4000-8000-000000000031"); + assert.equal(changed.status, 200); + assert.notEqual(changed.headers.get("etag"), cachedEtag); + assert.deepEqual((await changed.json()).context.entryIds, ["u1", "a1", "a2"]); + }); +}); + +test("paged history answers the same strong ETag and 304s on a repeated read", async () => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-00000000000d"; + writeSessionFile(dir, "2026-01-01_sync-etag.jsonl", { id, cwd: dir, timestamp: "2026-01-01T00:00:00.000Z" }, [ + { type: "message", id: "one", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "one" } }, + { type: "message", id: "two", parentId: "one", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "two" } }, + ]); + const response = await getContext(id, "sync=1&limit=1&deferThinking"); + assert.equal(response.status, 200); + const etag = response.headers.get("etag"); + assert.match(etag, /^"[0-9a-f]{32}"$/); + await response.json(); + + const repeated = await getContext(id, "sync=1&limit=1&deferThinking"); + assert.equal(repeated.headers.get("etag"), etag, "an unchanged page reuses the validator"); + await repeated.json(); + + const notModified = await contextRoute.GET( + new Request(`http://localhost/api/sessions/${id}/context?sync=1&limit=1&deferThinking`, { headers: { "If-None-Match": etag } }), + { params: Promise.resolve({ id }) }, + ); + assert.equal(notModified.status, 304); + assert.equal(await notModified.text(), ""); + }); +}); + // ============================================================================ // Route-level integration: DELETE re-parenting + import invalidation // (TODO §3 leftover — fork itself is RPC-gated behind the omp binary and is @@ -1645,6 +1850,78 @@ test("sidebar rename cannot fall back to disk while Edit owns the session", asyn }); }); +test("a rename that times out on a live child answers 503 and writes nothing", async () => { + // docs/android/protocol.md §3.5: a busy omp keeps the file, so the route must + // not write the title slot beside it — the child's next flush would clobber + // the write and the client would show success for a rename that never stuck. + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000012"; + const filePath = writeSessionFile(dir, "0a000000-0000-4000-8000-000000000012.jsonl", { id, cwd: dir }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "question" } }, + { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [] } }, + ]); + cacheSessionPath(id, filePath); + const originalFile = readFileSync(filePath); + const commands = []; + const rpc = { + isAlive: () => true, + host: getHost("local"), + isEditingHistory: () => false, + async send(command) { + commands.push(command); + // Exactly what the wrapper raises after GET_STATE_TIMEOUT_MS. + throw new WebRpcError("omp is busy and did not answer in time; the session keeps running.", "session_slow"); + }, + }; + const previousSessions = globalThis.__ompSessions; + globalThis.__ompSessions = new Map([[id, rpc]]); + try { + const response = await sessionRoute.PATCH(new Request(`http://localhost/api/sessions/${id}`, { + method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Renamed" }), + }), { params: Promise.resolve({ id }) }); + assert.equal(response.status, 503); + assert.equal((await response.json()).code, "session_slow"); + assert.deepEqual(commands.map((command) => command.type), ["set_session_name"]); + assert.deepEqual(readFileSync(filePath), originalFile, "a slow rename must not rewrite the session title slot"); + } finally { + globalThis.__ompSessions = previousSessions; + } + }); +}); + +test("a rename omp rejects outright still falls back to the file", async () => { + // The other half of the contract: `RpcCommandError` means nothing was + // applied, so the on-disk title slot is the correct place to write. + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000013"; + const filePath = writeSessionFile(dir, "0a000000-0000-4000-8000-000000000013.jsonl", { id, cwd: dir }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "question" } }, + { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [] } }, + ]); + cacheSessionPath(id, filePath); + const rpc = { + isAlive: () => true, + host: getHost("local"), + isEditingHistory: () => false, + async send() { + throw new RpcCommandError("set_session_name", "Unknown command", "unsupported"); + }, + }; + const previousSessions = globalThis.__ompSessions; + globalThis.__ompSessions = new Map([[id, rpc]]); + try { + const response = await sessionRoute.PATCH(new Request(`http://localhost/api/sessions/${id}`, { + method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Renamed" }), + }), { params: Promise.resolve({ id }) }); + assert.equal(response.status, 200); + assert.deepEqual(await response.json(), { ok: true }); + assert.match(readFileSync(filePath, "utf8"), /"title":"Renamed"/); + } finally { + globalThis.__ompSessions = previousSessions; + } + }); +}); + test("automatic title fallback cannot write after Edit takes over", async () => { await withAgentDir(async (dir) => { const id = "0a000000-0000-4000-8000-000000000011"; @@ -1817,3 +2094,22 @@ test("GET /api/sessions?id= returns only the requested session for na assert.deepEqual(dataNone.sessions, []); }); }); + +test("the state poll omits the system prompt only when asked", async (t) => { + const { AgentSessionWrapper } = await import("./rpc-manager.ts"); + const sent = []; + const wrapper = Object.create(AgentSessionWrapper.prototype); + Object.assign(wrapper, { + _alive: true, proc: { isAlive: true }, promptRunning: false, streaming: false, compacting: false, + bashRunning: false, pendingUiRequests: new Map(), pendingHostTools: new Map(), pendingHostUris: new Map(), + send: async (command) => { sent.push(command); return { sessionId: "s", sessionFile: "/s.jsonl" }; }, + }); + const route = await import("../app/api/agent/[id]/route.ts"); + const before = globalThis.__ompSessions; + globalThis.__ompSessions = new Map([["sp", wrapper]]); + t.after(() => { globalThis.__ompSessions = before; }); + const full = await route.GET(new Request("http://localhost/api/agent/sp"), { params: Promise.resolve({ id: "sp" }) }); + assert.equal(full.status, 200); + await route.GET(new Request("http://localhost/api/agent/sp?systemPrompt=0"), { params: Promise.resolve({ id: "sp" }) }); + assert.deepEqual(sent.map((command) => command.systemPrompt), [undefined, false], "the flag rides the get_state frame"); +}); From be2ee079a74054e49ca870870ec722ae5af78482 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:20:09 +0100 Subject: [PATCH 2/3] fix(sessions): keep the includeState contract and map real rename failures `?includeState` keeps its historical meaning: any live wrapper answers `running: true`, idle included, as `/api/agent` and `/state` do. The idle/running split is opt-in via `?includeState=alive`, which adds `alive` and samples `running` after the state read. A child that exits between its reply and the handler's resume is reported as not live instead of stale-live. The rename route now maps the error classes the wrapper actually raises instead of a synthetic code: `session_slow`, `session_state_timeout`, `session_restarting` and `session_unresponsive` answer 503 with their own retriable code, `host_offline` answers the 503 `{hostOffline, delivery}` body, and a raw `RpcCommandTimeoutError` answers 503 `session_slow`. None of them falls back to the on-disk title slot: the child still owns the file, so the completion stays unknown and the client retries instead of being told the rename stuck. Only an outright `RpcCommandError` (or a child that exited before answering) writes the slot. `?meta=1` now normalizes a daemon that predates the option: that daemon ignores `meta` and answers the full transcript, so the route derives the navigation shape from it rather than forwarding the second copy. The host result validator accepts that legacy answer and requires the navigation fields (tree, leafId, model, thinkingLevel) on a null-context result. Tests cover each contract at the route boundary; mutation probes on the normalization, the historical includeState shape, the retriable mapping and the post-timeout fallback each fail the suite. --- app/api/sessions/[id]/route.ts | 104 +++++++++++++---- lib/hosts/hub.test.mjs | 12 ++ lib/hosts/hub.ts | 13 ++- lib/session-routes.test.mjs | 208 ++++++++++++++++++++++++++++++--- 4 files changed, 296 insertions(+), 41 deletions(-) diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index e964031da..41a9bff90 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -1,12 +1,24 @@ import { apiErrorResponse, hostOfflineResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { HostOpError } from "@/lib/hosts/link-protocol"; import { invalidateHostSessionList } from "@/lib/hosts/session-index"; +import type { SessionReadValue } from "@/lib/hosts/session-ops"; import { invalidateSessionCaches } from "@/lib/session-reader"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { clearExitedRpcSession, getLiveRpcSessionIds, getRpcSession, WebRpcError } from "@/lib/rpc-manager"; import { forgetSessionReplacementMappings } from "@/lib/message-outbox"; import { removeSessionWatches } from "@/lib/github/watch-store"; -import { RpcCommandError } from "@/lib/omp/rpc-process"; +import { RpcCommandError, RpcCommandTimeoutError } from "@/lib/omp/rpc-process"; + +/** Session-level failures a client retries instead of treating the request as + * applied: omp is busy, restarting or was reset, and the session keeps going. + * `session_slow` is the wrapper's answer once a command exceeds its timeout, + * `session_state_timeout` the status poll's. */ +const RETRIABLE_SESSION_CODES: Record = { + session_slow: true, + session_state_timeout: true, + session_restarting: true, + session_unresponsive: true, +}; /** Stable, client-safe error body for catch-all handlers: details go to the * server log only, never to the browser. */ @@ -14,10 +26,19 @@ function sessionsErrorResponse(error: unknown): Response { if (error instanceof WebRpcError && error.code === "session_busy") { return Response.json({ error: error.message, code: error.code }, { status: 409 }); } - // omp is busy, not gone: the session keeps running, so a client retries - // instead of treating the rename as applied (docs/android/protocol.md §3.5). - if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { - return Response.json({ error: error.message, code: "session_slow" }, { status: 503 }); + // omp is busy, restarting or was reset — not gone: the session keeps running, + // so a client retries instead of treating the rename as applied. + if (error instanceof WebRpcError && RETRIABLE_SESSION_CODES[error.code]) { + return Response.json({ error: error.message, code: error.code }, { status: 503 }); + } + // A command timeout leaves the completion unknown. Nothing was written here + // and the child still owns the file, so the client retries and re-reads the + // title instead of assuming the rename stuck. + if (error instanceof RpcCommandTimeoutError) { + return Response.json( + { error: "The session did not confirm the change in time. It keeps running — retry shortly.", code: "session_slow" }, + { status: 503 }, + ); } if (error instanceof RequestBodyTooLargeError) { return Response.json({ error: "Request body is too large", code: "request_too_large" }, { status: 413 }); @@ -25,12 +46,31 @@ function sessionsErrorResponse(error: unknown): Response { if (error instanceof SyntaxError) { return Response.json({ error: "Invalid JSON request body", code: "invalid_json" }, { status: 400 }); } - // A host link failure keeps its status: 503 offline, 504 timeout. - if (error instanceof HostOpError) return apiErrorResponse(error); + // A host link failure keeps its status: 503 offline, 504 timeout. A live + // wrapper whose link dropped answers 503 `{hostOffline: true}` plus its + // `delivery` ("refused": nothing left this server). + if (error instanceof HostOpError || (error instanceof WebRpcError && error.code === "host_offline")) return apiErrorResponse(error); console.error("[api/sessions]", error); return Response.json({ error: "Session request failed", code: "session_request_failed" }, { status: 500 }); } +/** `?meta=1` against a daemon that predates the option: it ignores `meta` and + * answers the full transcript. Derive the navigation shape from it — the same + * context supplies the branch metadata — so the client never receives the + * second copy. `lastMessageAt` stays absent: that daemon never scanned it. */ +function navigationShape(value: SessionReadValue): SessionReadValue { + if (!value.context) return value; + return { + ...value, + info: { + ...value.info, + model: value.context.model, + thinkingLevel: value.context.thinkingLevel, + }, + context: null, + }; +} + export async function GET( req: Request, { params }: { params: Promise<{ id: string }> } @@ -43,31 +83,48 @@ export async function GET( const searchParams = new URL(req.url).searchParams; const meta = searchParams.get("meta") === "1"; const includeState = searchParams.has("includeState"); + // `?includeState=alive` opts into the split liveness shape; every other + // value (including bare `?includeState`) keeps the historical meaning. + const stateAlive = searchParams.get("includeState") === "alive"; const read = await resolved.host.sessionOps.readSession(id, { deferThinking: searchParams.has("deferThinking"), deferMedia: searchParams.has("deferMedia"), meta, }); if (!read.ok) return opErrorResponse(read); + // A daemon that predates `meta` ignores the option and answers the full + // transcript; derive the navigation shape here so the client never gets it. + const value = meta ? navigationShape(read.value) : read.value; // ?includeState=1 inlines the wrapper's live agent state (same shape as // GET /api/agent/[id]) so the client's post-turn refresh is one request // instead of two. On a get_state failure the field is omitted entirely — // callers treat a missing `agent` as "fetch it separately". - let agent: { running: boolean; alive: boolean; state?: unknown } | undefined; + // + // The historical shape says `running: true` for any live wrapper, idle + // included (that is what /api/agent and /state answer). The idle/running + // split is opt-in (`?includeState=alive`), so an existing caller keeps its + // meaning: `running` there is the child's liveness, not a turn in flight. + let agent: { running: boolean; alive?: boolean; state?: unknown } | undefined; if (includeState) { const rpc = getRpcSession(id); if (rpc?.isAlive()) { try { - // Sample `running` after the state read, like the state route: the - // reply (and frames it flushed) is what makes the answer authoritative. const state = await rpc.send({ type: "get_state" }); - agent = { running: rpc.isRunning(), alive: true, state }; + // The child can exit between its reply and this line: its state is + // stale then, so answer the not-live shape instead of reporting it. + if (rpc.isAlive()) { + agent = stateAlive + ? { running: rpc.isRunning(), alive: true, state } + : { running: true, state }; + } else { + agent = stateAlive ? { running: false, alive: false } : { running: false }; + } } catch { // Leave agent unset; the session payload is still valid without it. } } else { - agent = { running: false, alive: false }; + agent = stateAlive ? { running: false, alive: false } : { running: false }; } } @@ -75,7 +132,7 @@ export async function GET( // reads from this route, without a second transcript copy. `context` is // omitted entirely (not null) so clients keyed on its presence keep their // historical shape; the transcript comes from /api/sessions/[id]/context. - const { context, ...navigation } = read.value; + const { context, ...navigation } = value; return Response.json({ sessionId: id, ...navigation, @@ -109,13 +166,20 @@ export async function PATCH( await rpc.send({ type: "set_session_name", name: name.trim() }); renamed = true; } catch (error) { - // The file fallback is only for "nothing was applied": omp rejected the - // command outright, or the child died before answering. A timeout means - // omp is busy and still writes the file itself, so a slot write here - // would race its next flush — answer 503 and write nothing - // (docs/android/protocol.md §3.5). - if (error instanceof WebRpcError) throw error; - if (!(error instanceof RpcCommandError) && rpc.isAlive?.()) throw error; + // The file fallback is only for "nothing was applied": omp answered + // with a rejection (`RpcCommandError`), or the child died before + // answering, so no live process can flush over our write. Everything + // else keeps its own answer: a timeout leaves the completion unknown + // while the child still owns the file, and a busy/restarting/offline + // session is retried by the client instead of being written behind + // omp's back (its next flush would clobber the slot). + if (error instanceof RpcCommandError) { + // omp rejected the command outright; fall through to the file. + } else if (error instanceof RpcCommandTimeoutError || error instanceof WebRpcError) { + throw error; + } else if (rpc.isAlive?.()) { + throw error; + } } } if (!renamed) { diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index e23577bab..4ee5995d9 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -544,6 +544,12 @@ test("export, session and context results must have the fields the routes read", await assert.rejects(answer(() => ops.exportSession("s1"), null), badResult); await assert.rejects(answer(() => ops.readSession("s1", options), "not a session"), badResult); await assert.rejects(answer(() => ops.readSession("s1", options), { info: {}, context: null }), badResult); + // `?meta=1`: a null context must carry the navigation fields the route reads. + const metaOptions = { ...options, meta: true }; + await assert.rejects(answer(() => ops.readSession("s1", metaOptions), { info: {}, context: null }), badResult); + await assert.rejects(answer(() => ops.readSession("s1", metaOptions), { info: { model: null, thinkingLevel: "off" }, leafId: null, tree: "t", context: null }), badResult); + await assert.rejects(answer(() => ops.readSession("s1", metaOptions), { info: { model: null }, leafId: null, tree: [], context: null }), badResult); + await assert.rejects(answer(() => ops.readSession("s1", metaOptions), { info: { model: null, thinkingLevel: "off" }, leafId: 3, tree: [], context: null }), badResult); await assert.rejects(answer(() => ops.readContext("s1", undefined, contextOptions()), { context: 3 }), badResult); await assert.rejects(answer(() => ops.readContext("s1", undefined, contextOptions({ boundary: true })), { entryIds: "e1" }), badResult); await assert.rejects(answer(() => ops.readContext("s1", undefined, contextOptions({ sync: { cursor: null, limit: 10 } })), { leafId: null, tipId: null }), badResult); @@ -552,6 +558,12 @@ test("export, session and context results must have the fields the routes read", assert.deepEqual((await answer(() => ops.exportSession("s1"), exported)).value, exported); const session = { filePath: "/f", info: { id: "s1" }, leafId: null, tree: [], context: { messages: [] } }; assert.deepEqual((await answer(() => ops.readSession("s1", options), session)).value, session); + // A daemon that predates `?meta=1` ignores the option and answers the full + // transcript; the route normalizes it, so the validator must accept it. + assert.deepEqual((await answer(() => ops.readSession("s1", metaOptions), session)).value, session); + // The navigation shape itself: no transcript, branch metadata in `info`. + const navigation = { filePath: "/f", info: { id: "s1", model: null, thinkingLevel: "off" }, leafId: "e1", tree: [], context: null }; + assert.deepEqual((await answer(() => ops.readSession("s1", metaOptions), navigation)).value, navigation); const page = { history: { messages: [] }, leafId: "e1", tipId: "e1" }; assert.deepEqual((await answer(() => ops.readContext("s1", "e1", contextOptions({ sync: { cursor: null, limit: 10 } })), page)).value, page); assert.deepEqual((await answer(() => ops.readContext("s1", undefined, contextOptions({ boundary: true })), { entryIds: ["e1"] })).value, { entryIds: ["e1"] }); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 274db4c07..8b6bb5592 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -1116,10 +1116,17 @@ function validResult(op: keyof SessionOps, result: unknown, args: unknown[]): bo case "exportSession": return isRecord(value) && typeof value.html === "string" && typeof value.fileName === "string"; case "readSession": { - // `?meta=1` is the navigation shape: no transcript, so `context` is null. const options = isRecord(args[1]) ? args[1] : {}; - return isRecord(value) && isRecord(value.info) - && (isRecord(value.context) || (options.meta === true && value.context === null)); + if (!isRecord(value) || !isRecord(value.info)) return false; + // A daemon that predates `?meta=1` ignores the option and answers the + // full transcript; the route derives the navigation shape from it. + if (isRecord(value.context)) return true; + if (options.meta !== true || value.context !== null) return false; + // Nothing to derive the navigation fields from: a null-context result + // must carry the tree, leaf and branch metadata itself (model may be null). + return Array.isArray(value.tree) && nullableString(value.leafId) + && (value.info.model === null || isRecord(value.info.model)) + && typeof value.info.thinkingLevel === "string"; } case "readContext": { // The context route reads a different shape per mode. diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 58f72deb9..5a0f70f3c 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -17,9 +17,10 @@ const stateRoute = await import("../app/api/sessions/[id]/state/route.ts"); const autoNameRoute = await import("../app/api/sessions/[id]/auto-name/route.ts"); const sessionsListRoute = await import("../app/api/sessions/route.ts"); const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await import("./session-reader.ts"); +const { sessionOps } = await import("./hosts/session-ops.ts"); const { allowFileRoot, normalizeSlashes } = await import("./file-access.ts"); const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); -const { RpcCommandError } = await import("./omp/rpc-process.ts"); +const { RpcCommandError, RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); const { closeHostLink, getHost, linkTimings } = await import("./hosts/hub.ts"); const { HostOpError } = await import("./hosts/link-protocol.ts"); const { revokeHost } = await import("./hosts/registry.ts"); @@ -254,7 +255,7 @@ test("?meta=1 answers the navigation shape and leaves the transcript to /context }); }); -test("?includeState=1 embeds the live agent shape with alive", async (t) => { +test("?includeState=1 keeps the historical shape: a live idle wrapper answers running:true", async (t) => { await withAgentDir(async (dir) => { const id = "0a000000-0000-4000-8000-000000000032"; writeSessionFile(dir, "2026-01-01_state.jsonl", { @@ -267,10 +268,11 @@ test("?includeState=1 embeds the live agent shape with alive", async (t) => { const previousSessions = globalThis.__ompSessions; const wrapper = { isAlive: () => true, - isRunning: () => true, + // Idle: no turn in flight. The historical contract still says running. + isRunning: () => false, send: async (command) => { assert.equal(command.type, "get_state"); - return { sessionId: id, isStreaming: true }; + return { sessionId: id, isStreaming: false }; }, host: getHost("local"), }; @@ -282,15 +284,47 @@ test("?includeState=1 embeds the live agent shape with alive", async (t) => { { params: Promise.resolve({ id }) }, ); assert.equal(live.status, 200); - assert.deepEqual((await live.json()).agent, { - running: true, - alive: true, - state: { sessionId: id, isStreaming: true }, - }); + const agent = (await live.json()).agent; + assert.deepEqual(agent, { running: true, state: { sessionId: id, isStreaming: false } }, + "an existing caller keeps the live-wrapper meaning of running; the idle/running split is opt-in"); }); }); -test("?includeState=1 without a live wrapper answers running:false, alive:false", async (t) => { +test("?includeState=alive opts into the idle/running split", async (t) => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000034"; + writeSessionFile(dir, "2026-01-01_alive.jsonl", { + id, + cwd: join(tmpdir(), "omp-web-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + ]); + const previousSessions = globalThis.__ompSessions; + let running = false; + const wrapper = { + isAlive: () => true, + isRunning: () => running, + send: async () => ({ sessionId: id, isStreaming: running }), + host: getHost("local"), + }; + globalThis.__ompSessions = new Map([[id, wrapper]]); + t.after(() => { globalThis.__ompSessions = previousSessions; }); + + const read = async () => (await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?includeState=alive`), + { params: Promise.resolve({ id }) }, + )).json(); + const idle = (await read()).agent; + assert.deepEqual(idle, { running: false, alive: true, state: { sessionId: id, isStreaming: false } }, + "alive but idle: the child exists, no turn is running"); + running = true; + const busy = (await read()).agent; + assert.deepEqual(busy, { running: true, alive: true, state: { sessionId: id, isStreaming: true } }); + }); +}); + +test("?includeState=1 without a live wrapper keeps the historical running:false", async (t) => { await withAgentDir(async (dir) => { const id = "0a000000-0000-4000-8000-000000000033"; writeSessionFile(dir, "2026-01-01_no-wrapper.jsonl", { @@ -309,13 +343,90 @@ test("?includeState=1 without a live wrapper answers running:false, alive:false" { params: Promise.resolve({ id }) }, ); assert.equal(res.status, 200); - const agent = (await res.json()).agent; + assert.deepEqual((await res.json()).agent, { running: false }, "no extra field for a caller that did not ask for the split"); + + const split = await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?includeState=alive`), + { params: Promise.resolve({ id }) }, + ); + const agent = (await split.json()).agent; assert.equal(agent.running, false); assert.equal(agent.alive, false); assert.equal(Object.hasOwn(agent, "state"), false, "no child, no state"); }); }); +test("?includeState never reports a child that exited after answering as live", async (t) => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000035"; + writeSessionFile(dir, "2026-01-01_exit-after-answer.jsonl", { + id, + cwd: join(tmpdir(), "omp-web-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, + ]); + const previousSessions = globalThis.__ompSessions; + let alive = true; + const wrapper = { + isAlive: () => alive, + isRunning: () => true, + send: async () => { + // The child answered, then exited before the handler resumed. + alive = false; + return { sessionId: id, isStreaming: true }; + }, + host: getHost("local"), + }; + globalThis.__ompSessions = new Map([[id, wrapper]]); + t.after(() => { globalThis.__ompSessions = previousSessions; }); + + const read = async (query) => (await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?${query}`), + { params: Promise.resolve({ id }) }, + )).json(); + const historical = (await read("includeState=1")).agent; + assert.deepEqual(historical, { running: false }, "the stale state is dropped and the live flag is not claimed"); + const split = (await read("includeState=alive")).agent; + assert.deepEqual(split, { running: false, alive: false }, "the child is gone: not alive, not running"); + }); +}); + +test("?meta=1 normalizes a daemon that ignores the option instead of shipping the transcript", async () => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000036"; + writeSessionFile(dir, "2026-01-01_old-daemon.jsonl", { + id, + cwd: join(tmpdir(), "omp-web-missing-project"), + timestamp: "2026-01-01T00:00:00.000Z", + }, [ + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello legacy" } }, + { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "world" } }, + { type: "model_change", id: "m1", parentId: "a1", timestamp: "2026-01-01T00:00:02.000Z", model: "test/model", role: "default" }, + { type: "thinking_level_change", id: "t1", parentId: "m1", timestamp: "2026-01-01T00:00:03.000Z", thinkingLevel: "high" }, + ]); + + const res = await sessionRoute.GET( + new Request(`http://localhost/api/sessions/${id}?meta=1`), + { params: Promise.resolve({ id }) }, + ); + const meta = await res.json(); + assert.equal(res.status, 200, JSON.stringify(meta)); + assert.deepEqual(Object.keys(meta).sort(), ["filePath", "info", "leafId", "sessionId", "tree"], + "the older daemon's transcript is not forwarded under the navigation shape"); + assert.equal(Object.hasOwn(meta, "context"), false); + assert.deepEqual(meta.info.model, { provider: "test", modelId: "model" }, "derived from the full context it did send"); + assert.equal(meta.info.thinkingLevel, "high"); + assert.equal(meta.info.messageCount, 2); + assert.equal(meta.info.firstMessage, "hello legacy"); + assert.equal(meta.leafId, "t1"); + assert.ok(Array.isArray(meta.tree) && meta.tree.length > 0); + }, { + // A daemon built before `?meta=1`: it drops the option and answers the full transcript. + readSession: (args) => sessionOps.readSession(args.id, { ...args.options, meta: false }), + }); +}); + test("context sends a strong ETag, answers 304, and re-keys it when the body changes", async () => { await withAgentDir(async (dir) => { const filePath = writeSessionFile(dir, "2026-01-01_etag.jsonl", { @@ -1851,9 +1962,9 @@ test("sidebar rename cannot fall back to disk while Edit owns the session", asyn }); test("a rename that times out on a live child answers 503 and writes nothing", async () => { - // docs/android/protocol.md §3.5: a busy omp keeps the file, so the route must - // not write the title slot beside it — the child's next flush would clobber - // the write and the client would show success for a rename that never stuck. + // A timeout leaves the completion unknown: omp may still apply the rename and + // write the file itself, so a slot write here would race its next flush and + // the client would show success for a rename that never stuck. await withAgentDir(async (dir) => { const id = "0a000000-0000-4000-8000-000000000012"; const filePath = writeSessionFile(dir, "0a000000-0000-4000-8000-000000000012.jsonl", { id, cwd: dir }, [ @@ -1869,8 +1980,8 @@ test("a rename that times out on a live child answers 503 and writes nothing", a isEditingHistory: () => false, async send(command) { commands.push(command); - // Exactly what the wrapper raises after GET_STATE_TIMEOUT_MS. - throw new WebRpcError("omp is busy and did not answer in time; the session keeps running.", "session_slow"); + // What the wrapper raises when the child never answers the command. + throw new RpcCommandTimeoutError("set_session_name", 5_000); }, }; const previousSessions = globalThis.__ompSessions; @@ -1880,15 +1991,76 @@ test("a rename that times out on a live child answers 503 and writes nothing", a method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Renamed" }), }), { params: Promise.resolve({ id }) }); assert.equal(response.status, 503); - assert.equal((await response.json()).code, "session_slow"); + const body = await response.json(); + assert.equal(body.code, "session_slow", "the client's retriable contract, not a generic 500"); assert.deepEqual(commands.map((command) => command.type), ["set_session_name"]); - assert.deepEqual(readFileSync(filePath), originalFile, "a slow rename must not rewrite the session title slot"); + assert.deepEqual(readFileSync(filePath), originalFile, "an unknown outcome must not touch the session title slot"); } finally { globalThis.__ompSessions = previousSessions; } }); }); +test("each real rename failure class keeps its intentional HTTP answer and writes nothing", async () => { + // The classes the wrapper actually raises on a live session, and the answer + // each one owes the client. None of them may fall back to the on-disk slot: + // the child still owns the file, so a write would be clobbered by its flush. + const cases = [ + // omp is busy with a turn: retriable, the session keeps running. + { error: () => new WebRpcError("omp is busy and did not answer in time; the session keeps running.", "session_slow"), status: 503, code: "session_slow" }, + // The status query timed out; the session was left running, so it retries. + { error: () => new WebRpcError("The OMP status query timed out. The session was left running; retry shortly.", "session_state_timeout"), status: 503, code: "session_state_timeout" }, + // A reload is replacing the child: retriable once it is back. + { error: () => new WebRpcError("This session is restarting — retry in a moment.", "session_restarting"), status: 503, code: "session_restarting" }, + // The child stopped responding and was reset: retriable on a fresh child. + { error: () => new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive"), status: 503, code: "session_unresponsive" }, + // The host link is down, nothing was sent: the client retries after reconnect. + { error: () => new WebRpcError("Workstation is offline. The run continues there; it reconnects automatically.", "host_offline", "refused"), status: 503, code: "host_offline", hostOffline: true, delivery: "refused" }, + // A history edit owns the session: the client waits, then retries. + { error: () => new WebRpcError("Wait for the history edit to finish", "session_busy"), status: 409, code: "session_busy" }, + // A timeout whose child died meanwhile: the completion is still unknown, so + // the file must not be rewritten just because no live process remains. + { error: () => new RpcCommandTimeoutError("set_session_name", 5_000), status: 503, code: "session_slow", childDied: true }, + ]; + for (const [index, expected] of cases.entries()) { + await withAgentDir(async (dir) => { + const id = `0a000000-0000-4000-8000-00000000004${index}`; + const filePath = writeSessionFile(dir, `${id}.jsonl`, { id, cwd: dir }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "question" } }, + { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [] } }, + ]); + cacheSessionPath(id, filePath); + const originalFile = readFileSync(filePath); + let alive = true; + const rpc = { + isAlive: () => alive, + host: getHost("local"), + isEditingHistory: () => false, + async send() { + // A timeout can outlive the child it was waiting for. + if (expected.childDied) alive = false; + throw expected.error(); + }, + }; + const previousSessions = globalThis.__ompSessions; + globalThis.__ompSessions = new Map([[id, rpc]]); + try { + const response = await sessionRoute.PATCH(new Request(`http://localhost/api/sessions/${id}`, { + method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Renamed" }), + }), { params: Promise.resolve({ id }) }); + const body = await response.json(); + assert.equal(response.status, expected.status, `${expected.code}: ${JSON.stringify(body)}`); + assert.equal(body.code, expected.code); + if (expected.hostOffline) assert.equal(body.hostOffline, true, "a client identifies the offline host"); + if (expected.delivery) assert.equal(body.delivery, expected.delivery, "nothing left this server"); + assert.deepEqual(readFileSync(filePath), originalFile, `${expected.code} must not rewrite the session title slot`); + } finally { + globalThis.__ompSessions = previousSessions; + } + }); + } +}); + test("a rename omp rejects outright still falls back to the file", async () => { // The other half of the contract: `RpcCommandError` means nothing was // applied, so the on-disk title slot is the correct place to write. From 6e64066b09bd03804046cdb9d6b79947a3385e91 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:12:51 +0100 Subject: [PATCH 3/3] fix(sessions): prove the prompt-less state poll and document the new options MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ?systemPrompt=0 test stubbed the wrapper's send, so it only proved the route forwarded the flag; forcing buildWebState(state, true) passed it. The test now runs the real dispatchCommand/buildWebState path with only the child's RPC faked, so the flag has to reach the built state — that mutation fails it now. Also correct the retriable-code comment (the wrapper does not raise session_slow; this route answers its own RpcCommandTimeoutError with it) and document ?meta=1, ?includeState=alive, ?systemPrompt=0 and the context ETag in AGENTS.md and CHANGELOG.md. --- AGENTS.md | 6 ++--- CHANGELOG.md | 1 + app/api/sessions/[id]/route.ts | 6 +++-- lib/session-routes.test.mjs | 40 ++++++++++++++++++++++++++++++---- 4 files changed, 44 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index dfc78bbcb..b130a1fd6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -117,13 +117,13 @@ app/ app/api/ sessions/route.ts GET list all sessions sessions/search/route.ts GET ?q= — NDJSON { scores } batches (titles + transcripts); closing the request stops the scan - sessions/[id]/route.ts GET/PATCH/DELETE session - sessions/[id]/context/route.ts GET ?leafId= — context for a specific leaf + sessions/[id]/route.ts GET/PATCH/DELETE session; GET ?meta=1 answers the navigation shape (tree + leaf, no transcript), ?includeState=alive the split liveness shape (`running` = a turn in flight, `alive` = the child exists; every other `includeState` value keeps the historical `running` = live-wrapper meaning) + sessions/[id]/context/route.ts GET ?leafId= — context for a specific leaf; answers a strong ETag for the exact bytes and 304 on a matching If-None-Match sessions/[id]/matches/route.ts GET ?q=&limit= — best `limit` search hits in the active conversation (best match, then newest); Load more asks for a longer prefix sessions/[id]/export/route.ts GET exported HTML for a session sessions/[id]/local-file/route.ts GET ?uri=local:// → `{ path, sessionId }`: the absolute path of a file in the session's own local:// directory, resolved on the owning host's daemon, and the canonical session that owns it (a live alias resolves to its current id; the tab must store that, since the alias goes with its wrapper). The open_file host tool then reads it through /api/files with that `sessionId`; 400 `invalid_local_uri` / `not_a_file`, 404 `session_not_found` / `file_not_found`, 403 on a symlink out, 501 `workspace_unsupported` for a host daemon that predates `resolveLocalFile` agent/new/route.ts POST { cwd, message, toolNames?, provider?, modelId? } - agent/[id]/route.ts GET state | POST any channel command + agent/[id]/route.ts GET state (?systemPrompt=0 drops the ~13 KB prompt from the poll) | POST any channel command events/route.ts GET multiplexed SSE | POST subscribe/unsubscribe channels events/link/route.ts GET WebSocket upgrade: the browser link (lib/browser-link.ts), bound to the request's web session; gated like every API route, 426 without an upgrade transport-metrics/route.ts GET { now } (the SSE clock probe) | POST { samples } → /omp-web/transport-metrics.jsonl diff --git a/CHANGELOG.md b/CHANGELOG.md index 548e9ad55..dcd1a95cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -98,6 +98,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f **Before upgrading:** after this update, every linked host already in the first pool uses this machine's provider logins (it can read their access tokens and stored API keys) without a confirmation having been shown. This includes a first pool disabled through the API, and a host added to the first pool later through `PUT /api/hosts` or by editing `pools.json`. Each linked member needs an updated ompweb host daemon (link protocol 9 at that release; cluster members now need link protocol 10, see the first entry) and omp 15.13.1 or newer; until its daemon is updated, cluster placement skips that member, and a start fails when no other member is eligible. Before updating, remove a host that should not receive the logins from the first pool using `PUT /api/hosts` or editing `~/.omp/agent/omp-web/pools.json`; the old version has no membership switch. - **Hosts can use the server's provider logins.** **Settings → Hosts** has a per-host toggle, **Use this server's provider logins**, off by default; turning it on asks for confirmation. Sessions started on that host then use the logins stored on the ompweb server instead of the host's own, through `omp auth-broker serve` on the server and a loopback forwarder in the host daemon. The host token never enters an omp process's environment, and OAuth refresh tokens never leave the server machine; the host can read current access tokens and stored API keys. Starting a session on a sharing host needs a daemon on link protocol v9 and omp 15.13.1 or newer, and is refused otherwise rather than falling back to the host's own logins. Custom providers in `models.yml`, environment-variable API keys and omp settings are not shared. A reverse proxy must let `/api/hosts/broker/` through without its own authentication, response buffering or redirects. - **Windows hosts can be pool workers and accept local maintenance controls.** `ompweb host status`, `drain` and `resume` now work on Windows through a named pipe with a random name and a per-start token, kept in `/omp-web/host-control.json`; requests without the current token are refused. Windows hosts also report CPU busy time and available memory, so pools can place sessions on them. Windows reports no load average, so CPU pressure there comes from busy time alone. +- **Native clients can read a session without downloading its transcript.** `GET /api/sessions/[id]?meta=1` answers only the navigation shape (message tree and current leaf), `?includeState=alive` splits liveness into `running` (a turn in flight) and `alive` (the child exists) while every other `includeState` value keeps the historical meaning, and `GET /api/agent/[id]?systemPrompt=0` drops the ~13 KB system prompt from the periodic state poll. `GET /api/sessions/[id]/context` now answers a strong `ETag` for the exact bytes and 304 on a matching `If-None-Match`, so an unchanged context costs no body. - **Archive and restore sessions on linked hosts.** Archiving now works for sessions on any linked machine, not only this one. The Archived Sessions browser lists every host's archive, shows which host each session is on, and restores it on that host. A host that is offline or runs an older ompweb host is named in the browser instead of hiding its archive silently. Restore rejects a session ID already active on any registered host, so every registered host must be online to restore, even an archive on this machine; the browser names the offline host that blocks it. A per-session claim stops web-server processes that share one agent directory from restoring the same session together; it does not coordinate separate web servers that share a daemon. A restore on another host keeps running when the web server stops waiting for it (after 30 s, or when the link drops), so the session stays claimed until that host's daemon process confirms it stopped: restoring the same ID again, on any host, is refused until then instead of creating a second active copy. Only the daemon process that took the restore can confirm that, so if the daemon was replaced, restarted or shut down meanwhile, or its host was unregistered, the session stays blocked: there is no timeout and no automatic clearing, and recovery is manual (see AGENTS.md). A restored session's attachments and other files are put back before the session becomes visible, so a file attached from another tab at that moment can no longer fail the restore or block retrying it. Restore streams archives with fixed 256 MiB compressed and expanded limits and rejects unsupported session IDs before consuming the archive. - **Traditional Chinese (`zh-TW`) interface language.** Select Traditional Chinese (繁體中文) in the top-bar language menu. On compact layouts, open **More controls** first. Alternatively, let omp-web pick it automatically when the browser language is `zh-TW`, `zh-HK`, `zh-MO`, or `zh-Hant`. Localized Web Push notifications and a Traditional Chinese README (`README.zh-TW.md`) are included. - **Several web apps can share one host daemon and the same live sessions.** Link additional servers with `ompweb host login --add --url ` (token from stdin). Prompts, tool progress, results and dialogs stay synchronized, and restarting one web app leaves the other connected to the same omp process. Link protocol v7 moves session startup, idle cleanup and interrupted-run recovery into the host; older links remain supported without sharing their processes. Schedule the first daemon upgrade while its host is quiescent. diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index 41a9bff90..eebaba262 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -11,8 +11,10 @@ import { RpcCommandError, RpcCommandTimeoutError } from "@/lib/omp/rpc-process"; /** Session-level failures a client retries instead of treating the request as * applied: omp is busy, restarting or was reset, and the session keeps going. - * `session_slow` is the wrapper's answer once a command exceeds its timeout, - * `session_state_timeout` the status poll's. */ + * `session_slow` and `session_state_timeout` are the codes the wrapper and the + * `get_state` dispatch use for "the completion is unknown"; this route answers + * its own `RpcCommandTimeoutError` with `session_slow` below, and accepts the + * rest from any wrapper that raises them, so a client sees one stable name. */ const RETRIABLE_SESSION_CODES: Record = { session_slow: true, session_state_timeout: true, diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 5a0f70f3c..011218b50 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -2272,9 +2272,36 @@ test("the state poll omits the system prompt only when asked", async (t) => { const sent = []; const wrapper = Object.create(AgentSessionWrapper.prototype); Object.assign(wrapper, { - _alive: true, proc: { isAlive: true }, promptRunning: false, streaming: false, compacting: false, + _alive: true, _sessionId: "sp", _sessionFile: "/sp.jsonl", _sessionName: "sp", + // The real `dispatchCommand`/`buildWebState` path runs: only the child's RPC + // is faked, so the route's flag has to travel all the way into the built state. + proc: { + isAlive: true, + sendCommand: async (command) => { + sent.push(command); + return { + sessionId: "sp", sessionFile: "/sp.jsonl", sessionName: "sp", + isStreaming: false, isCompacting: false, steeringMode: "all", followUpMode: "all", + interruptMode: "immediate", autoCompactionEnabled: false, autoRetryEnabled: false, + messageCount: 0, queuedMessageCount: 0, thinkingLevel: "off", + systemPrompt: ["first line", "second line"], + }; + }, + }, + // `buildWebState` reconciles identity through the owning host, so the fake + // needs the fields that path reads. + host: { id: "local", label: "This machine", status: () => "online", onStatus: () => () => {} }, + promptRunning: false, streaming: false, compacting: false, bashRunning: false, pendingUiRequests: new Map(), pendingHostTools: new Map(), pendingHostUris: new Map(), - send: async (command) => { sent.push(command); return { sessionId: "s", sessionFile: "/s.jsonl" }; }, + extensionStatuses: new Map(), extensionWidgets: new Map(), + movedFromIds: [], nativeQueuedMessages: { steering: [], followUp: [] }, + promptDispatchPendingCount: 0, historyEditInFlight: false, mcpListWaiter: null, + awaitingAgentStart: false, awaitingAgentStartDeadline: 0, continuationGraceUntil: 0, + streamSequence: 0, responseObserved: false, fastModeEnabled: false, sessionMovePending: false, + invalidateSessionLists() {}, resetStream() {}, clearLiveSnapshots() {}, + // `sent` records the frames at the child boundary (proc.sendCommand), so + // the assertion below is about what omp would receive. + send: async (command) => AgentSessionWrapper.prototype.dispatchCommand.call(wrapper, command), }); const route = await import("../app/api/agent/[id]/route.ts"); const before = globalThis.__ompSessions; @@ -2282,6 +2309,11 @@ test("the state poll omits the system prompt only when asked", async (t) => { t.after(() => { globalThis.__ompSessions = before; }); const full = await route.GET(new Request("http://localhost/api/agent/sp"), { params: Promise.resolve({ id: "sp" }) }); assert.equal(full.status, 200); - await route.GET(new Request("http://localhost/api/agent/sp?systemPrompt=0"), { params: Promise.resolve({ id: "sp" }) }); - assert.deepEqual(sent.map((command) => command.systemPrompt), [undefined, false], "the flag rides the get_state frame"); + assert.equal((await full.json()).state.systemPrompt, "first line\n\nsecond line", "the default poll carries the prompt"); + const lean = await route.GET(new Request("http://localhost/api/agent/sp?systemPrompt=0"), { params: Promise.resolve({ id: "sp" }) }); + assert.equal(lean.status, 200); + const leanState = (await lean.json()).state; + assert.equal("systemPrompt" in leanState, false, "?systemPrompt=0 drops the field from the built state"); + assert.equal(leanState.sessionId, "sp", "the rest of the state is untouched"); + assert.equal(sent.length, 2, "each poll asked the child once"); });