From bff0c47d325e55a5609495206418b9e9edbb739b Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Fri, 6 Nov 2026 05:18:15 +0100 Subject: [PATCH 1/5] fix(rpc): keep the omp child on every command timeout A command omp answered late used to recycle the child, ending a run that was merely busy and losing the prompt's outcome. Control and passthrough commands now share one bounded path: at most 32 may wait (else `session_busy`), and an expired wait answers `session_slow` with `maybeStarted` or `abortUnconfirmed` instead of hanging or destroying the child. Only a child that has produced no frame and answered nothing for five minutes is disposed, and its session reports that as an exited run with `detail: "stalled"`. `alive` is now reported separately from `running`, so a freshly spawned idle child is not mistaken for a dead one, and `silentForMs` says how long the child has been quiet. A stray unhandled promise rejection is journaled and rate-limited instead of taking the whole server down; an uncaught exception still exits 2. --- app/api/agent/[id]/route.ts | 36 +- app/api/agent/new/route.ts | 24 +- app/api/sessions/[id]/state/route.ts | 26 +- hooks/useAgentSession.ts | 92 ++++- instrumentation.node.ts | 40 +- lib/agent-client.ts | 34 +- lib/agent-command.test.mjs | 2 +- lib/agent-command.ts | 12 +- lib/i18n/locales/en.json | 8 + lib/i18n/locales/ja.json | 8 + lib/i18n/locales/zh-CN.json | 8 + lib/instrumentation-crash-policy.test.mjs | 15 + lib/message-outbox.ts | 2 +- lib/pi-types.ts | 37 +- lib/rpc-manager.test.mjs | 193 ++++++++-- lib/rpc-manager.ts | 439 ++++++++++++++++++---- 16 files changed, 856 insertions(+), 120 deletions(-) diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index c7ee93199..5b2b73656 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -37,22 +37,48 @@ 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); if (!session || !session.isAlive()) { - return Response.json({ running: false }); + return Response.json({ running: false, alive: false }); } try { - const state = await session.send({ type: "get_state" }); - return Response.json({ running: true, 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: session.isRunning(), alive: true, state }); } catch (error) { + // omp being slow is not the run ending: answer 503 so clients retry the + // poll instead of treating the session as idle/recovered. Both the code + // this tree raises (`session_slow`) and 0.6.0's own + // `session_state_timeout` mean the same thing to a client. + if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { + return Response.json( + { + error: error.message, + code: "session_slow", + ...error.details, + running: session.isRunning(), + alive: true, + silentForMs: session.silentForMs(), + }, + { status: 503 }, + ); + } if (error instanceof WebRpcError && error.code === "session_unresponsive") { - return Response.json({ running: false, recovered: true }); + return Response.json({ running: false, alive: false, recovered: true }); } throw error; } diff --git a/app/api/agent/new/route.ts b/app/api/agent/new/route.ts index dc62d98f1..671b01ab2 100644 --- a/app/api/agent/new/route.ts +++ b/app/api/agent/new/route.ts @@ -14,7 +14,13 @@ function newSessionErrorResponse(error: unknown) { // host_offline falls through to apiErrorResponse: 503 {hostOffline: true}. if ((error instanceof WebRpcError && error.code !== "host_offline") || error instanceof RpcCommandError) { return Response.json( - { error: error.message, code: error instanceof WebRpcError ? error.code : (error.code ?? "rpc_command_failed") }, + { + error: error.message, + code: error instanceof WebRpcError ? error.code : (error.code ?? "rpc_command_failed"), + // `maybeStarted`/`abortUnconfirmed` must reach the client, exactly as on + // POST /api/agent/[id]: without them a timeout looks like "not sent". + ...(error instanceof WebRpcError ? error.details : undefined), + }, { status: 400 }, ); } @@ -70,6 +76,22 @@ export async function POST(req: Request) { }; return await (preparing ? session.withPendingCommand(run, true) : run()); } catch (error) { + // A command timeout means omp is busy, not dead: the frame may already sit + // in the child's stdin and a run it started must survive. Same contract as + // POST /api/agent/[id]; the liveness watchdog alone may dispose the child. + // The body carries the real session id so a client that posted the prompt + // directly here can still poll and adopt the run `maybeStarted` announced. + if (error instanceof WebRpcError && error.code === "session_slow") { + return Response.json( + { + error: error.message, + code: error.code, + sessionId: realSessionId, + ...error.details, + }, + { status: 400 }, + ); + } // The child was spawned but the prompt never ran: without this cleanup a // failed set_model/set_thinking_level/prompt leaves an orphaned omp // process and a registry entry nobody will ever use. diff --git a/app/api/sessions/[id]/state/route.ts b/app/api/sessions/[id]/state/route.ts index 8467e3c95..ef2a97af2 100644 --- a/app/api/sessions/[id]/state/route.ts +++ b/app/api/sessions/[id]/state/route.ts @@ -27,22 +27,40 @@ async function sessionState(id: string): Promise { if (rpc?.isAlive()) { try { const state = await rpc.send({ type: "get_state" }); - return Response.json({ running: true, state }); + return Response.json({ running: rpc.isRunning(), alive: true, state }); } catch (error) { + // omp being slow is not the run ending: answer 503 so clients retry + // instead of treating the session as idle/recovered. Both the code + // this tree raises (`session_slow`) and 0.6.0's own + // `session_state_timeout` mean the same thing to a client. + if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { + return Response.json( + { + error: error.message, + code: "session_slow", + ...error.details, + running: rpc.isRunning(), + alive: true, + silentForMs: rpc.silentForMs(), + }, + { status: 503 }, + ); + } if (error instanceof WebRpcError && error.code === "session_unresponsive") { - return Response.json({ running: false, recovered: true }); + return Response.json({ running: false, alive: false, recovered: true }); } throw error; } } const exited = getExitedRpcSession(id); - if (exited) return Response.json({ running: false, exited }); + if (exited) return Response.json({ running: false, alive: false, exited }); const resolved = await resolveSessionHostOr404(id); if ("response" in resolved) return resolved.response; const result = await resolved.host.sessionOps.readSessionState(id); - return result.ok ? Response.json(result.value) : opErrorResponse(result); + if (!result.ok) return opErrorResponse(result); + return Response.json({ ...(result.value as Record), alive: false }); } catch (error) { return apiErrorResponse(error); } diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 0b27a1ee3..b86ac9270 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -18,7 +18,7 @@ import type { import { normalizeToolCalls } from "@/lib/normalize"; import { hasVisibleAssistantContent } from "@/lib/assistant-response"; import type { ThinkingModelMeta } from "@/lib/thinking-levels"; -import { HostOfflineError, TransportLostError, getOutboxScope, rememberOutboxScope, sendAgentCommand, setSessionAdvisorSpawn } from "@/lib/agent-client"; +import { AgentCommandError, HostOfflineError, TransportLostError, getOutboxScope, rememberOutboxScope, sendAgentCommand, setSessionAdvisorSpawn } from "@/lib/agent-client"; import type { HostStatus } from "@/lib/hosts/host"; import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { newChatDraftKey, remoteHostId } from "@/lib/project-ordering"; @@ -215,6 +215,17 @@ function currentRunAssistant(context: SessionData["context"], previousEntryIds: } } return null; +/** A state GET answers 503 when omp is alive but its event loop is blocked by + * a large session (`session_slow`, and 0.6.0's own `session_state_timeout`). + * That is "still running, retry later" — never a load failure. */ +async function isBusySessionResponse(res: Response): Promise { + if (res.status !== 503) return false; + try { + const body = await res.json() as { code?: unknown }; + return body?.code === "session_slow" || body?.code === "session_state_timeout"; + } catch { + return false; + } } export interface UseAgentSessionOptions { @@ -645,6 +656,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } | null>(null); const lastShownExitRef = useRef(null); const runHadContentRef = useRef(false); + // Set when the prompt ack timed out but omp may already hold the frame + // (`session_slow` + `maybeStarted`). Suppresses the "stopped without a + // response" claim for this run and keeps the send lock until frames or a + // successful get_state settle it. + const maybeStartedRunRef = useRef(false); // Native starts/epoch changes also fence recovery, even without a local send. const responseRunVersionRef = useRef(0); // Persisted entries preceding a locally submitted run cannot supply its answer. @@ -1019,6 +1035,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync]); + // omp answered a state read with 503 `session_slow`: the child is alive and + // a run is under way, but its event loop is blocked and `get_state` timed + // out. The run must stay marked so the periodic reconcile poll settles it, + // and the observer stream attaches (frames are the completion path once omp + // answers again). The on-disk transcript is already loaded by the caller. + const markSessionAliveStateUnknown = useCallback(() => { + if (!agentRunningRef.current) { + agentRunningRef.current = true; + setAgentRunning(true); + } + syncActionsRef.current?.subscribe(false); + }, []); + const loadSession = useCallback(async (sid: string, showLoading = false, includeState = false, fenceRunId?: number) => { const requestSeq = ++contextRequestSeqRef.current; catchUp.invalidate(); @@ -1101,7 +1130,20 @@ export function useAgentSession(opts: UseAgentSessionOptions) { return { context: d.context, agentState: null }; } const { stateRes, agentState } = reply; - if (!stateRes.ok) throw new Error(`HTTP ${stateRes.status}`); + if (!stateRes.ok) { + // A busy child (503 `session_slow` / `session_state_timeout`) is not + // a failed load: the transcript above is the on-disk copy, the run + // keeps going and the state is merely unknown right now. + if (await isBusySessionResponse(stateRes)) { + if (!hookAliveRef.current || sessionIdRef.current !== sid + || contextRequestSeqRef.current !== requestSeq || promptRunIdRef.current !== requestRun) { + return null; + } + markSessionAliveStateUnknown(); + return { context: d.context, agentState: null }; + } + throw new Error(`HTTP ${stateRes.status}`); + } if (!hookAliveRef.current) return null; if (sessionIdRef.current !== sid) { if (showLoading) setLoading(false); @@ -1164,7 +1206,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // Ensure the flag is cleared even if the pre-state early-return path was taken if (showLoading && includeState && !messagesLoaded) initialHydrationPendingRef.current = false; } - }, [catchUp, refreshSubagentHistory, applyAuthoritativeModel, beginAuthoritativeModelSync, applyQueueStateSnapshot, applySkillDiagnosticsSnapshot]); + }, [catchUp, refreshSubagentHistory, applyAuthoritativeModel, beginAuthoritativeModelSync, applyQueueStateSnapshot, applySkillDiagnosticsSnapshot, markSessionAliveStateUnknown]); const loadContext = useCallback(async (sid: string, leafId: string | null, includePreCompaction = false): Promise => { const seq = ++contextRequestSeqRef.current; @@ -1985,8 +2027,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // error — never leave the user with a disappeared spinner and no // explanation. Builtin slash commands are allowed to complete without // an assistant message, hence allowEmptyResponse above. - const message = translate("agentSession.responseFailed"); - addNotice({ type: "error", message }); + // A prompt whose ack timed out may have started late: do not claim it + // failed, repeat the localized hint instead (no error toast). + const message = maybeStartedRunRef.current + ? translate("agentSession.maybeStarted") + : translate("agentSession.responseFailed"); + addNotice({ type: maybeStartedRunRef.current ? "warning" : "error", message }); } catchUp.invalidate(); eventCoalescer.reset(); @@ -2011,6 +2057,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { lastRunErrorRef.current = null; runErrorAssistantRef.current = null; independentRunErrorRef.current = null; + maybeStartedRunRef.current = false; slashCommandRunRef.current = false; onAgentEnd?.(); } @@ -2383,6 +2430,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { lastRunErrorRef.current = null; runErrorAssistantRef.current = null; independentRunErrorRef.current = null; + maybeStartedRunRef.current = false; break; case "agent_end": { // isTerminal === false means an async delivery resumes this run soon. @@ -2473,6 +2521,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { lastRunErrorRef.current = null; runErrorAssistantRef.current = null; independentRunErrorRef.current = null; + maybeStartedRunRef.current = false; slashCommandRunRef.current = false; if (endedSid) { void loadSession(endedSid, false, false, endedRunId); @@ -3215,6 +3264,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { lastRunErrorRef.current = null; runErrorAssistantRef.current = null; independentRunErrorRef.current = null; + maybeStartedRunRef.current = false; runPreviousEntryIdsRef.current = sessionIdRef.current ? null : []; agentRunningRef.current = true; slashCommandRunRef.current = isSlashCommandPrompt; @@ -3317,6 +3367,15 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (promptRunIdRef.current !== promptRunId) return { status: "superseded" }; promptDispatchPendingRef.current = false; console.error("Failed to send message:", e); + // The prompt frame may already sit in omp's stdin (ack timed out while + // omp was busy). Not an undo: keep the optimistic turn, keep reporting + // the run, and keep sending locked until a frame or the next successful + // get_state settles it. A later rollback would contradict the hint. + if (e instanceof AgentCommandError && e.code === "session_slow" && e.maybeStarted) { + maybeStartedRunRef.current = true; + addNotice({ type: "warning", message: translate("agentSession.maybeStarted") }); + return { status: "accepted" }; + } // Every failure here (stream connect, startup, set_model, or the prompt // POST itself) leaves no run to show, so roll back the optimistic bubble. setOptimisticUserMessage(null); @@ -3489,16 +3548,33 @@ export function useAgentSession(opts: UseAgentSessionOptions) { let restoredQueue: RestoredQueue | null | undefined; let unsupported = false; let failures = 0; + let abortUnconfirmed = false; // A failure after omp already withdrew would lose the texts on the // per-entry path (the queue is empty by then). Retrying the same command // is safe instead: omp returns whatever is still queued. - for (let attempt = 0; attempt < 2 && restoredQueue === undefined && !unsupported && (attempt === 0 || sameRun()); attempt++) { + for (let attempt = 0; attempt < 2 && restoredQueue === undefined && !unsupported && !abortUnconfirmed && (attempt === 0 || sameRun()); attempt++) { try { restoredQueue = (await sendAgentCommand(sid, { type: "abort_and_restore_queue" })) ?? null; } catch (error) { unsupported = error instanceof Error && error.message.includes("Unknown command"); if (!unsupported) failures += 1; + // A stop omp never confirmed (too busy to answer) is not a stopped run: + // the frame may sit in its stdin and the run may still execute. Nothing + // is known about the queue either, so this attempt is not retried — + // a second 30-second window on a child that is still busy only keeps + // the Stop pending longer. + if (error instanceof AgentCommandError && error.code === "session_slow" && error.abortUnconfirmed) { + abortUnconfirmed = true; + } + } + } + if (abortUnconfirmed) { + // Nothing is known about the queue, so neither the composer nor the queue + // chips may be rewritten on a guess. + if (hookAliveRef.current && sessionIdRef.current === sid) { + addNotice({ type: "warning", message: translate("agentSession.abortUnconfirmed") }); } + return; } if (!unsupported) { const steering = Array.isArray(restoredQueue?.steering) ? restoredQueue.steering : []; @@ -3581,6 +3657,10 @@ export function useAgentSession(opts: UseAgentSessionOptions) { await sendAgentCommand(sid, { type: "abort" }); } catch (e) { console.error("Failed to abort:", e); + if (e instanceof AgentCommandError && e.code === "session_slow" && e.abortUnconfirmed + && hookAliveRef.current && sessionIdRef.current === sid) { + addNotice({ type: "warning", message: translate("agentSession.abortUnconfirmed") }); + } } } // From here only late recovery remains: a new run's Stop must not wait on it. diff --git a/instrumentation.node.ts b/instrumentation.node.ts index 3e41722fa..be98c8004 100644 --- a/instrumentation.node.ts +++ b/instrumentation.node.ts @@ -102,9 +102,9 @@ export async function register(): Promise { // user is away leaves no trace in a terminal that no longer exists (CLI runs // are killed with their terminal; pages then show endless loading until the // process is restarted). Append fatal errors and event-loop stalls to a file - // so the next incident explains itself. Node's default crash semantics are - // preserved — this only adds the record before exiting — except for client - // aborts, which are journaled and survived (see below). + // so the next incident explains itself. An uncaught exception keeps Node's + // crash semantics (journal + console record, then exit); client aborts and + // unhandled rejections are journaled and survived (see below). const logDir = getDiagnosticsDir(); const logPath = join(logDir, "diagnostics.log"); const appendDiag = (kind: string, detail: string) => { @@ -128,14 +128,40 @@ export async function register(): Promise { return; } appendDiag("crash", `uncaughtException ${describe(error)}`); + console.error(`[omp-web] uncaught exception — exiting: ${describe(error)}`); // An uncaughtException listener suppresses Node's default exit; keep the - // crash-visible semantics by exiting explicitly. + // crash-visible semantics by exiting explicitly. Unlike a rejection, the + // throw escaped a request handler or timer halfway through its work, so the + // process state (a half-written session file, a held mutex) is unknown and + // there is no safe resume point: staying up would serve corrupted state. process.exit(2); }); + // Rejections of fire-and-forget chains are logged and survived: nobody + // awaited that promise, so every request path is still intact, and killing + // the server for one would take down every chat it serves — the scheduled + // task does not restart a server that dies on its own. The journal always + // gets the record; the console copy is rate-limited so a tick that rejects + // once a second cannot bury it. + let rejectionWindowStart = Date.now(); + let rejectionsLogged = 0; + let rejectionsSuppressed = 0; process.on("unhandledRejection", (reason) => { - appendDiag("crash", `unhandledRejection ${describe(reason)}`); - // Same as above: preserve Node's crash-on-unhandled-rejection default. - process.exit(2); + appendDiag("rejection", `unhandledRejection ${describe(reason)}`); + const now = Date.now(); + if (now - rejectionWindowStart >= 60_000) { + if (rejectionsSuppressed > 0) { + console.error(`[omp-web] ${rejectionsSuppressed} further unhandled rejection(s) in the last minute were journaled only.`); + } + rejectionWindowStart = now; + rejectionsLogged = 0; + rejectionsSuppressed = 0; + } + if (rejectionsLogged < 10) { + rejectionsLogged += 1; + console.error(`[omp-web] unhandled rejection (server keeps running): ${describe(reason)}`); + } else { + rejectionsSuppressed += 1; + } }); let lastTick = Date.now(); let lastCpu = process.cpuUsage(); diff --git a/lib/agent-client.ts b/lib/agent-client.ts index 451976396..3ed1b7deb 100644 --- a/lib/agent-client.ts +++ b/lib/agent-client.ts @@ -11,6 +11,31 @@ import { recordTransportSample, sendSessionCommand, type CommandReply } from "@/lib/event-stream"; import { formatApiError } from "@/lib/i18n/api-error"; +/** A failed `POST /api/agent/[id]` carrying the route's stable code. Callers + * that must react differently from a plain error (a `session_slow` ack timeout + * with `maybeStarted` is not a rolled-back prompt; `abortUnconfirmed` is not a + * completed stop; `session_running_elsewhere` means another omp holds the + * session and the user must decide) branch on these fields. */ +export class AgentCommandError extends Error { + readonly code: string | undefined; + readonly maybeStarted: boolean; + /** The abort frame may have reached omp, but nothing confirmed it: the run + * may still be executing. */ + readonly abortUnconfirmed: boolean; + constructor( + message: string, + code: string | undefined, + maybeStarted: boolean, + abortUnconfirmed: boolean, + ) { + super(message); + this.name = "AgentCommandError"; + this.code = code; + this.maybeStarted = maybeStarted; + this.abortUnconfirmed = abortUnconfirmed; + } +} + // Sessions whose per-chat advisor toggle is on: their lazily spawned omp // process must start with --advisor. Keyed by session id because the spawn // decision happens inside the route, which only sees id + query string. @@ -99,6 +124,8 @@ export async function sendAgentCommand( code?: string; hostOffline?: boolean; delivery?: string; + maybeStarted?: boolean; + abortUnconfirmed?: boolean; }; const failed = reply.status < 200 || reply.status >= 300 || Boolean(body.error); let outcome = failed ? "error" : "ok"; @@ -126,7 +153,12 @@ export async function sendAgentCommand( const message = body.error || body.code ? formatApiError(body) : `HTTP ${reply.status}`; if (reply.status === 503 && body.hostOffline) throw new HostOfflineError(message, body.delivery === "unknown"); if (reply.status === 503 && body.code === "transport_lost") throw new TransportLostError(message); - throw new Error(message); + throw new AgentCommandError( + message, + body.code, + body.maybeStarted === true, + body.abortUnconfirmed === true, + ); } return body.data as T; } diff --git a/lib/agent-command.test.mjs b/lib/agent-command.test.mjs index 4eed36c7f..cd7be7ec2 100644 --- a/lib/agent-command.test.mjs +++ b/lib/agent-command.test.mjs @@ -179,7 +179,7 @@ test("POST answers carry received/replied times", async (t) => { test("GET returns the agent state without command transport timing headers", async (t) => { useRegistry(t, { s2: fake() }); const res = await route.GET(new Request("http://omp.test/api/agent/s2"), ctx("s2")); - assert.deepEqual(await jsonOf(res), { running: true, state: { ok: true } }); + assert.deepEqual(await jsonOf(res), { running: false, alive: true, state: { ok: true } }); assert.equal(res.headers.get("x-omp-received-at"), null); assert.equal(res.headers.get("x-omp-replied-at"), null); }); diff --git a/lib/agent-command.ts b/lib/agent-command.ts index e362a22df..6ba7f986a 100644 --- a/lib/agent-command.ts +++ b/lib/agent-command.ts @@ -36,7 +36,9 @@ export function commandErrorResponse(error: unknown): Response { } // host_offline falls through to apiErrorResponse: 503 {hostOffline: true}. if (error instanceof WebRpcError && error.code !== "host_offline") { - return Response.json({ error: error.message, code: error.code }, { status: 400 }); + // `maybeStarted`/`abortUnconfirmed` must reach the client: without them a + // timeout looks like "not sent". + return Response.json({ error: error.message, code: error.code, ...error.details }, { status: 400 }); } if (error instanceof RpcCommandError) { return Response.json({ error: error.message, code: error.code ?? "rpc_command_failed" }, { status: 400 }); @@ -53,11 +55,17 @@ function sendFences(): Map> { return (globalThis.__ompSendFences ??= new Map()); } +export interface RunAgentCommandOptions { + /** Upload receipts the outbox already proved, so its own retry is not re-checked. */ + trustedUploads?: OutboxUploadReceipt[]; +} + /** Everything POST /api/agent/[id] does once the body is parsed; shared with * the browser socket. `owner`: the caller's web session (lib/web-auth.ts * `requestOwner`), whose uploads a prompt may attach. Never throws: failures * become `commandErrorResponse`. */ -export async function runAgentCommand(id: string, body: unknown, advisor: boolean, owner: string, trustedUploads?: OutboxUploadReceipt[]): Promise { +export async function runAgentCommand(id: string, body: unknown, advisor: boolean, owner: string, options: RunAgentCommandOptions = {}): Promise { + const trustedUploads = options.trustedUploads; let release = () => {}; // frees this command's send fence; idempotent try { const command = body as { type?: unknown; [key: string]: unknown } | null; diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index ddfdb2abf..772989299 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -55,6 +55,8 @@ "agentSession.reloadedResources": "Reloaded session resources", "agentSession.responseFailed": "The agent stopped without returning a response. Please retry and check the provider configuration if this continues.", "agentSession.sendFailed": "Failed to send message: {detail}", + "agentSession.maybeStarted": "omp is busy — your message may still be running.", + "agentSession.abortUnconfirmed": "The stop is not confirmed yet — omp is busy and the run may still be going. The session keeps running.", "agentSession.sessionRenamed": "Session renamed to {name}", "agentSession.shellSessionFailed": "Unable to create a session for the shell command", "agentSession.queuedPromotionUnavailable": "The queued follow-up is no longer available to steer.", @@ -307,6 +309,9 @@ "notifications.completedBody": "Task finished.", "notifications.inputBody": "Waiting for your answer: {detail}", "notifications.inputBodyNoDetail": "Waiting for your answer.", + "notifications.reminderTitle": "Reminder: {title}", + "notifications.reminderBody": "Still waiting since {since}: {detail}", + "notifications.reminderBodyNoDetail": "Still waiting for your answer since {since}.", "notifications.errorBody": "Run failed: {detail}", "notifications.errorBodyNoDetail": "Run failed.", "notifications.modelSwitchBody": "Switched {from} → {to}: {detail}", @@ -329,6 +334,8 @@ "notifications.typeCompletedDesc": "A prompt and the background work it started are done. Subagents never notify.", "notifications.typeInput": "Waiting for input", "notifications.typeInputDesc": "The agent asks a question or needs an approval.", + "notifications.inputReminder": "Remind me about unanswered questions", + "notifications.inputReminderDesc": "The notification repeats while a question stays unanswered, until it is answered or cancelled.", "notifications.typeError": "Run failed", "notifications.typeErrorDesc": "A run stops with an error after retries and fallbacks, or the omp process exits.", "notifications.typeModelSwitch": "Model switched automatically", @@ -680,6 +687,7 @@ "directoryPicker.cloneInterrupted": "The clone connection ended unexpectedly. Check the destination before retrying.", "directoryPicker.cloneOutputLabel": "git clone output", "errors.session_state_timeout": "OMP status query timed out. The session was kept running. Try again shortly.", + "errors.session_slow": "The agent is busy and did not answer in time. It is still running — try again in a moment.", "errors.access_denied": "Access denied", "errors.outbox_dispatched": "This message is already being delivered.", "errors.outbox_scope_changed": "This message belongs to another omp-web installation or sign-in configuration.", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 7411bc7cd..f575300b3 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -55,6 +55,8 @@ "agentSession.reloadedResources": "セッションリソースを再読み込みしました", "agentSession.responseFailed": "エージェントが応答を返さずに停止しました。もう一度お試しください。続く場合はプロバイダー設定を確認してください。", "agentSession.sendFailed": "メッセージの送信に失敗しました: {detail}", + "agentSession.maybeStarted": "omp は処理中です。メッセージはまだ実行されている可能性があります。", + "agentSession.abortUnconfirmed": "停止はまだ確認されていません。omp は処理中で、実行が続いている可能性があります。セッションは動作を続けます。", "agentSession.sessionRenamed": "セッション名を {name} に変更しました", "agentSession.shellSessionFailed": "シェルコマンド用のセッションを作成できませんでした", "agentSession.queuedPromotionUnavailable": "このフォローアップはキューに存在しないため、ステアリングに変更できません。", @@ -290,6 +292,9 @@ "notifications.completedBody": "タスクが完了しました。", "notifications.inputBody": "回答を待っています: {detail}", "notifications.inputBodyNoDetail": "回答を待っています。", + "notifications.reminderTitle": "リマインダー: {title}", + "notifications.reminderBody": "{since} から回答を待っています: {detail}", + "notifications.reminderBodyNoDetail": "{since} から回答を待っています。", "notifications.errorBody": "実行に失敗しました: {detail}", "notifications.errorBodyNoDetail": "実行に失敗しました。", "notifications.modelSwitchBody": "{from} → {to} に切り替えました: {detail}", @@ -312,6 +317,8 @@ "notifications.typeCompletedDesc": "プロンプトと、それが開始したバックグラウンド作業が完了したとき。サブエージェントでは通知しません。", "notifications.typeInput": "入力待ち", "notifications.typeInputDesc": "エージェントが質問したり承認を求めたりしたとき。", + "notifications.inputReminder": "未回答の質問を再通知する", + "notifications.inputReminderDesc": "回答またはキャンセルされるまで、通知を繰り返します。", "notifications.typeError": "実行失敗", "notifications.typeErrorDesc": "再試行とフォールバックの後に実行がエラーで止まったとき、または omp プロセスが終了したとき。", "notifications.typeModelSwitch": "モデルの自動切り替え", @@ -663,6 +670,7 @@ "directoryPicker.cloneInterrupted": "クローンの接続が予期せず終了しました。再試行する前に保存先を確認してください。", "directoryPicker.cloneOutputLabel": "git clone の出力", "errors.session_state_timeout": "OMPの状態取得がタイムアウトしました。セッションは停止せず維持しています。しばらくしてから再試行してください。", + "errors.session_slow": "エージェントは処理中で時間内に応答しませんでした。実行は続いています。しばらくしてから再試行してください。", "errors.access_denied": "アクセスが拒否されました", "errors.outbox_dispatched": "このメッセージはすでに配信中です。", "errors.outbox_scope_changed": "このメッセージは別の omp-web インストールまたはサインイン設定に属しています。", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 7599b575c..a1b5c0257 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -55,6 +55,8 @@ "agentSession.reloadedResources": "已重新加载会话资源", "agentSession.responseFailed": "智能体在未返回响应的情况下停止了。请重试;如果问题持续,请检查提供商配置。", "agentSession.sendFailed": "发送消息失败:{detail}", + "agentSession.maybeStarted": "omp 正忙——你的消息可能仍在运行中。", + "agentSession.abortUnconfirmed": "停止尚未确认——omp 正忙,运行可能仍在继续。会话仍在运行。", "agentSession.sessionRenamed": "会话已重命名为 {name}", "agentSession.shellSessionFailed": "无法为 shell 命令创建会话", "agentSession.queuedPromotionUnavailable": "该后续消息已不在队列中,无法转为引导消息。", @@ -290,6 +292,9 @@ "notifications.completedBody": "任务已完成。", "notifications.inputBody": "正在等待你的回答:{detail}", "notifications.inputBodyNoDetail": "正在等待你的回答。", + "notifications.reminderTitle": "提醒:{title}", + "notifications.reminderBody": "自 {since} 起一直在等待:{detail}", + "notifications.reminderBodyNoDetail": "自 {since} 起一直在等待你的回答。", "notifications.errorBody": "运行失败:{detail}", "notifications.errorBodyNoDetail": "运行失败。", "notifications.modelSwitchBody": "已切换 {from} → {to}:{detail}", @@ -312,6 +317,8 @@ "notifications.typeCompletedDesc": "提示及其启动的后台工作全部完成。子代理不会触发通知。", "notifications.typeInput": "等待输入", "notifications.typeInputDesc": "代理提出问题或需要批准。", + "notifications.inputReminder": "提醒我未回答的问题", + "notifications.inputReminderDesc": "问题未被回答或取消时,通知会重复发送。", "notifications.typeError": "运行失败", "notifications.typeErrorDesc": "运行在重试和回退后仍因错误停止,或 omp 进程退出。", "notifications.typeModelSwitch": "模型自动切换", @@ -663,6 +670,7 @@ "directoryPicker.cloneInterrupted": "克隆连接意外结束。请先检查目标目录,再重试。", "directoryPicker.cloneOutputLabel": "git clone 输出", "errors.session_state_timeout": "OMP 状态查询超时。会话仍在运行,未被停止。请稍后重试。", + "errors.session_slow": "代理正忙,未能及时响应。它仍在运行,请稍后重试。", "errors.access_denied": "访问被拒绝", "errors.outbox_dispatched": "这条消息正在投递中。", "errors.outbox_scope_changed": "这条消息属于另一个 omp-web 安装或登录配置。", diff --git a/lib/instrumentation-crash-policy.test.mjs b/lib/instrumentation-crash-policy.test.mjs index cf00ed172..53f9180f1 100644 --- a/lib/instrumentation-crash-policy.test.mjs +++ b/lib/instrumentation-crash-policy.test.mjs @@ -77,6 +77,21 @@ test("a client disconnect surfacing as uncaught `aborted` is journaled without e assert.doesNotMatch(journal, /\[crash\]/); }); +// Fire-and-forget chains reject without an awaiter; killing every chat the +// server serves for one would be worse than a journaled record. +const rejectAfterRegister = (options) => runAfterRegister(` + void Promise.reject(new Error("background boom")); + setTimeout(() => process.exit(0), 300); +`, options); + +test("an unhandled rejection is journaled and the server keeps serving", () => { + const { status, journal, stderr } = rejectAfterRegister(); + assert.equal(status, 0, stderr); + assert.match(journal, /\[rejection\] unhandledRejection Error: background boom/); + assert.match(stderr, /unhandled rejection \(server keeps running\): Error: background boom/); + assert.doesNotMatch(journal, /\[crash\]/); +}); + test("the journal follows an isolated agent dir and keeps ~/.omp/omp-web by default", () => { const isolated = throwAfterRegister(`new Error("boom")`); assert.match(isolated.journal, /\[crash\] uncaughtException Error: boom/); diff --git a/lib/message-outbox.ts b/lib/message-outbox.ts index 4f5dcc86b..f0ba3ae94 100644 --- a/lib/message-outbox.ts +++ b/lib/message-outbox.ts @@ -728,7 +728,7 @@ async function deliver(entry: Row): Promise { publish(sessionId); try { // attachUploads mutates this same command before writing it: the watcher matches the final attachment block too. - const response = await runAgentCommand(sessionId, command, current.advisor === 1, current.owner, uploadReceipts); + const response = await runAgentCommand(sessionId, command, current.advisor === 1, current.owner, { trustedUploads: uploadReceipts }); if (!response.ok) { // Nothing was written: a gone child is retried, and any other refusal is classified as not sent. const written = nativeWriteStarted(command); diff --git a/lib/pi-types.ts b/lib/pi-types.ts index c0b5e67a5..da2cb20c7 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -16,6 +16,26 @@ export type UsageLimitState = export type SlowModeScope = "session" | "global"; +/** omp's goal record (`goal` command reply, `goal_updated`, `get_state.goal.goal`). */ +export interface GoalInfo { + id: string; + objective: string; + /** `active` / `paused`; completed and dropped goals answer `null` instead. */ + status: string; + tokenBudget?: number; + tokensUsed: number; + timeUsedSeconds: number; + createdAt: number; + updatedAt: number; +} + +/** Mirror of omp's GoalModeState: the `goal` reply and the `goal` field of `get_state`. */ +export interface GoalModeState { + enabled: boolean; + mode: string; + goal: GoalInfo | null; +} + export interface ModelLike { id: string; provider: string; @@ -102,6 +122,8 @@ export interface RpcSessionState { tokensPerSecond?: number | null; /** Structured skill resolution diagnostics; absent on older OMP builds. */ skillDiagnostics?: SkillDiagnosticsSnapshot; + /** omp goal mode; absent on older OMP builds (never invented here). */ + goal?: GoalModeState | null; } /** @@ -127,7 +149,8 @@ export interface WebSessionState { queuedMessageCount: number; queuedMessages: QueuedMessages; 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; @@ -140,6 +163,8 @@ export interface WebSessionState { /** Parsed public diagnostics DTO; absent means unsupported or malformed. */ skillDiagnostics?: SkillDiagnosticsSnapshot; todoPhases: TodoPhase[]; + /** omp goal mode snapshot; omitted when the child predates the `goal` field. */ + goal?: GoalModeState | null; extensionStatuses: Array<{ key: string; text: string }>; extensionWidgets: Array<{ key: string; lines: string[]; placement: "aboveEditor" | "belowEditor" }>; } @@ -224,6 +249,16 @@ export interface RpcAskDialogAnswer { customInput?: string; } +/** + * One answer to a blocking extension dialog. Exactly one variant is sent, both + * by the web dialog (ExtensionDialog) and by the notification answer endpoint. + */ +export type ExtensionUiResponse = + | { value: string } + | { confirmed: boolean } + | { cancelled: true } + | { answers: RpcAskDialogAnswer[] }; + /** * omp's rpc-ui extension UI request frames, including the methods missing from * the browser-facing union in lib/types.ts (`open_url`, `cancel`). The wrapper diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index c58bac61b..7ef1e42ed 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -469,7 +469,7 @@ test("abort_and_prompt images go through the same server-side validation as prom await wrapper.destroyAndWait(); }); -test("get_state timeout preserves the process and reports a transient status error", async () => { +test("get_state timeout preserves the process and reports session_slow", async () => { const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); @@ -495,7 +495,7 @@ test("get_state timeout preserves the process and reports a transient status err wrapper.send({ type: "get_state" }), (err) => { assert.ok(err instanceof WebRpcError || err.name === "WebRpcError"); - assert.equal(err.code, "session_state_timeout"); + assert.equal(err.code, "session_slow"); return true; }, ); @@ -517,7 +517,7 @@ test("a running task survives a slow status query and later state reads recover" const dispose = wrapper.proc.dispose; wrapper.proc.dispose = async () => { disposed = true; return dispose(); }; emit({ type: "agent_start" }); - await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_state_timeout" }); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); assert.equal(disposed, false, "a read-only poll must never stop generation"); assert.equal(wrapper.isRunning(), true); const state = await wrapper.send({ type: "get_state" }); @@ -528,7 +528,7 @@ test("a running task survives a slow status query and later state reads recover" assert.equal(wrapper.isAlive(), true); }); -test("prompt ack timeout recycles a child that accepts the frame but withholds its response", async (t) => { +test("prompt ack timeout keeps the child and reports session_slow with maybeStarted", async (t) => { const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); @@ -566,15 +566,19 @@ test("prompt ack timeout recycles a child that accepts the frame but withholds i pending, (err) => { assert.ok(err instanceof WebRpcError || err.name === "WebRpcError"); - assert.equal(err.code, "session_unresponsive"); + assert.equal(err.code, "session_slow"); + // The frame may already sit in the child's stdin: the client must not + // treat this as "not sent" and resend the text. + assert.equal(err.details?.maybeStarted, true); return true; }, ); - assert.equal(disposed, true); - assert.equal(removedFromRegistry, true); - assert.equal(wrapper.isAlive(), false); - assert.equal(wrapper.isRunning(), false); + // Busy, not dead: recycling here killed the run the prompt may have started. + assert.equal(disposed, false); + assert.equal(removedFromRegistry, false); + assert.equal(wrapper.isAlive(), true); + assert.equal(wrapper.isRunning(), true, "the run stays marked until a frame settles it"); }); test("getRunningRpcSessions and getRunningRpcSessionIds export running sessions with their originating cwd", async () => { @@ -835,7 +839,7 @@ test("buildSessionSpawnArgs binds an explicit model on resume only (#277)", asyn -test("mcp list ack timeout recycles a child that accepts the frame but withholds its response", async (t) => { +test("mcp list ack timeout keeps the child and reports session_slow", async (t) => { const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); @@ -871,14 +875,15 @@ test("mcp list ack timeout recycles a child that accepts the frame but withholds pending, (err) => { assert.ok(err instanceof WebRpcError || err.name === "WebRpcError"); - assert.equal(err.code, "session_unresponsive"); + assert.equal(err.code, "session_slow"); return true; }, ); - assert.equal(disposed, true); - assert.equal(wrapper.isAlive(), false); - assert.equal(wrapper.isRunning(), false); + // Busy, not dead: only the stall watchdog may dispose a silent child. + assert.equal(disposed, false); + assert.equal(wrapper.isAlive(), true); + assert.equal(wrapper.isRunning(), false, "the in-flight flag was released for the next attempt"); }); test("mcp list ack timeout clears the waiter so a retry is not blocked as busy", async (t) => { @@ -905,17 +910,16 @@ test("mcp list ack timeout clears the waiter so a retry is not blocked as busy", const first = wrapper.getMcpList(); await Promise.resolve(); t.mock.timers.tick(30000); - await assert.rejects(first, { code: "session_unresponsive" }); + await assert.rejects(first, { code: "session_slow" }); - // The wedged wrapper must not report itself busy: without the bounded ack - // the finally block never ran and this second call failed with session_busy. - await assert.rejects( - () => wrapper.getMcpList(), - (err) => { - assert.equal(err.message, "Session is no longer running"); - return true; - }, - ); + // The busy wrapper must not report itself busy forever: without the bounded + // ack the finally block never ran and this second call failed with + // session_busy. It now retries and answers the same busy code. + const retry = wrapper.getMcpList(); + await Promise.resolve(); + t.mock.timers.tick(30000); + await assert.rejects(retry, { code: "session_slow" }); + assert.equal(wrapper.isAlive(), true); }); test("live snapshots restore quiet partial messages and tools, with ordered event metadata", async (t) => { @@ -3279,7 +3283,7 @@ test("an edit that times out with no uplink since dispatch answers host_offline assert.equal(session.isAlive(), true); }); -test("a prompt that times out after the host sent uplink traffic is recycled as before", async (t) => { +test("a prompt that times out after the host sent uplink traffic keeps the child and says maybeStarted", async (t) => { const { startRpcSession } = await import("./rpc-manager.ts"); const hub = await import("./hosts/hub.ts"); const { linkHost } = await import("./hosts/link-driver.test-helper.mjs"); @@ -3311,10 +3315,12 @@ test("a prompt that times out after the host sent uplink traffic is recycled as // A pong after dispatch: the link is alive, so omp itself is what went quiet. await link.post(); t.mock.timers.tick(29_000); - await assert.rejects(sending, (error) => error.code === "session_unresponsive"); + await assert.rejects(sending, (error) => error.code === "session_slow" && error.details?.maybeStarted === true); t.mock.timers.reset(); - assert.equal(kills.length > 0, true, "the wedged child is recycled"); - assert.equal(session.isAlive(), false); + // The link answered a pong, so the child is alive and the prompt may run: + // only a child silent for STALL_DESTROY_MS (5 min) is disposed. + assert.deepEqual(kills, [], "the busy child is not recycled"); + assert.equal(session.isAlive(), true); }); /** A wrapper whose host link starts down; `linkReturns()` brings it back. */ @@ -4096,3 +4102,134 @@ test("a delta for a message that already ended has no base", async (t) => { assert.equal(events.length, before); assert.deepEqual(filters().map((filter) => filter.messageUpdates), ["delta", "full"]); }); + +// ---------------------------------------------------------------- #325: timeouts keep the child + +test("a prompt ack timeout keeps the child alive and answers session_slow with maybeStarted", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const sent = []; + const { wrapper } = snapshotSession(t, async (command) => { + sent.push(command.type); + if (command.type === "prompt") throw new RpcCommandTimeoutError("prompt", 30_000); + return {}; + }, SnapshotWrapper, "slow-prompt"); + await assert.rejects( + wrapper.send({ type: "prompt", message: "hi" }), + (error) => error.code === "session_slow" && error.details?.maybeStarted === true, + ); + assert.deepEqual(sent, ["prompt"]); + assert.equal(wrapper.isAlive(), true, "a timeout is not a reason to recycle the child"); + assert.equal(wrapper.isRunning(), true, "the run stays marked until a frame or a successful get_state settles it"); +}); + +test("a get_state timeout keeps the child alive and reports session_slow without details", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const { wrapper } = snapshotSession(t, async () => { + throw new RpcCommandTimeoutError("get_state", 5_000); + }, SnapshotWrapper, "slow-state"); + await assert.rejects(wrapper.send({ type: "get_state" }), (error) => error.code === "session_slow" && error.details === undefined); + assert.equal(wrapper.isAlive(), true); +}); + +test("steer, follow-up and abort timeouts name what may already have happened", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const { wrapper } = snapshotSession(t, async (command) => { + throw new RpcCommandTimeoutError(command.type, 30_000); + }, SnapshotWrapper, "slow-controls"); + for (const type of ["steer", "follow_up"]) { + await assert.rejects(wrapper.send({ type, message: "x" }), (error) => error.details?.maybeStarted === true, type); + } + await assert.rejects(wrapper.send({ type: "abort" }), (error) => error.details?.abortUnconfirmed === true); + assert.equal(wrapper.isAlive(), true); +}); + +test("control commands are bounded; unbounded passthrough commands keep waiting", async (t) => { + const commands = []; + const { wrapper } = snapshotSession(t, async (command) => { + commands.push({ type: command.type, timeout: undefined }); + return {}; + }, SnapshotWrapper, "bounded"); + await wrapper.send({ type: "set_session_name", name: "Renamed" }); + await wrapper.send({ type: "login" }); + // The fake cannot see the timeout, so the source states it: every control + // call goes through sendControl, only the four long runners stay uncapped. + const source = await readFile(new URL("./rpc-manager.ts", import.meta.url), "utf8"); + assert.match(source, /await this\.sendControl\(\{ type: "set_session_name", name \}, GET_STATE_TIMEOUT_MS\)/); + assert.match(source, /UNBOUNDED_PASSTHROUGH_COMMANDS\.has\(type\)/); + assert.match(source, /"login",\s+\/\/ interactive login flow/); + assert.deepEqual(commands.map((command) => command.type), ["set_session_name", "login"]); +}); + +test("no more than 32 commands may wait on one child", async (t) => { + const resolvers = []; + const { wrapper } = snapshotSession(t, () => new Promise((resolve) => resolvers.push(resolve)), SnapshotWrapper, "pending-cap"); + const pending = Array.from({ length: 32 }, () => wrapper.send({ type: "get_state" })); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_busy" }); + for (const resolve of resolvers) resolve({}); + await Promise.all(pending); +}); + +// ---------------------------------------------------------------- #325: timeouts keep the child + +test("a prompt ack timeout keeps the child alive and answers session_slow with maybeStarted", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const sent = []; + const { wrapper } = snapshotSession(t, async (command) => { + sent.push(command.type); + if (command.type === "prompt") throw new RpcCommandTimeoutError("prompt", 30_000); + return {}; + }, SnapshotWrapper, "slow-prompt"); + await assert.rejects( + wrapper.send({ type: "prompt", message: "hi" }), + (error) => error.code === "session_slow" && error.details?.maybeStarted === true, + ); + assert.deepEqual(sent, ["prompt"]); + assert.equal(wrapper.isAlive(), true, "a timeout is not a reason to recycle the child"); + assert.equal(wrapper.isRunning(), true, "the run stays marked until a frame or a successful get_state settles it"); +}); + +test("a get_state timeout keeps the child alive and reports session_slow without details", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const { wrapper } = snapshotSession(t, async () => { + throw new RpcCommandTimeoutError("get_state", 5_000); + }, SnapshotWrapper, "slow-state"); + await assert.rejects(wrapper.send({ type: "get_state" }), (error) => error.code === "session_slow" && error.details === undefined); + assert.equal(wrapper.isAlive(), true); +}); +test("steer, follow-up and abort timeouts name what may already have happened", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const { wrapper } = snapshotSession(t, async (command) => { + throw new RpcCommandTimeoutError(command.type, 30_000); + }, SnapshotWrapper, "slow-controls"); + for (const type of ["steer", "follow_up"]) { + await assert.rejects(wrapper.send({ type, message: "x" }), (error) => error.details?.maybeStarted === true, type); + } + await assert.rejects(wrapper.send({ type: "abort" }), (error) => error.details?.abortUnconfirmed === true); + assert.equal(wrapper.isAlive(), true, "a timeout is not a reason to recycle the child"); +}); + +test("control commands are bounded; unbounded passthrough commands keep waiting", async (t) => { + const commands = []; + const { wrapper } = snapshotSession(t, async (command) => { + commands.push({ type: command.type }); + return {}; + }, SnapshotWrapper, "bounded"); + await wrapper.send({ type: "set_session_name", name: "Renamed" }); + await wrapper.send({ type: "login" }); + // The fake cannot see the timeout, so the source states it: every control + // call goes through sendControl, only the four long runners stay uncapped. + const source = await readFile(new URL("./rpc-manager.ts", import.meta.url), "utf8"); + assert.match(source, /await this\.sendControl\(\{ type: "set_session_name", name \}, GET_STATE_TIMEOUT_MS\)/); + assert.match(source, /UNBOUNDED_PASSTHROUGH_COMMANDS\.has\(type\)/); + assert.match(source, /"login",\s+\/\/ interactive login flow/); + assert.deepEqual(commands.map((command) => command.type), ["set_session_name", "login"]); +}); + +test("no more than 32 commands may wait on one child", async (t) => { + const resolvers = []; + const { wrapper } = snapshotSession(t, () => new Promise((resolve) => resolvers.push(resolve)), SnapshotWrapper, "pending-cap"); + const pending = Array.from({ length: 32 }, () => wrapper.send({ type: "get_state" })); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_busy" }); + for (const resolve of resolvers) resolve({}); + await Promise.all(pending); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 9436d4df2..2c5c9a1c0 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -27,6 +27,7 @@ import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "./ import { eventWithToolResultImageUrls } from "./media-cache"; import type { BashResultInfo, + ExtensionUiResponse, OmpModel, RpcAvailableSlashCommand, RpcSessionState, @@ -63,6 +64,22 @@ interface CompactionResultLike { tokensAfter?: number; } +/** + * Read a millisecond setting without turning a typo into "off": only a finite, + * non-negative number is accepted (`0` keeps its documented "disabled" meaning + * in both consumers). `5m`, `-1` or an empty value used to evaluate to 0 via + * `Number(...) || 0`, which silently disabled the very watchdog that rescues a + * wedged child. Such a value now keeps the default and warns once at startup. + */ +export function readNonNegativeMs(name: string, fallback: number): number { + const raw = process.env[name]; + if (raw === undefined) return fallback; + const parsed = raw.trim() === "" ? Number.NaN : Number(raw); + if (Number.isFinite(parsed) && parsed >= 0) return parsed; + console.warn(`[omp-web] ignoring invalid ${name}="${raw}" (expected milliseconds >= 0); using ${fallback}.`); + return fallback; +} + const IDLE_DESTROY_MS = 10 * 60 * 1000; /** * How long a session may sit with **no web UI attached** before its omp child is @@ -79,19 +96,39 @@ const IDLE_DESTROY_MS = 10 * 60 * 1000; * the idle backstop. Set `OMP_WEB_DISCONNECT_DESTROY_MS=0` to disable reaping * and fall back to IDLE_DESTROY_MS alone. */ -const DISCONNECT_DESTROY_MS = process.env.OMP_WEB_DISCONNECT_DESTROY_MS !== undefined - ? Math.max(0, Number(process.env.OMP_WEB_DISCONNECT_DESTROY_MS) || 0) - : 120_000; +const DISCONNECT_DESTROY_MS = readNonNegativeMs("OMP_WEB_DISCONNECT_DESTROY_MS", 120_000); +/** + * How long a child may go without any positive evidence of life (a frame or a + * successful command answer) before a *timed-out* command is allowed to + * dispose it. omp blocks its event loop for tens of seconds on large sessions, + * so a timeout alone only means "busy"; five minutes of complete silence on a + * child that then misses another answer means wedged. Set + * `OMP_WEB_STALL_DESTROY_MS=0` to disable the watchdog (a stalled child then + * lives until the disconnect reaper or process exit). + */ +const STALL_DESTROY_MS = readNonNegativeMs("OMP_WEB_STALL_DESTROY_MS", 5 * 60_000); +/** Refuse a new command while this many are already awaiting omp. Requests + * cannot pin the wrapper (and the child's stdin) without bound. */ +const MAX_PENDING_COMMANDS = 32; const READY_TIMEOUT_MS = 120_000; const MCP_LIST_TIMEOUT_MS = 15_000; +/** Bounds one request's wait for an answer. It says nothing about the child: + * omp blocks its event loop for tens of seconds on large sessions (a 2.8 MB + * transcript answered `get_state` after 49 s), so an expired wait means "busy", + * never "dead" — see `slowSessionError()`. */ const GET_STATE_TIMEOUT_MS = 5_000; /** Cap on the *acknowledgement* of a prompt frame — not on model execution. * omp acks a prompt as soon as it accepts it and the run then reports through - * events (agent_start/agent_end), so an ack that never arrives means the child - * is wedged: without this the API request (and the UI spinner behind it) would - * stay pending forever. Generous enough to cover slow local startup work the - * child does before acking. */ + * events (agent_start/agent_end), so without this bound the API request (and + * the UI spinner behind it) would stay pending for as long as omp is blocked. + * Generous enough to cover slow local startup work the child does before + * acking. */ const PROMPT_ACK_TIMEOUT_MS = 30_000; +/** Stable code for "omp did not answer this command in time". The session keeps + * running; clients answer with HTTP 503 and retry instead of treating the run + * as ended. */ +const SESSION_SLOW_CODE = "session_slow"; +const SESSION_SLOW_MESSAGE = "omp is busy and did not answer in time; the session keeps running."; /** Title generation is an LLM call on omp's side. */ const GENERATE_TITLE_TIMEOUT_MS = 60_000; const RENAME_POLL_INTERVAL_MS = 500; @@ -119,17 +156,46 @@ export class WebRpcError extends Error { /** `host_offline` only: "refused" when nothing was sent, "unknown" when the * link dropped after the command left, so it may still run on the host. */ readonly delivery?: "refused" | "unknown"; + /** Extra machine-readable facts the agent route forwards next to `code` + * (`maybeStarted`, `abortUnconfirmed`). */ + readonly details: Record | undefined; - constructor(message: string, code: string, delivery?: "refused" | "unknown") { + constructor(message: string, code: string, delivery?: "refused" | "unknown", details?: Record) { super(message); this.name = "WebRpcError"; this.code = code; if (delivery) this.delivery = delivery; + this.details = details; } } +const SESSION_SLOW_MAYBE_STARTED_MESSAGE = + "omp is busy and did not acknowledge the message in time; it may still be running. The session keeps running."; +const SESSION_SLOW_ABORT_UNCONFIRMED_MESSAGE = + "omp is busy and did not answer the abort in time; the abort is not confirmed and the session keeps running."; + +/** A command timeout means omp is busy, not dead. omp blocks its event loop + * for tens of seconds on large sessions, so a missing answer only ends this + * request's wait — the child, and any run it is executing, keeps going and + * keeps reporting through frames. Only the liveness watchdog + * (`destroyIfStalled`) may dispose a child with no evidence of life for + * `STALL_DESTROY_MS`; a mere timeout never does. Recycling a child here killed + * live runs and made omp record a `dispose` ("Generation stopped by user"). */ +function slowSessionError(details?: Record): WebRpcError { + return new WebRpcError( + details?.abortUnconfirmed + ? SESSION_SLOW_ABORT_UNCONFIRMED_MESSAGE + : details?.maybeStarted + ? SESSION_SLOW_MAYBE_STARTED_MESSAGE + : SESSION_SLOW_MESSAGE, + SESSION_SLOW_CODE, + undefined, + details, + ); +} + /** Shape check for an ask-dialog `answers` payload; omp validates the content. */ -function isAskAnswers(value: unknown): boolean { +export function isAskAnswers(value: unknown): boolean { return Array.isArray(value) && value.every((answer: unknown) => isRecord(answer) && typeof answer.id === "string" @@ -169,6 +235,9 @@ const PASSTHROUGH_COMMANDS = new Set([ "btw", "btw_cancel", "get_btw_history", + // Goal mode (`{type:"goal", op}`) has the same shape as omp's RPC frame and + // is the only way native clients reach it; every op answers `{goal, state}`. + "goal", ]); // Outlasts omp's cold prediction-daemon start (up to 3 × 30s start rounds plus a @@ -176,6 +245,21 @@ const PASSTHROUGH_COMMANDS = new Set([ // cannot pin the request forever. const PREDICT_WORD_TIMEOUT_MS = 125_000; +// Passthrough commands whose answer legitimately takes minutes and therefore +// stays uncapped, mirroring the explicit switch cases (compact, bash, +// branch/fork). `predict_word` has its own (generous) PREDICT_WORD_TIMEOUT_MS. +// Every other command — including the control commands that used to call +// `sendRpc` without a bound (set_model, set_fast_mode, set_slow_mode, +// get_session_stats, get_last_assistant_text, get_commands, +// new_session/switch_session) — goes through `sendControl`, so a wedged child +// answers `session_slow` instead of pinning the request forever. +const UNBOUNDED_PASSTHROUGH_COMMANDS = new Set([ + "login", // interactive login flow (browser/device code) + "btw", // LLM side question + "handoff", // starts a new session and may run model work + "export_html", // walks the whole transcript +]); + // Commands that can carry user-attached images to the model. All of them must // pass the same server-side per-image/count/aggregate validation before the // payload reaches omp — a client is free to POST any of them directly. @@ -443,6 +527,15 @@ export class AgentSessionWrapper { private reapTimer: ReturnType | null = null; private reapDeadline = 0; private lastActivityAt = 0; + /** Last frame the child sent. `silentForMs` reports from here: a command + * answer is not a frame, so polls never move this clock. */ + private lastFrameAt = 0; + /** Last positive evidence that the child's event loop is alive: a frame or a + * successful command answer (an `RpcCommandError` counts too — omp replied). + * Timed-out answers, polls and `send()` writes deliberately do not move it: + * `send()` only feeds the disconnect reaper. Read exclusively by the stall + * watchdog in the command-timeout branches. */ + private lastEvidenceAt = 0; /** In-flight `send()` calls: the reaper must never dispose the child out from * under a command that is still awaiting its response. */ private pendingCommands = 0; @@ -547,6 +640,8 @@ export class AgentSessionWrapper { this.host = host; this.launchAdvisor = launchAdvisor; this.fellBack = fellBack; + this.lastFrameAt = Date.now(); + this.lastEvidenceAt = this.lastFrameAt; } get sessionId(): string { @@ -576,6 +671,11 @@ export class AgentSessionWrapper { || this.pendingUiRequests.size > 0 || this.pendingHostTools.size > 0 || this.pendingHostUris.size > 0); } + /** Time since the child's last frame (epoch-ms clock started at spawn). */ + silentForMs(): number { + return Math.max(0, Date.now() - this.lastFrameAt); + } + /** Local history navigation is busy control work, not an interruptible model turn. */ isEditingHistory(): boolean { return this.historyEditInFlight; @@ -1160,6 +1260,10 @@ export class AgentSessionWrapper { // even when they arrive after a failed/timed-out edit. if (isSessionEditReply(frame)) return; this.resetIdleTimer(); + // Any frame proves the child's event loop is running (a `ready` frame is + // consumed by waitReady, so this covers runtime frames only). + this.lastFrameAt = Date.now(); + this.lastEvidenceAt = this.lastFrameAt; const event = frame.type === "available_commands_update" && Array.isArray(frame.commands) ? { ...frame, commands: (frame.commands as RpcAvailableSlashCommand[]).filter((command) => command.name !== SESSION_EDIT_COMMAND) } : frame; @@ -1439,13 +1543,52 @@ export class AgentSessionWrapper { clearTimeout(timer); this.uiExpiryTimers.delete(id); } + // Every settle path (answer, cancel, expiry, restart, destroy, new run) + // forgets the dialog; the repeat must stop with it. + } + + /** + * A pending dialog is settled (answered, cancelled, expired or its child is + * gone): forget it and retract the `input` notification it produced. + */ + private settlePendingUiRequest(id: string): boolean { + if (!this.pendingUiRequests.has(id)) return false; + this.forgetPendingUiRequest(id); + return true; } private clearPendingUiRequests(): void { this.dropServerUiRequests(); for (const timer of this.uiExpiryTimers.values()) clearTimeout(timer); this.uiExpiryTimers.clear(); - this.pendingUiRequests.clear(); + for (const id of [...this.pendingUiRequests.keys()]) this.settlePendingUiRequest(id); + } + + /** + * Answer a blocking dialog from a notification action. Uses the same + * validation and frame as the agent route's `extension_ui_response` command, + * and returns whether the request was still pending. + */ + answerExtensionUiRequest(id: string, response: ExtensionUiResponse): "answered" | "alreadySettled" { + const pending = this.pendingUiRequests.get(id); + if (!pending) return "alreadySettled"; + const pendingAsk = pending.method === "ask"; + // A pending ask accepts only its answers or a cancel; any other pending + // dialog accepts no answers. Anything else would drop it from reconnect + // replay while omp rejects the payload. + if (pendingAsk) { + if (!("cancelled" in response) && !isAskAnswers("answers" in response ? response.answers : undefined)) { + throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); + } + } else if ("answers" in response) { + throw new WebRpcError("This dialog does not take answers", "invalid_ask_answers"); + } + const wasPending = this.settlePendingUiRequest(id); + this.proc.sendFrame({ type: "extension_ui_response", id, ...response }); + // omp sends no cancel for an answered dialog; other tabs on this session + // would keep showing it, so settle it for them here. + if (wasPending) this.emit({ type: "extension_ui_request", id: `cancel:${id}`, method: "cancel", targetId: id }); + return "answered"; } /** Settle every server dialog as declined and close it in attached tabs. */ @@ -1476,7 +1619,8 @@ export class AgentSessionWrapper { const method = event.method as string; const id = event.id as string; if (method === "cancel") { - this.forgetPendingUiRequest(event.targetId as string); + const targetId = typeof event.targetId === "string" ? event.targetId : ""; + if (targetId) this.settlePendingUiRequest(targetId); return false; } // Only the “Allow tool: ” confirmation is covered. Other extension @@ -1493,7 +1637,7 @@ export class AgentSessionWrapper { const timeout = typeof event.timeout === "number" ? event.timeout : undefined; if (timeout && timeout > 0) { event.expiresAt = Date.now() + timeout; - const timer = setTimeout(() => this.forgetPendingUiRequest(id), timeout); + const timer = setTimeout(() => this.settlePendingUiRequest(id), timeout); timer.unref?.(); this.uiExpiryTimers.set(id, timer); } @@ -2006,7 +2150,9 @@ export class AgentSessionWrapper { // acks it would otherwise suspend this call forever — the `finally` below // would never run and the wrapper would keep reporting itself as busy // (later calls fail with session_busy) until unrelated traffic cleared - // the wedge. The 15s output wait above stays a separate concern. + // the wedge. The 15s output wait above stays a separate concern. An + // expired ack leaves the child alone: it is busy, and the run it may be + // executing keeps reporting through frames. await this.sendNativeMessageCommand({ type: "prompt", message: action === "list" ? "/mcp list" : `/mcp ${action}${name ? ` ${name}` : ""}` }, PROMPT_ACK_TIMEOUT_MS); const result = await output; if (action !== "list" && /^(?:Failed|Usage:|Server .* not found|Unknown)/m.test(result)) { @@ -2024,7 +2170,7 @@ export class AgentSessionWrapper { this.mcpListWaiter = null; waiter.reject( expired - ? new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive") + ? slowSessionError() : error instanceof Error ? error : new Error(String(error)), @@ -2032,10 +2178,13 @@ export class AgentSessionWrapper { } if (expired) { if (error instanceof RpcCommandTimeoutError && this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); - // Nothing on this child will ever resolve the waiter; recycle it like - // the prompt-ack timeout path so the next request gets a fresh child. - await this.destroyAndWait("session-unresponsive", true); - throw new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive"); + // Nothing on this child will ever resolve the waiter; the `finally` + // releases the in-flight flag so the next attempt is not reported as + // busy. The child itself stays unless it has been silent past + // STALL_DESTROY_MS — then the liveness watchdog disposes it; otherwise + // a later `/mcp list` simply retries. + await this.destroyIfStalled(); + throw slowSessionError(); } throw error; } finally { @@ -2141,7 +2290,94 @@ export class AgentSessionWrapper { } private async getStateWithTimeout(): Promise { - return this.proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS); + return this.sendRpc({ type: "get_state" }, GET_STATE_TIMEOUT_MS); + } + + /** + * Single command choke point for the wrapper. Every successful answer — and + * every `RpcCommandError`, because omp answered — is positive evidence that + * the child's event loop is alive, which is exactly what the stall watchdog + * needs. Timeouts are not evidence and deliberately do not touch the clock. + */ + private async sendRpc( + command: { type: string; [key: string]: unknown }, + timeoutMs?: number, + onReply?: (success: boolean) => void, + ): Promise { + try { + const result = await this.proc.sendCommand(command, timeoutMs, onReply); + this.lastEvidenceAt = Date.now(); + return result; + } catch (error) { + if (error instanceof RpcCommandError) this.lastEvidenceAt = Date.now(); + throw error; + } + } + + /** + * Bounded command for the control paths: a timeout answers `session_slow` + * instead of pinning the request forever, and only the liveness watchdog may + * dispose the child. A child the watchdog *did* dispose never ran the frame, + * so the error then carries no `details` and clients fall back to their + * normal rollback (the text stays recoverable). + */ + private async sendControl( + command: { type: string; [key: string]: unknown }, + timeoutMs: number, + timeoutDetails?: Record, + onReply?: (success: boolean) => void, + ): Promise { + try { + return await this.sendRpc(command, timeoutMs, onReply); + } catch (error) { + if (!(error instanceof RpcCommandTimeoutError)) throw error; + if (this.destroyIfStalled()) throw slowSessionError(); + throw slowSessionError(timeoutDetails); + } + } + + /** + * Liveness watchdog, called only from a command-timeout branch. A timeout + * normally means "busy" (omp blocks its loop for tens of seconds); it means + * "wedged" only when the child has produced no frame and answered no command + * for `STALL_DESTROY_MS`. That child is disposed through the regular exit + * path: the exited-session map gets a `detail: "stalled"` record which + * `GET /api/sessions/[id]/state` serves, while `GET /api/agent/[id]` only + * sees `{running:false}` — exactly like a process crash. + * + * Returns whether the child was disposed. + */ + private destroyIfStalled(): boolean { + if (STALL_DESTROY_MS <= 0 || !this.isAlive()) return false; + if (Date.now() - this.lastEvidenceAt < STALL_DESTROY_MS) return false; + const minutes = Math.round(STALL_DESTROY_MS / 60_000); + const idleFor = Math.round((Date.now() - this.lastEvidenceAt) / 1000); + console.warn(`[omp-web] omp child for session ${this._sessionId || "(new)"} produced no evidence of life for ${idleFor}s (>= ${minutes} min); disposing the stalled child.`); + if (this._sessionId) { + // Same record shape as handleProcessExit so every exited-session consumer + // (badges, resume prompts) treats it as the child being gone. + getExitedMap().set(this._sessionId, { + id: this._sessionId, + cwd: this.cwd, + ...(this.host.id === LOCAL_HOST_ID ? {} : { hostId: this.host.id }), + at: Date.now(), + code: null, + signal: null, + detail: "stalled", + }); + } + this.emit({ + type: "notice", + level: "error", + message: "The omp process for this session stopped responding and was stopped; the next message starts it again. The run may have been interrupted.", + }); + // Let a client mid-stream stop spinning now, like a process exit would. + if (this.streaming || this.promptRunning) this.emit({ type: "agent_end", isTerminal: true, messages: [] }); + if (this.streaming || this.promptRunning || this.unsettled) { + this.publishNotifications({ type: "process_exit", detail: "stalled" }); + } + this.destroy(); + return true; } /** After branch/new_session/switch_session the child is on a different @@ -2391,6 +2627,9 @@ export class AgentSessionWrapper { } } finally { this.restarting = false; + // The replacement answered its handshake: the stall clock starts here, so + // the disposed old child's silence never counts against the new one. + this.lastEvidenceAt = Date.now(); } notifyRunningChange(); } @@ -2466,8 +2705,15 @@ export class AgentSessionWrapper { }; } - /** `origin`: the command a caller submitted through `send`; marked once its native message write begins. */ - private async sendNativeMessageCommand(command: { type: string; [key: string]: unknown }, timeoutMs?: number, origin?: object): Promise { + /** `origin`: the command a caller submitted through `send`; marked once its native message write begins. + * `timeoutDetails`: a timeout means the frame may already be in omp's stdin, so the error names what may + * already have happened instead of leaving clients to roll back and resend. */ + private async sendNativeMessageCommand( + command: { type: string; [key: string]: unknown }, + timeoutMs?: number, + origin?: object, + timeoutDetails?: Record, + ): Promise { const message = IMAGE_BEARING_COMMANDS.has(command.type); const proof = message && !this.messageReplacement && !this.hasPendingMessageCommands() ? watchReplacement(this, command, this.nativeQueuedMessages, this.messageCommandGeneration, false, @@ -2481,7 +2727,7 @@ export class AgentSessionWrapper { const generation = this.messageCommandGeneration; try { const replacement = proof ?? this.messageReplacement; - const result = await this.proc.sendCommand(command, timeoutMs, message && replacement + const result = await this.sendRpc(command, timeoutMs, message && replacement ? (_ok, id) => replacement.replied(proof ? command : origin ?? command, id) : undefined); if (message && isRecord(result) && result.agentInvoked === false) { @@ -2496,6 +2742,15 @@ export class AgentSessionWrapper { } catch (error) { proof?.stop(); if (message && error instanceof RpcCommandError) this.confirmMessageCommandGeneration(generation); + // Only callers that name the uncertainty translate the timeout here; the + // prompt path keeps the raw error because its own catch owns the run flags. + if (timeoutDetails && error instanceof RpcCommandTimeoutError) { + if (this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); + // A child the watchdog disposed never ran the frame: report a definite + // failure so the client recovers the text. Otherwise the frame sits in + // omp's stdin and the message may still be delivered. + throw this.destroyIfStalled() ? slowSessionError() : slowSessionError(timeoutDetails); + } throw error; } finally { if (message) this.pendingMessageCommands -= 1; @@ -2507,6 +2762,9 @@ export class AgentSessionWrapper { if (this.restarting) throw new WebRpcError(RESTARTING_MESSAGE, "session_restarting"); if (this.mcpListInFlight) throw new WebRpcError("MCP management is in progress. Try again when it finishes.", "session_busy"); if (!this.isAlive()) throw new Error("Session is no longer running"); + if (this.pendingCommands >= MAX_PENDING_COMMANDS) { + throw new WebRpcError("Too many commands are in flight for this session", "session_busy"); + } if (this.hostDown() || this.oldChildExiting) throw this.hostOfflineError("refused"); if (typeof command.type === "string" && command.type.startsWith("abort")) { console.info("[omp-web] cancellation-command", JSON.stringify({ sessionId: this._sessionId, type: command.type, at: new Date().toISOString() })); @@ -2583,20 +2841,36 @@ export class AgentSessionWrapper { } if (ack?.agentInvoked === false) return ack; } catch (error) { + if (error instanceof RpcCommandTimeoutError) { + if (this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); + // Busy, not dead: omp may simply be blocked inside the run this + // frame started, and the frame may already sit in its stdin. Never + // recycle the child (that killed the run and made omp record a + // `dispose`) and never declare the prompt "not started": keep the + // optimistic run state and let agent_start/agent_end — or the + // deadline checked in buildWebState — settle it. The client gets + // `maybeStarted` and keeps its send lock until a frame or a + // successful get_state arrives. A child with no evidence of life + // for STALL_DESTROY_MS is the one exception (see watchdog). + const stalled = this.destroyIfStalled(); + if (!stalled) { + this.awaitingAgentStart = true; + this.awaitingAgentStartDeadline = Date.now() + AWAITING_AGENT_START_TIMEOUT_MS; + } + if (!streamingBehavior) notifyRunningChange(); + // A child the watchdog disposed never ran the frame: report a + // definite failure so the client rolls back and recovers the text + // instead of waiting for a run that cannot exist. Otherwise the + // frame sits in omp's stdin and the message may still run. + throw stalled ? slowSessionError() : slowSessionError({ maybeStarted: true }); + } this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.streaming = false; this.clearLiveSnapshots(); notifyRunningChange(); - if (error instanceof RpcCommandTimeoutError) { - if (this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); - // The child took the frame but never acked it, so nothing will ever - // report this run: recycle the unacknowledged prompt. A read-only - // get_state timeout deliberately does not take this destructive path. - await this.destroyAndWait("session-unresponsive", true); - throw new WebRpcError("The OMP session stopped responding and was reset.", "session_unresponsive"); - } + throw error; } finally { if (!streamingBehavior) { @@ -2612,11 +2886,14 @@ export class AgentSessionWrapper { // there is no live turn to steer anyway, so it joins the follow-up // queue like a prompt would. if (type === "steer" && this.bashRunning && !this.streaming) return await this.queueWhileShellRunning(command); + // The frame is written before the ack is awaited: a timeout means it + // may already be in omp's stdin, so the message may still be delivered. + // Reporting "not sent" made clients roll back and resend it twice. await this.sendNativeMessageCommand({ type, message: command.message as string, ...(toImageContents(command.images) ? { images: toImageContents(command.images) } : {}), - }, undefined, command); + }, PROMPT_ACK_TIMEOUT_MS, command, { maybeStarted: true }); return null; } @@ -2624,7 +2901,7 @@ export class AgentSessionWrapper { case "promote_queued_message": { // Queue mutations are synchronous control operations, like get_state. // Expiry must not abort unrelated work or replay a possibly applied mutation. - const result = await this.proc.sendCommand(command as { type: string }, GET_STATE_TIMEOUT_MS); + const result = await this.sendControl(command as { type: string }, GET_STATE_TIMEOUT_MS); return result ?? null; } @@ -2635,7 +2912,10 @@ export class AgentSessionWrapper { this.responseObserved = false; this.responseRunActive = false; const result = await this.withFinalRunningNotification(async () => { - const response: unknown = await this.proc.sendCommand({ type }); + // The abort frame may already have reached omp without omp managing + // to confirm it: never report this as done, and keep the run flags + // (the run may still be live and reporting frames). + const response = await this.sendControl({ type }, PROMPT_ACK_TIMEOUT_MS, { abortUnconfirmed: true }); // If the prompt was aborted before the agent loop started, no // agent_end will arrive to clear the flag; the streaming flag still // tracks a live turn that ends with its own agent_end. @@ -2654,22 +2934,24 @@ export class AgentSessionWrapper { } case "get_state": { + // The 5 s bound belongs to this request only. A busy child (omp blocks + // its loop for tens of seconds on big sessions) must keep running and + // keep the run it is executing; clients get `session_slow` and retry + // the poll. Only the liveness watchdog may dispose a child that has + // been silent past STALL_DESTROY_MS. try { - const state = await this.proc.sendCommand({ type: "get_state" }, GET_STATE_TIMEOUT_MS); + const state = await this.sendControl({ type: "get_state" }, GET_STATE_TIMEOUT_MS); return this.buildWebState(state); } catch (error) { - if (error instanceof RpcCommandTimeoutError) { - // This is only an observer poll. A busy event loop or delayed RPC - // response is not authority to stop generation or a pending tool. + if (error instanceof WebRpcError && error.code === SESSION_SLOW_CODE) { console.warn("[omp-web] status-query-timeout", JSON.stringify({ sessionId: this._sessionId, timeoutMs: GET_STATE_TIMEOUT_MS, running: this.isRunning(), action: "preserved", at: new Date().toISOString() })); - throw new WebRpcError("The OMP status query timed out. The session was left running; retry shortly.", "session_state_timeout"); } throw error; } } case "get_skill_diagnostics": { - const result = await this.proc.sendCommand({ type: "get_skill_diagnostics" }, GET_STATE_TIMEOUT_MS); + const result = await this.sendControl({ type: "get_skill_diagnostics" }, GET_STATE_TIMEOUT_MS); return this.requireSkillDiagnostics(result); } @@ -2677,7 +2959,7 @@ export class AgentSessionWrapper { if (typeof command.enabled !== "boolean") { throw new WebRpcError("enabled must be a boolean", "invalid_skill_startup_diagnostics"); } - const result = await this.proc.sendCommand({ + const result = await this.sendControl({ type: "set_skill_startup_diagnostics", enabled: command.enabled, }, GET_STATE_TIMEOUT_MS); @@ -2686,7 +2968,7 @@ export class AgentSessionWrapper { case "set_model": { const { provider, modelId } = command as { provider: string; modelId: string }; - const model = await this.proc.sendCommand({ type: "set_model", provider, modelId }); + const model = await this.sendControl({ type: "set_model", provider, modelId }, GET_STATE_TIMEOUT_MS); invalidateModelsCache(); this.invalidateSessionLists(); return { id: model.id, provider: model.provider }; @@ -2694,14 +2976,14 @@ export class AgentSessionWrapper { case "set_fast_mode": { const enabled = command.enabled === true; - const result = await this.proc.sendCommand<{ enabled?: boolean; active?: boolean }>({ type: "set_fast_mode", enabled }); + const result = await this.sendControl<{ enabled?: boolean; active?: boolean }>({ type: "set_fast_mode", enabled }, GET_STATE_TIMEOUT_MS); this.fastModeEnabled = result?.enabled ?? enabled; return { enabled: this.fastModeEnabled, active: result?.active ?? false }; } case "set_slow_mode": { const enabled = command.enabled === true; - const result = await this.proc.sendCommand<{ enabled?: boolean }>({ type: "set_slow_mode", enabled }); + const result = await this.sendControl<{ enabled?: boolean }>({ type: "set_slow_mode", enabled }, GET_STATE_TIMEOUT_MS); return { enabled: result?.enabled ?? enabled }; } @@ -2715,7 +2997,7 @@ export class AgentSessionWrapper { if (this.bashRunning) { throw new Error("Cannot fork while a shell command is running"); } - const result = await this.proc.sendCommand<{ text: string; cancelled: boolean }>({ + const result = await this.sendRpc<{ text: string; cancelled: boolean }>({ type: "branch", entryId: command.entryId as string, }); @@ -2727,7 +3009,10 @@ export class AgentSessionWrapper { case "new_session": case "switch_session": { - const result = await this.proc.sendCommand<{ cancelled: boolean }>(command as { type: string }); + // Switching writes a session file before answering, so it gets the + // generous prompt-ack bound instead of the 5 s poll bound — but it is + // still bounded: a wedged child must not pin the request forever. + const result = await this.sendControl<{ cancelled: boolean }>(command as { type: string }, PROMPT_ACK_TIMEOUT_MS); if (!result.cancelled) { const newSessionId = await this.refreshIdentityAfterSessionChange(); return { cancelled: false, newSessionId }; @@ -2742,7 +3027,7 @@ export class AgentSessionWrapper { this.streamSequence += 1; notifyRunningChange(); try { - const result = await this.proc.sendCommand({ + const result = await this.sendRpc({ type: "compact", ...(command.customInstructions ? { customInstructions: command.customInstructions } : {}), }); @@ -2761,32 +3046,32 @@ export class AgentSessionWrapper { case "abort_compaction": // No dedicated RPC command; a plain abort cancels the in-flight turn // including compaction work. - await this.withFinalRunningNotification(() => this.proc.sendCommand({ type: "abort" })); + await this.withFinalRunningNotification(() => this.sendControl({ type: "abort" }, PROMPT_ACK_TIMEOUT_MS, { abortUnconfirmed: true })); return null; case "set_session_name": { const name = (command.name as string | undefined)?.trim(); if (!name) throw new Error("Session name cannot be empty"); - await this.proc.sendCommand({ type: "set_session_name", name }); + await this.sendControl({ type: "set_session_name", name }, GET_STATE_TIMEOUT_MS); this._sessionName = name; this.invalidateSessionLists(); return null; } case "get_session_stats": { - const stats = await this.proc.sendCommand>({ type: "get_session_stats" }); + const stats = await this.sendControl>({ type: "get_session_stats" }, GET_STATE_TIMEOUT_MS); return { ...stats, sessionName: this._sessionName }; } case "get_last_assistant_text": { - const data = await this.proc.sendCommand<{ text: string | null }>({ type: "get_last_assistant_text" }); + const data = await this.sendControl<{ text: string | null }>({ type: "get_last_assistant_text" }, GET_STATE_TIMEOUT_MS); return { text: data.text ?? "" }; } case "get_commands": { - const data = await this.proc.sendCommand<{ commands: RpcAvailableSlashCommand[] }>({ + const data = await this.sendControl<{ commands: RpcAvailableSlashCommand[] }>({ type: "get_available_commands", - }); + }, GET_STATE_TIMEOUT_MS); return { ...data, commands: data.commands.filter((command) => command.name !== SESSION_EDIT_COMMAND) }; } @@ -2803,8 +3088,9 @@ export class AgentSessionWrapper { if (("answers" in rest || pendingAsk) && !isAskAnswers(rest.answers) && !(pendingAsk && rest.cancelled === true)) { throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); } - const wasPending = this.pendingUiRequests.has(id); - this.forgetPendingUiRequest(id); + // Forgets the pending dialog and retracts its notification for other + // tabs/devices; the cancel frame below settles it in other tabs. + const wasPending = this.settlePendingUiRequest(id); const serverRequest = this.serverUiRequests.get(id); if (serverRequest) { this.serverUiRequests.delete(id); @@ -2839,7 +3125,7 @@ export class AgentSessionWrapper { // `isStreaming`. Read it then: an agent_end in the same batch is // applied before this await resumes. let deferred = this.streaming; - const result = await this.proc.sendCommand({ type: "bash", command: command.command as string }, undefined, () => { deferred = this.streaming; }); + const result = await this.sendRpc({ type: "bash", command: command.command as string }, undefined, () => { deferred = this.streaming; }); return { ...result, deferred }; } finally { this.bashRunning = false; @@ -2873,7 +3159,7 @@ export class AgentSessionWrapper { return null; } // Applied as the successful reply is read, before a call in the same host-link batch is routed. - await this.proc.sendCommand({ type: "set_host_tools", tools: merged }, undefined, (success) => { + await this.sendControl({ type: "set_host_tools", tools: merged }, GET_STATE_TIMEOUT_MS, undefined, (success) => { if (!success) return; this.hostToolNames = new Set(merged.map((t) => t.name as string)); this.registeredHostTools = valid.filter((tool) => !AGENT_TOOL_NAMES.has(tool.name as string)); @@ -2910,7 +3196,7 @@ export class AgentSessionWrapper { this.registeredHostUriSchemes = schemes; return null; } - await this.proc.sendCommand({ type: "set_host_uri_schemes", schemes }, undefined, (success) => { + await this.sendControl({ type: "set_host_uri_schemes", schemes }, GET_STATE_TIMEOUT_MS, undefined, (success) => { if (!success) return; this.registeredHostUriSchemes = schemes; this.hostUriSchemes = new Map(); @@ -2936,11 +3222,24 @@ export class AgentSessionWrapper { this.responseRunActive = false; this.streamSequence += 1; } - const result: unknown = await this.sendNativeMessageCommand( - command as { type: string }, - type === "predict_word" ? PREDICT_WORD_TIMEOUT_MS : undefined, - command, - ); + const timeoutMs = type === "predict_word" + ? PREDICT_WORD_TIMEOUT_MS + : UNBOUNDED_PASSTHROUGH_COMMANDS.has(type) + ? undefined + : type.startsWith("abort") + ? PROMPT_ACK_TIMEOUT_MS + : GET_STATE_TIMEOUT_MS; + // `abort_and_prompt` writes the frame before the ack: a timeout means + // the abort may already have landed and the new prompt may already be + // running, so it must not be reported as "not sent". + const timeoutDetails = type === "abort_and_prompt" ? { maybeStarted: true } : undefined; + const result: unknown = timeoutMs === undefined + ? await this.sendRpc(command as { type: string }) + // A message-bearing passthrough (`abort_and_prompt`) keeps the native + // write bookkeeping the replacement watcher depends on. + : IMAGE_BEARING_COMMANDS.has(type) + ? await this.sendNativeMessageCommand(command as { type: string }, timeoutMs, command, timeoutDetails) + : await this.sendControl(command as { type: string }, timeoutMs, timeoutDetails); if (type === "set_thinking_level") this.invalidateSessionLists(); return result ?? null; } @@ -2962,11 +3261,13 @@ export class AgentSessionWrapper { */ private async queueWhileShellRunning(command: Record): Promise { const images = toImageContents(command.images); + // Same rule as `steer`: the follow_up frame reaches omp's stdin before the + // ack does, so a timeout may mean the message is already queued. await this.sendNativeMessageCommand({ type: "follow_up", message: command.message as string, ...(images ? { images } : {}), - }, undefined, command); + }, PROMPT_ACK_TIMEOUT_MS, command, { maybeStarted: true }); return { queued: true, queue: "followUp", reason: "shellRunning" }; } @@ -3123,6 +3424,18 @@ function getLocks(): Map Date: Mon, 9 Nov 2026 13:06:29 +0100 Subject: [PATCH 2/5] fix(rpc): read the state body once, keep uncertain prompts sent Review follow-ups for the command-timeout contract. - hooks/useAgentSession.ts: the 503 busy branch read `stateRes.json()` a second time after the request had already parsed it, so the read threw and a busy chat became an HTTP 503 load failure. The code now comes from the parsed body. Covered by opening a chat through the hook against a real Response (a second read throws there). - lib/message-outbox.ts: `refused` now honours the wrapper's explicit `maybeStarted` evidence, so a `session_slow` ack timeout (HTTP 400) fails as possibly-sent instead of "Not sent" with a resend offer. - lib/rpc-manager.ts: `destroyIfStalled` stops the child with `stopShared` instead of only dropping this web app's membership, so the "was stopped" claim is true for a daemon-owned child. - lib/rpc-manager.ts: a timed-out new_session/switch_session fences commands until a state read reconciles the identity, instead of leaving a stale wrapper identity that a later command could act through. - Routes answer the dead state (not `503 alive:true`) when the watchdog disposed the child, and the sessions-state route includes its stalled exit record. - Hook Slow-mode consumers read `alive` (with `running` as the fallback for older servers), so an idle live child keeps its session-scoped support instead of falling back to the catalog. - Dropped unrelated payloads: goal types/passthrough, the notification-answer helpers, the ownership helper, the unhandled-rejection policy change, reminder i18n strings, the `?systemPrompt=0` option, and the `RunAgentCommandOptions` refactor. - Tests: the duplicated block is gone and the source-string assertion is replaced by a transport-boundary one (the deadline `sendCommand` receives). New cases cover the stall watchdog's `stopShared`, the identity fence, the outbox `maybeStarted` classification and the busy chat hydration. --- app/api/agent/[id]/route.ts | 16 +-- app/api/sessions/[id]/state/route.ts | 7 ++ hooks/useAgentSession.rpc.test.mjs | 40 ++++++- hooks/useAgentSession.ts | 46 ++++---- instrumentation.node.ts | 40 ++----- lib/agent-client.ts | 3 +- lib/agent-command.ts | 8 +- lib/i18n/locales/en.json | 5 - lib/i18n/locales/ja.json | 5 - lib/i18n/locales/zh-CN.json | 5 - lib/instrumentation-crash-policy.test.mjs | 15 --- lib/message-outbox.test.mjs | 29 +++++ lib/message-outbox.ts | 9 +- lib/pi-types.ts | 37 +----- lib/rpc-manager.test.mjs | 114 ++++++++---------- lib/rpc-manager.ts | 134 +++++++++++----------- 16 files changed, 233 insertions(+), 280 deletions(-) diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index 5b2b73656..0ff1972af 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -37,13 +37,10 @@ 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); @@ -51,13 +48,7 @@ export async function GET( return Response.json({ running: false, alive: false }); } try { - // 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 }), - }); + const state = await session.send({ type: "get_state" }); return Response.json({ running: session.isRunning(), alive: true, state }); } catch (error) { // omp being slow is not the run ending: answer 503 so clients retry the @@ -65,6 +56,9 @@ export async function GET( // this tree raises (`session_slow`) and 0.6.0's own // `session_state_timeout` mean the same thing to a client. if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { + // The liveness watchdog disposes a child that stayed silent past its + // threshold; that child is gone, so the busy answer would be a lie. + if (!session.isAlive()) return Response.json({ running: false, alive: false }); return Response.json( { error: error.message, diff --git a/app/api/sessions/[id]/state/route.ts b/app/api/sessions/[id]/state/route.ts index ef2a97af2..772ecab66 100644 --- a/app/api/sessions/[id]/state/route.ts +++ b/app/api/sessions/[id]/state/route.ts @@ -34,6 +34,13 @@ async function sessionState(id: string): Promise { // this tree raises (`session_slow`) and 0.6.0's own // `session_state_timeout` mean the same thing to a client. if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { + // The liveness watchdog disposes a child that stayed silent past its + // threshold; that child is gone, so the busy answer would be a lie. + // Its `detail: "stalled"` record answers like any other exit. + if (!rpc.isAlive()) { + const exited = getExitedRpcSession(id); + return Response.json({ running: false, alive: false, ...(exited ? { exited } : {}) }); + } return Response.json( { error: error.message, diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 8d67c16c3..b83ffcd27 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -190,7 +190,10 @@ async function fetchStub(url, init = {}) { for (let i = 0; i < world.holds.length; i++) { if (world.holds[i].match(method, u, body)) { const h = world.holds.splice(i, 1)[0]; - const { status = 200, value } = await h.produce(); + const produced = await h.produce(); + // A hold may hand back a real Response (a body that can be read once). + if (produced.response) return produced.response; + const { status = 200, value } = produced; return jsonResponse(status, value); } } @@ -1786,6 +1789,41 @@ test("a failed transcript reload is retried instead of being classified as an em assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), []); }); +test("opening a chat whose state read answers 503 session_slow keeps the transcript and shows the run, not a load failure", async () => { + resetWorld(); + const sid = "busy-open"; + primeSession(sid, [userMsg("u0", "saved history")]); + // A real Response: its body can be read exactly once, so a second read (the + // bug that turned this path into an HTTP 503 load failure) throws here. + world.holds.push({ + match: (method, url) => method === "GET" && url === `/api/sessions/${sid}/state`, + produce: async () => ({ + response: Response.json( + { running: true, alive: true, code: "session_slow", error: "omp is busy", silentForMs: 12_000 }, + { status: 503 }, + ), + }), + }); + const w = await mountSession(sid); + assert.equal(w.latest.loading, false); + assert.equal(w.latest.error, null, "a busy child is not a failed load"); + assert.ok(w.latest.messages.some((m) => m.role === "user" && m.content === "saved history"), "the on-disk transcript stays"); + assert.equal(w.latest.agentRunning, true, "the run stays marked so the reconcile poll settles it"); + assert.ok(lastEs(), "the observer stream attaches to receive the completion frames"); +}); + +test("a 503 state answer without a busy code stays a load failure", async () => { + resetWorld(); + const sid = "broken-open"; + primeSession(sid, [userMsg("u0", "saved history")]); + world.holds.push({ + match: (method, url) => method === "GET" && url === `/api/sessions/${sid}/state`, + produce: async () => ({ status: 503, value: { error: "Host is offline", hostOffline: true } }), + }); + const w = await mountSession(sid); + assert.equal(w.latest.agentRunning, false); +}); + for (const recovered of ["answer", "empty", "absent wrapper"]) { test(`a failed state read stays retryable until recovery confirms ${recovered}`, async () => { resetWorld(); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index b86ac9270..9ba9fc574 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -215,17 +215,6 @@ function currentRunAssistant(context: SessionData["context"], previousEntryIds: } } return null; -/** A state GET answers 503 when omp is alive but its event loop is blocked by - * a large session (`session_slow`, and 0.6.0's own `session_state_timeout`). - * That is "still running, retry later" — never a load failure. */ -async function isBusySessionResponse(res: Response): Promise { - if (res.status !== 503) return false; - try { - const body = await res.json() as { code?: unknown }; - return body?.code === "session_slow" || body?.code === "session_state_timeout"; - } catch { - return false; - } } export interface UseAgentSessionOptions { @@ -1005,7 +994,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { try { const res = await fetch(`/api/sessions/${encodeURIComponent(sid)}/state`); if (!res.ok) return; - const agentState = await res.json() as { running: boolean; state?: AgentStateResponse }; + const agentState = await res.json() as { running: boolean; alive?: boolean; state?: AgentStateResponse }; if (!hookAliveRef.current || sessionIdRef.current !== sid) return; applySkillDiagnosticsSnapshot(skillDiagnosticsRevision, agentState.state?.skillDiagnostics); const applied = applyAuthoritativeModel(toThinkingModelMeta(agentState.state?.model), token); @@ -1020,8 +1009,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setFastModeEnabled(agentState.state.fastModeEnabled); } setFastModeActive(agentState.state?.fastModeActive); - // No omp process: back to the catalog fallback. - setSlowModeSupported(agentState.running ? (agentState.state?.slowModeSupported ?? false) : undefined); + // No omp process: back to the catalog fallback. `alive`, not `running`: + // an idle live child still knows whether this session's model supports + // Slow mode, and reading it as absent showed an enabled setting as + // disabled and sent the wrong toggle value. An older server/daemon + // answers without `alive`, where `running` is the only liveness signal. + setSlowModeSupported((agentState.alive ?? agentState.running) ? (agentState.state?.slowModeSupported ?? false) : undefined); setSlowModeEnabled(agentState.state?.slowModeEnabled ?? false); setSlowModeScope(agentState.state?.slowModeScope); setUsageLimit(agentState.state?.usageLimit); @@ -1064,7 +1057,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { queueRevision: ++queueSeqRef.current, skillDiagnosticsRevision: ++skillDiagnosticsSeqRef.current, response: fetch(`/api/sessions/${encodeURIComponent(sid)}/state`).then(async (stateRes) => { - const agentState = await stateRes.json().catch(() => ({})) as { running: boolean; state?: AgentStateResponse; exited?: ExitedRpcSession; outbox?: OutboxEntry[]; outboxScope?: string; outboxSettledIds?: string[] }; + const agentState = await stateRes.json().catch(() => ({})) as { running: boolean; alive?: boolean; state?: AgentStateResponse; code?: unknown; exited?: ExitedRpcSession; outbox?: OutboxEntry[]; outboxScope?: string; outboxSettledIds?: string[] }; if (hookAliveRef.current && sessionIdRef.current === sid && contextRequestSeqRef.current === requestSeq && promptRunIdRef.current === requestRun && (fenceRunId === undefined || promptRunIdRef.current === fenceRunId)) { if (typeof agentState.outboxScope === "string") rememberOutboxScope(agentState.outboxScope); @@ -1133,8 +1126,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (!stateRes.ok) { // A busy child (503 `session_slow` / `session_state_timeout`) is not // a failed load: the transcript above is the on-disk copy, the run - // keeps going and the state is merely unknown right now. - if (await isBusySessionResponse(stateRes)) { + // keeps going and the state is merely unknown right now. The code + // comes from the body already parsed above — a Response body can be + // read only once, and re-reading it threw, turning the busy path into + // an HTTP 503 load failure. + if (stateRes.status === 503 && (agentState.code === "session_slow" || agentState.code === "session_state_timeout")) { if (!hookAliveRef.current || sessionIdRef.current !== sid || contextRequestSeqRef.current !== requestSeq || promptRunIdRef.current !== requestRun) { return null; @@ -1166,7 +1162,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (modelApplied && liveState.thinkingLevel !== undefined) setThinkingLevel(normalizeThinkingLevel(liveState.thinkingLevel)); if (liveState.fastModeEnabled !== undefined) setFastModeEnabled(liveState.fastModeEnabled); setFastModeActive(liveState.fastModeActive); - setSlowModeSupported(agentState.running ? (liveState.slowModeSupported ?? false) : undefined); + // `alive`, not `running`: an idle live child still knows its model's Slow support. + setSlowModeSupported((agentState.alive ?? agentState.running) ? (liveState.slowModeSupported ?? false) : undefined); setSlowModeEnabled(liveState.slowModeEnabled ?? false); setSlowModeScope(liveState.slowModeScope); setUsageLimit(liveState.usageLimit); @@ -1179,7 +1176,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (liveState.extensionWidgets !== undefined) setExtensionWidgets(liveState.extensionWidgets ?? []); if (liveState.todoPhases !== undefined) setTodoPhases(liveState.todoPhases ?? []); applyQueueStateSnapshot(queueRevision, liveState.queuedMessages); - } else if (!agentState.running) { + } else if (!(agentState.alive ?? agentState.running)) { setSlowModeSupported(undefined); applyQueueStateSnapshot(queueRevision, null); } @@ -1301,14 +1298,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { ...(advisorEnabled ? { advisor: true } : {}), }), }); - const body = await res.json().catch(() => ({})) as { sessionId?: unknown; error?: string; code?: string; hostOffline?: boolean; delivery?: string }; + const body = await res.json().catch(() => ({})) as { sessionId?: unknown; error?: string; code?: string; hostOffline?: boolean; delivery?: string; maybeStarted?: boolean }; const offline = res.status === 503 && body.hostOffline === true; - if (!res.ok && !offline) throw new Error(body.error || body.code ? formatApiError(body) : `HTTP ${res.status}`); + // A command timeout keeps the spawned child (HTTP 400 `session_slow` with + // its id): the preset may already be applied and a prompt it carried may + // already run, so a retry must adopt it instead of spawning a second one. + const slow = body.code === "session_slow"; + if (!res.ok && !offline && !slow) throw new Error(body.error || body.code ? formatApiError(body) : `HTTP ${res.status}`); // A host that dropped after the spawn keeps the session (503 with its id): // adopt it, so a retry sends there instead of starting a second session. const realId = typeof body.sessionId === "string" && body.sessionId ? body.sessionId : null; if (!realId) { if (offline) throw new HostOfflineError(formatApiError(body), body.delivery === "unknown"); + if (slow) throw new Error(formatApiError(body)); return null; } sessionIdRef.current = realId; @@ -1328,6 +1330,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { observeCreatedSessionRef.current?.(realId); } if (offline) throw new HostOfflineError(formatApiError(body), body.delivery === "unknown"); + // Adopted above: the id is kept, so the caller's retry targets this child. + if (slow) throw new Error(formatApiError(body)); return realId; })(); diff --git a/instrumentation.node.ts b/instrumentation.node.ts index be98c8004..3e41722fa 100644 --- a/instrumentation.node.ts +++ b/instrumentation.node.ts @@ -102,9 +102,9 @@ export async function register(): Promise { // user is away leaves no trace in a terminal that no longer exists (CLI runs // are killed with their terminal; pages then show endless loading until the // process is restarted). Append fatal errors and event-loop stalls to a file - // so the next incident explains itself. An uncaught exception keeps Node's - // crash semantics (journal + console record, then exit); client aborts and - // unhandled rejections are journaled and survived (see below). + // so the next incident explains itself. Node's default crash semantics are + // preserved — this only adds the record before exiting — except for client + // aborts, which are journaled and survived (see below). const logDir = getDiagnosticsDir(); const logPath = join(logDir, "diagnostics.log"); const appendDiag = (kind: string, detail: string) => { @@ -128,40 +128,14 @@ export async function register(): Promise { return; } appendDiag("crash", `uncaughtException ${describe(error)}`); - console.error(`[omp-web] uncaught exception — exiting: ${describe(error)}`); // An uncaughtException listener suppresses Node's default exit; keep the - // crash-visible semantics by exiting explicitly. Unlike a rejection, the - // throw escaped a request handler or timer halfway through its work, so the - // process state (a half-written session file, a held mutex) is unknown and - // there is no safe resume point: staying up would serve corrupted state. + // crash-visible semantics by exiting explicitly. process.exit(2); }); - // Rejections of fire-and-forget chains are logged and survived: nobody - // awaited that promise, so every request path is still intact, and killing - // the server for one would take down every chat it serves — the scheduled - // task does not restart a server that dies on its own. The journal always - // gets the record; the console copy is rate-limited so a tick that rejects - // once a second cannot bury it. - let rejectionWindowStart = Date.now(); - let rejectionsLogged = 0; - let rejectionsSuppressed = 0; process.on("unhandledRejection", (reason) => { - appendDiag("rejection", `unhandledRejection ${describe(reason)}`); - const now = Date.now(); - if (now - rejectionWindowStart >= 60_000) { - if (rejectionsSuppressed > 0) { - console.error(`[omp-web] ${rejectionsSuppressed} further unhandled rejection(s) in the last minute were journaled only.`); - } - rejectionWindowStart = now; - rejectionsLogged = 0; - rejectionsSuppressed = 0; - } - if (rejectionsLogged < 10) { - rejectionsLogged += 1; - console.error(`[omp-web] unhandled rejection (server keeps running): ${describe(reason)}`); - } else { - rejectionsSuppressed += 1; - } + appendDiag("crash", `unhandledRejection ${describe(reason)}`); + // Same as above: preserve Node's crash-on-unhandled-rejection default. + process.exit(2); }); let lastTick = Date.now(); let lastCpu = process.cpuUsage(); diff --git a/lib/agent-client.ts b/lib/agent-client.ts index 3ed1b7deb..032af89b4 100644 --- a/lib/agent-client.ts +++ b/lib/agent-client.ts @@ -14,8 +14,7 @@ import { formatApiError } from "@/lib/i18n/api-error"; /** A failed `POST /api/agent/[id]` carrying the route's stable code. Callers * that must react differently from a plain error (a `session_slow` ack timeout * with `maybeStarted` is not a rolled-back prompt; `abortUnconfirmed` is not a - * completed stop; `session_running_elsewhere` means another omp holds the - * session and the user must decide) branch on these fields. */ + * completed stop) branch on these fields. */ export class AgentCommandError extends Error { readonly code: string | undefined; readonly maybeStarted: boolean; diff --git a/lib/agent-command.ts b/lib/agent-command.ts index 6ba7f986a..775449b1e 100644 --- a/lib/agent-command.ts +++ b/lib/agent-command.ts @@ -55,17 +55,11 @@ function sendFences(): Map> { return (globalThis.__ompSendFences ??= new Map()); } -export interface RunAgentCommandOptions { - /** Upload receipts the outbox already proved, so its own retry is not re-checked. */ - trustedUploads?: OutboxUploadReceipt[]; -} - /** Everything POST /api/agent/[id] does once the body is parsed; shared with * the browser socket. `owner`: the caller's web session (lib/web-auth.ts * `requestOwner`), whose uploads a prompt may attach. Never throws: failures * become `commandErrorResponse`. */ -export async function runAgentCommand(id: string, body: unknown, advisor: boolean, owner: string, options: RunAgentCommandOptions = {}): Promise { - const trustedUploads = options.trustedUploads; +export async function runAgentCommand(id: string, body: unknown, advisor: boolean, owner: string, trustedUploads?: OutboxUploadReceipt[]): Promise { let release = () => {}; // frees this command's send fence; idempotent try { const command = body as { type?: unknown; [key: string]: unknown } | null; diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 772989299..b64ed4b5b 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -309,9 +309,6 @@ "notifications.completedBody": "Task finished.", "notifications.inputBody": "Waiting for your answer: {detail}", "notifications.inputBodyNoDetail": "Waiting for your answer.", - "notifications.reminderTitle": "Reminder: {title}", - "notifications.reminderBody": "Still waiting since {since}: {detail}", - "notifications.reminderBodyNoDetail": "Still waiting for your answer since {since}.", "notifications.errorBody": "Run failed: {detail}", "notifications.errorBodyNoDetail": "Run failed.", "notifications.modelSwitchBody": "Switched {from} → {to}: {detail}", @@ -334,8 +331,6 @@ "notifications.typeCompletedDesc": "A prompt and the background work it started are done. Subagents never notify.", "notifications.typeInput": "Waiting for input", "notifications.typeInputDesc": "The agent asks a question or needs an approval.", - "notifications.inputReminder": "Remind me about unanswered questions", - "notifications.inputReminderDesc": "The notification repeats while a question stays unanswered, until it is answered or cancelled.", "notifications.typeError": "Run failed", "notifications.typeErrorDesc": "A run stops with an error after retries and fallbacks, or the omp process exits.", "notifications.typeModelSwitch": "Model switched automatically", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index f575300b3..515ab5b4c 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -292,9 +292,6 @@ "notifications.completedBody": "タスクが完了しました。", "notifications.inputBody": "回答を待っています: {detail}", "notifications.inputBodyNoDetail": "回答を待っています。", - "notifications.reminderTitle": "リマインダー: {title}", - "notifications.reminderBody": "{since} から回答を待っています: {detail}", - "notifications.reminderBodyNoDetail": "{since} から回答を待っています。", "notifications.errorBody": "実行に失敗しました: {detail}", "notifications.errorBodyNoDetail": "実行に失敗しました。", "notifications.modelSwitchBody": "{from} → {to} に切り替えました: {detail}", @@ -317,8 +314,6 @@ "notifications.typeCompletedDesc": "プロンプトと、それが開始したバックグラウンド作業が完了したとき。サブエージェントでは通知しません。", "notifications.typeInput": "入力待ち", "notifications.typeInputDesc": "エージェントが質問したり承認を求めたりしたとき。", - "notifications.inputReminder": "未回答の質問を再通知する", - "notifications.inputReminderDesc": "回答またはキャンセルされるまで、通知を繰り返します。", "notifications.typeError": "実行失敗", "notifications.typeErrorDesc": "再試行とフォールバックの後に実行がエラーで止まったとき、または omp プロセスが終了したとき。", "notifications.typeModelSwitch": "モデルの自動切り替え", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index a1b5c0257..415b5d1b0 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -292,9 +292,6 @@ "notifications.completedBody": "任务已完成。", "notifications.inputBody": "正在等待你的回答:{detail}", "notifications.inputBodyNoDetail": "正在等待你的回答。", - "notifications.reminderTitle": "提醒:{title}", - "notifications.reminderBody": "自 {since} 起一直在等待:{detail}", - "notifications.reminderBodyNoDetail": "自 {since} 起一直在等待你的回答。", "notifications.errorBody": "运行失败:{detail}", "notifications.errorBodyNoDetail": "运行失败。", "notifications.modelSwitchBody": "已切换 {from} → {to}:{detail}", @@ -317,8 +314,6 @@ "notifications.typeCompletedDesc": "提示及其启动的后台工作全部完成。子代理不会触发通知。", "notifications.typeInput": "等待输入", "notifications.typeInputDesc": "代理提出问题或需要批准。", - "notifications.inputReminder": "提醒我未回答的问题", - "notifications.inputReminderDesc": "问题未被回答或取消时,通知会重复发送。", "notifications.typeError": "运行失败", "notifications.typeErrorDesc": "运行在重试和回退后仍因错误停止,或 omp 进程退出。", "notifications.typeModelSwitch": "模型自动切换", diff --git a/lib/instrumentation-crash-policy.test.mjs b/lib/instrumentation-crash-policy.test.mjs index 53f9180f1..cf00ed172 100644 --- a/lib/instrumentation-crash-policy.test.mjs +++ b/lib/instrumentation-crash-policy.test.mjs @@ -77,21 +77,6 @@ test("a client disconnect surfacing as uncaught `aborted` is journaled without e assert.doesNotMatch(journal, /\[crash\]/); }); -// Fire-and-forget chains reject without an awaiter; killing every chat the -// server serves for one would be worse than a journaled record. -const rejectAfterRegister = (options) => runAfterRegister(` - void Promise.reject(new Error("background boom")); - setTimeout(() => process.exit(0), 300); -`, options); - -test("an unhandled rejection is journaled and the server keeps serving", () => { - const { status, journal, stderr } = rejectAfterRegister(); - assert.equal(status, 0, stderr); - assert.match(journal, /\[rejection\] unhandledRejection Error: background boom/); - assert.match(stderr, /unhandled rejection \(server keeps running\): Error: background boom/); - assert.doesNotMatch(journal, /\[crash\]/); -}); - test("the journal follows an isolated agent dir and keeps ~/.omp/omp-web by default", () => { const isolated = throwAfterRegister(`new Error("boom")`); assert.match(isolated.journal, /\[crash\] uncaughtException Error: boom/); diff --git a/lib/message-outbox.test.mjs b/lib/message-outbox.test.mjs index 396485c74..2668f4848 100644 --- a/lib/message-outbox.test.mjs +++ b/lib/message-outbox.test.mjs @@ -300,6 +300,35 @@ test("a lost reply fails as may-have-been-sent and is never resent, even on a ho assert.equal((await (await command(sid, { type: "outbox_remove", id: "x2" })).json()).data.removed, true); }); +test("a session_slow ack timeout after the write fails as may-have-been-sent, not as not-sent", async () => { + hostStatus = "online"; + const sid = "s-slow-ack"; + // The wrapper wrote the frame and omp never acked within the bound: HTTP 400 + // `session_slow` with `maybeStarted`, exactly as commandErrorResponse serves it. + const w = wrapper(sid, { + running: true, + reply: () => { throw new WebRpcError("omp is busy and did not acknowledge the message in time; it may still be running.", "session_slow", undefined, { maybeStarted: true }); }, + }); + await add(sid, "slow-ack-1", "may already run", "followUp"); + await until(() => states(sid)[0] === "may already run:failed", "the uncertain delivery"); + const [entry] = outbox.outboxEntries(sid); + assert.equal(entry.state, "failed"); + assert.equal(entry.mayHaveBeenSent, true, "the UI must say 'possibly sent', not 'not sent'"); + assert.equal(w.sent.length, 1); +}); + +test("a definite session_slow (the watchdog stopped the child) stays not-sent so the text is recoverable", async () => { + hostStatus = "online"; + const sid = "s-slow-definite"; + wrapper(sid, { + running: true, + reply: () => { throw new WebRpcError("omp is busy and did not answer in time; the session keeps running.", "session_slow"); }, + }); + await add(sid, "slow-def-1", "never ran", "followUp"); + await until(() => states(sid)[0] === "never ran:failed", "the definite failure"); + assert.equal(outbox.outboxEntries(sid)[0].mayHaveBeenSent, undefined); +}); + test("uncertain failures never disappear on same-text snapshots, new echoes, or empty upload-only text", async () => { hostStatus = "online"; const sid = "s-late"; diff --git a/lib/message-outbox.ts b/lib/message-outbox.ts index f0ba3ae94..2560ef9a7 100644 --- a/lib/message-outbox.ts +++ b/lib/message-outbox.ts @@ -728,7 +728,7 @@ async function deliver(entry: Row): Promise { publish(sessionId); try { // attachUploads mutates this same command before writing it: the watcher matches the final attachment block too. - const response = await runAgentCommand(sessionId, command, current.advisor === 1, current.owner, { trustedUploads: uploadReceipts }); + const response = await runAgentCommand(sessionId, command, current.advisor === 1, current.owner, uploadReceipts); if (!response.ok) { // Nothing was written: a gone child is retried, and any other refusal is classified as not sent. const written = nativeWriteStarted(command); @@ -783,7 +783,7 @@ function retry(entry: Row): Outcome { /** A non-2xx answer to the start (`sent` false) or to the message itself (spec O6). */ async function refused(entry: Row, response: Response, sent: boolean): Promise { - const body = await response.json().catch(() => ({})) as { error?: unknown; code?: unknown; hostOffline?: unknown; delivery?: unknown }; + const body = await response.json().catch(() => ({})) as { error?: unknown; code?: unknown; hostOffline?: unknown; delivery?: unknown; maybeStarted?: unknown }; const current = row(entry.id); if (!current || current.state === "delivered" || current.state === "failed") return "next"; const error = typeof body.error === "string" ? body.error : `HTTP ${response.status}`; @@ -820,7 +820,10 @@ async function refused(entry: Row, response: Response, sent: boolean): Promise= 500 || body.code === "session_unresponsive")); + // `maybeStarted` is the same statement from the wrapper itself: a `session_slow` ack timeout (HTTP 400) means the + // frame is already in omp's stdin, so the run may exist even though this request failed. Without it the UI called + // the message "Not sent" and offered a resend while omp was already executing it. + return fail(entry, error, sent && (response.status >= 500 || body.code === "session_unresponsive" || body.maybeStarted === true)); } /** `archived`/`absent`: every source answered. Otherwise the archive could not be read: `hello` while only a host's diff --git a/lib/pi-types.ts b/lib/pi-types.ts index da2cb20c7..c0b5e67a5 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -16,26 +16,6 @@ export type UsageLimitState = export type SlowModeScope = "session" | "global"; -/** omp's goal record (`goal` command reply, `goal_updated`, `get_state.goal.goal`). */ -export interface GoalInfo { - id: string; - objective: string; - /** `active` / `paused`; completed and dropped goals answer `null` instead. */ - status: string; - tokenBudget?: number; - tokensUsed: number; - timeUsedSeconds: number; - createdAt: number; - updatedAt: number; -} - -/** Mirror of omp's GoalModeState: the `goal` reply and the `goal` field of `get_state`. */ -export interface GoalModeState { - enabled: boolean; - mode: string; - goal: GoalInfo | null; -} - export interface ModelLike { id: string; provider: string; @@ -122,8 +102,6 @@ export interface RpcSessionState { tokensPerSecond?: number | null; /** Structured skill resolution diagnostics; absent on older OMP builds. */ skillDiagnostics?: SkillDiagnosticsSnapshot; - /** omp goal mode; absent on older OMP builds (never invented here). */ - goal?: GoalModeState | null; } /** @@ -149,8 +127,7 @@ export interface WebSessionState { queuedMessageCount: number; queuedMessages: QueuedMessages; contextUsage: ContextUsage | null; - /** Absent when the client asked for the prompt-less shape (`?systemPrompt=0`). */ - systemPrompt?: string; + systemPrompt: string; thinkingLevel: string; fastModeEnabled: boolean; fastModeActive?: boolean; @@ -163,8 +140,6 @@ export interface WebSessionState { /** Parsed public diagnostics DTO; absent means unsupported or malformed. */ skillDiagnostics?: SkillDiagnosticsSnapshot; todoPhases: TodoPhase[]; - /** omp goal mode snapshot; omitted when the child predates the `goal` field. */ - goal?: GoalModeState | null; extensionStatuses: Array<{ key: string; text: string }>; extensionWidgets: Array<{ key: string; lines: string[]; placement: "aboveEditor" | "belowEditor" }>; } @@ -249,16 +224,6 @@ export interface RpcAskDialogAnswer { customInput?: string; } -/** - * One answer to a blocking extension dialog. Exactly one variant is sent, both - * by the web dialog (ExtensionDialog) and by the notification answer endpoint. - */ -export type ExtensionUiResponse = - | { value: string } - | { confirmed: boolean } - | { cancelled: true } - | { answers: RpcAskDialogAnswer[] }; - /** * omp's rpc-ui extension UI request frames, including the methods missing from * the browser-facing union in lib/types.ts (`open_url`, `cancel`). The wrapper diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 7ef1e42ed..05e4ce2f3 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -4143,86 +4143,64 @@ test("steer, follow-up and abort timeouts name what may already have happened", assert.equal(wrapper.isAlive(), true); }); -test("control commands are bounded; unbounded passthrough commands keep waiting", async (t) => { - const commands = []; +test("the stall watchdog stops the child instead of only dropping membership, and reports it stopped", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); const { wrapper } = snapshotSession(t, async (command) => { - commands.push({ type: command.type, timeout: undefined }); - return {}; - }, SnapshotWrapper, "bounded"); - await wrapper.send({ type: "set_session_name", name: "Renamed" }); - await wrapper.send({ type: "login" }); - // The fake cannot see the timeout, so the source states it: every control - // call goes through sendControl, only the four long runners stay uncapped. - const source = await readFile(new URL("./rpc-manager.ts", import.meta.url), "utf8"); - assert.match(source, /await this\.sendControl\(\{ type: "set_session_name", name \}, GET_STATE_TIMEOUT_MS\)/); - assert.match(source, /UNBOUNDED_PASSTHROUGH_COMMANDS\.has\(type\)/); - assert.match(source, /"login",\s+\/\/ interactive login flow/); - assert.deepEqual(commands.map((command) => command.type), ["set_session_name", "login"]); -}); - -test("no more than 32 commands may wait on one child", async (t) => { - const resolvers = []; - const { wrapper } = snapshotSession(t, () => new Promise((resolve) => resolvers.push(resolve)), SnapshotWrapper, "pending-cap"); - const pending = Array.from({ length: 32 }, () => wrapper.send({ type: "get_state" })); - await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_busy" }); - for (const resolve of resolvers) resolve({}); - await Promise.all(pending); + throw new RpcCommandTimeoutError(command.type, 5_000); + }, SnapshotWrapper, "stalled-child", 0); + const disposeCalls = []; + wrapper.proc.dispose = async (_grace, stopShared) => { disposeCalls.push(stopShared); }; + // No frame, no answer for longer than the 5-minute threshold: this child is wedged. + t.mock.timers.tick(5 * 60_000 + 1_000); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); + assert.deepEqual(disposeCalls, [true], "a daemon-owned child is only stopped with stopShared"); + assert.equal(wrapper.isAlive(), false, "the wrapper is gone synchronously"); + const exited = (await import("./rpc-manager.ts")).getExitedRpcSession("stalled-child"); + assert.equal(exited?.detail, "stalled"); }); -// ---------------------------------------------------------------- #325: timeouts keep the child - -test("a prompt ack timeout keeps the child alive and answers session_slow with maybeStarted", async (t) => { +test("a timed-out session switch fences commands until a state read reconciles the identity", async (t) => { const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); const sent = []; + let switched = false; const { wrapper } = snapshotSession(t, async (command) => { sent.push(command.type); - if (command.type === "prompt") throw new RpcCommandTimeoutError("prompt", 30_000); + if (command.type === "switch_session") throw new RpcCommandTimeoutError("switch_session", 30_000); + if (command.type === "get_state") { + // The switch landed after the request gave up: the child now serves another conversation. + return switched + ? { sessionId: "new-conversation", sessionFile: "/tmp/new.jsonl", isStreaming: false, isCompacting: false, messageCount: 0, queuedMessageCount: 0, todoPhases: [], autoCompactionEnabled: true } + : { sessionId: "old-conversation", sessionFile: "/tmp/old.jsonl", isStreaming: false, isCompacting: false, messageCount: 0, queuedMessageCount: 0, todoPhases: [], autoCompactionEnabled: true }; + } return {}; - }, SnapshotWrapper, "slow-prompt"); - await assert.rejects( - wrapper.send({ type: "prompt", message: "hi" }), - (error) => error.code === "session_slow" && error.details?.maybeStarted === true, - ); - assert.deepEqual(sent, ["prompt"]); - assert.equal(wrapper.isAlive(), true, "a timeout is not a reason to recycle the child"); - assert.equal(wrapper.isRunning(), true, "the run stays marked until a frame or a successful get_state settles it"); -}); - -test("a get_state timeout keeps the child alive and reports session_slow without details", async (t) => { - const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); - const { wrapper } = snapshotSession(t, async () => { - throw new RpcCommandTimeoutError("get_state", 5_000); - }, SnapshotWrapper, "slow-state"); - await assert.rejects(wrapper.send({ type: "get_state" }), (error) => error.code === "session_slow" && error.details === undefined); - assert.equal(wrapper.isAlive(), true); -}); -test("steer, follow-up and abort timeouts name what may already have happened", async (t) => { - const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); - const { wrapper } = snapshotSession(t, async (command) => { - throw new RpcCommandTimeoutError(command.type, 30_000); - }, SnapshotWrapper, "slow-controls"); - for (const type of ["steer", "follow_up"]) { - await assert.rejects(wrapper.send({ type, message: "x" }), (error) => error.details?.maybeStarted === true, type); - } - await assert.rejects(wrapper.send({ type: "abort" }), (error) => error.details?.abortUnconfirmed === true); - assert.equal(wrapper.isAlive(), true, "a timeout is not a reason to recycle the child"); -}); - -test("control commands are bounded; unbounded passthrough commands keep waiting", async (t) => { - const commands = []; - const { wrapper } = snapshotSession(t, async (command) => { - commands.push({ type: command.type }); + }, SnapshotWrapper, "old-conversation"); + await assert.rejects(wrapper.send({ type: "switch_session", sessionId: "new-conversation" }), { code: "session_slow" }); + switched = true; + // The next command must not act on the stale identity: it reconciles first. + await wrapper.send({ type: "get_session_stats" }); + assert.deepEqual(sent, ["switch_session", "get_state", "get_session_stats"]); + assert.equal(wrapper.sessionId, "new-conversation", "the wrapper now serves the reconciled identity"); +}); + +test("control commands carry a deadline to the transport; unbounded passthrough commands carry none", async (t) => { + // The timeout is observable at the transport boundary: `sendCommand` receives + // it as its second argument. A command without a deadline pins the request. + const deadlines = new Map(); + const { wrapper } = snapshotSession(t, async (command, timeoutMs) => { + deadlines.set(command.type, timeoutMs); return {}; }, SnapshotWrapper, "bounded"); await wrapper.send({ type: "set_session_name", name: "Renamed" }); + await wrapper.send({ type: "get_session_stats" }); await wrapper.send({ type: "login" }); - // The fake cannot see the timeout, so the source states it: every control - // call goes through sendControl, only the four long runners stay uncapped. - const source = await readFile(new URL("./rpc-manager.ts", import.meta.url), "utf8"); - assert.match(source, /await this\.sendControl\(\{ type: "set_session_name", name \}, GET_STATE_TIMEOUT_MS\)/); - assert.match(source, /UNBOUNDED_PASSTHROUGH_COMMANDS\.has\(type\)/); - assert.match(source, /"login",\s+\/\/ interactive login flow/); - assert.deepEqual(commands.map((command) => command.type), ["set_session_name", "login"]); + await wrapper.send({ type: "export_html" }); + assert.equal(typeof deadlines.get("set_session_name"), "number", "a control command is bounded"); + assert.ok(deadlines.get("set_session_name") > 0); + assert.equal(typeof deadlines.get("get_session_stats"), "number"); + // `login` and `export_html` legitimately take minutes: no deadline at all. + assert.equal(deadlines.get("login"), undefined); + assert.equal(deadlines.get("export_html"), undefined); }); test("no more than 32 commands may wait on one child", async (t) => { diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 2c5c9a1c0..b7551bcb1 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -27,7 +27,6 @@ import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "./ import { eventWithToolResultImageUrls } from "./media-cache"; import type { BashResultInfo, - ExtensionUiResponse, OmpModel, RpcAvailableSlashCommand, RpcSessionState, @@ -71,7 +70,7 @@ interface CompactionResultLike { * `Number(...) || 0`, which silently disabled the very watchdog that rescues a * wedged child. Such a value now keeps the default and warns once at startup. */ -export function readNonNegativeMs(name: string, fallback: number): number { +function readNonNegativeMs(name: string, fallback: number): number { const raw = process.env[name]; if (raw === undefined) return fallback; const parsed = raw.trim() === "" ? Number.NaN : Number(raw); @@ -195,7 +194,7 @@ function slowSessionError(details?: Record): WebRpcError { } /** Shape check for an ask-dialog `answers` payload; omp validates the content. */ -export function isAskAnswers(value: unknown): boolean { +function isAskAnswers(value: unknown): boolean { return Array.isArray(value) && value.every((answer: unknown) => isRecord(answer) && typeof answer.id === "string" @@ -235,9 +234,6 @@ const PASSTHROUGH_COMMANDS = new Set([ "btw", "btw_cancel", "get_btw_history", - // Goal mode (`{type:"goal", op}`) has the same shape as omp's RPC frame and - // is the only way native clients reach it; every op answers `{goal, state}`. - "goal", ]); // Outlasts omp's cold prediction-daemon start (up to 3 × 30s start rounds plus a @@ -555,6 +551,10 @@ export class AgentSessionWrapper { private readonly movedFromIds: string[] = []; private initPromise: Promise | null = null; private restarting = false; + /** A session switch whose answer never arrived: commands stay fenced until a + * state read reconciles which conversation the child now serves. */ + private identityStale = false; + private identityReconcile: Promise | null = null; private mcpListWaiter: { resolve: (text: string) => void; reject: (error: Error) => void; timer: ReturnType } | null = null; /** Synchronous mutex for getMcpList: checked+set before any await, so two * concurrent callers can never both enter (the waiter/promptRunning @@ -1543,52 +1543,13 @@ export class AgentSessionWrapper { clearTimeout(timer); this.uiExpiryTimers.delete(id); } - // Every settle path (answer, cancel, expiry, restart, destroy, new run) - // forgets the dialog; the repeat must stop with it. - } - - /** - * A pending dialog is settled (answered, cancelled, expired or its child is - * gone): forget it and retract the `input` notification it produced. - */ - private settlePendingUiRequest(id: string): boolean { - if (!this.pendingUiRequests.has(id)) return false; - this.forgetPendingUiRequest(id); - return true; } private clearPendingUiRequests(): void { this.dropServerUiRequests(); for (const timer of this.uiExpiryTimers.values()) clearTimeout(timer); this.uiExpiryTimers.clear(); - for (const id of [...this.pendingUiRequests.keys()]) this.settlePendingUiRequest(id); - } - - /** - * Answer a blocking dialog from a notification action. Uses the same - * validation and frame as the agent route's `extension_ui_response` command, - * and returns whether the request was still pending. - */ - answerExtensionUiRequest(id: string, response: ExtensionUiResponse): "answered" | "alreadySettled" { - const pending = this.pendingUiRequests.get(id); - if (!pending) return "alreadySettled"; - const pendingAsk = pending.method === "ask"; - // A pending ask accepts only its answers or a cancel; any other pending - // dialog accepts no answers. Anything else would drop it from reconnect - // replay while omp rejects the payload. - if (pendingAsk) { - if (!("cancelled" in response) && !isAskAnswers("answers" in response ? response.answers : undefined)) { - throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); - } - } else if ("answers" in response) { - throw new WebRpcError("This dialog does not take answers", "invalid_ask_answers"); - } - const wasPending = this.settlePendingUiRequest(id); - this.proc.sendFrame({ type: "extension_ui_response", id, ...response }); - // omp sends no cancel for an answered dialog; other tabs on this session - // would keep showing it, so settle it for them here. - if (wasPending) this.emit({ type: "extension_ui_request", id: `cancel:${id}`, method: "cancel", targetId: id }); - return "answered"; + this.pendingUiRequests.clear(); } /** Settle every server dialog as declined and close it in attached tabs. */ @@ -1619,8 +1580,7 @@ export class AgentSessionWrapper { const method = event.method as string; const id = event.id as string; if (method === "cancel") { - const targetId = typeof event.targetId === "string" ? event.targetId : ""; - if (targetId) this.settlePendingUiRequest(targetId); + this.forgetPendingUiRequest(event.targetId as string); return false; } // Only the “Allow tool: ” confirmation is covered. Other extension @@ -1637,7 +1597,7 @@ export class AgentSessionWrapper { const timeout = typeof event.timeout === "number" ? event.timeout : undefined; if (timeout && timeout > 0) { event.expiresAt = Date.now() + timeout; - const timer = setTimeout(() => this.settlePendingUiRequest(id), timeout); + const timer = setTimeout(() => this.forgetPendingUiRequest(id), timeout); timer.unref?.(); this.uiExpiryTimers.set(id, timer); } @@ -2302,7 +2262,7 @@ export class AgentSessionWrapper { private async sendRpc( command: { type: string; [key: string]: unknown }, timeoutMs?: number, - onReply?: (success: boolean) => void, + onReply?: (success: boolean, id: string) => void, ): Promise { try { const result = await this.proc.sendCommand(command, timeoutMs, onReply); @@ -2325,7 +2285,7 @@ export class AgentSessionWrapper { command: { type: string; [key: string]: unknown }, timeoutMs: number, timeoutDetails?: Record, - onReply?: (success: boolean) => void, + onReply?: (success: boolean, id: string) => void, ): Promise { try { return await this.sendRpc(command, timeoutMs, onReply); @@ -2345,6 +2305,10 @@ export class AgentSessionWrapper { * `GET /api/sessions/[id]/state` serves, while `GET /api/agent/[id]` only * sees `{running:false}` — exactly like a process crash. * + * `stopShared` is essential for a daemon-owned child: without it `dispose()` + * only drops this web app's membership and the wedged child keeps running on + * the host, so claiming it was stopped would be false. + * * Returns whether the child was disposed. */ private destroyIfStalled(): boolean { @@ -2376,7 +2340,9 @@ export class AgentSessionWrapper { if (this.streaming || this.promptRunning || this.unsettled) { this.publishNotifications({ type: "process_exit", detail: "stalled" }); } - this.destroy(); + // `_alive` turns false synchronously, so the wrapper is gone before this + // returns; the child itself is stopped by the same call (shared or not). + void this.destroyAndWait("stalled", true); return true; } @@ -2393,6 +2359,33 @@ export class AgentSessionWrapper { return this._sessionId; } + /** + * A session switch timed out: the child may still be writing a new session + * file and may answer the switch after this request gave up. Until a state + * read names the conversation the child now serves, every command stays + * fenced — a command sent for the old id would otherwise act on the new + * conversation while the registry still maps the old id to this child. + * + * The flag outlives a failed read: the next command retries the reconcile + * instead of acting on a stale identity. + */ + /** One reconcile attempt for a fenced identity; throws `session_slow` when the child still cannot say. */ + private async reconcileFencedIdentity(): Promise { + this.identityReconcile ??= (async () => { + const oldId = this._sessionId; + // Generous: the child is busy by definition here, and `get_state` is the + // only read that names the new identity. + const state = await this.sendRpc({ type: "get_state" }, PROMPT_ACK_TIMEOUT_MS); + this.applyIdentity(state); + if (oldId && oldId !== this._sessionId) this.onIdentityChangeCallback?.(oldId, this._sessionId); + this.invalidateSessionLists(); + this.identityStale = false; + })().finally(() => { + this.identityReconcile = null; + }); + await this.identityReconcile; + } + private async editMessage(entryId: unknown): Promise { if (typeof entryId !== "string" || !entryId.trim()) { throw new WebRpcError("The edit target must be a user message", "invalid_edit_target"); @@ -2760,6 +2753,14 @@ export class AgentSessionWrapper { async send(command: Record): Promise { if (this.restarting) throw new WebRpcError(RESTARTING_MESSAGE, "session_restarting"); + // A timed-out session switch may still land: never act on a stale identity. + if (this.identityStale) { + try { + await this.reconcileFencedIdentity(); + } catch { + throw slowSessionError(); + } + } if (this.mcpListInFlight) throw new WebRpcError("MCP management is in progress. Try again when it finishes.", "session_busy"); if (!this.isAlive()) throw new Error("Session is no longer running"); if (this.pendingCommands >= MAX_PENDING_COMMANDS) { @@ -3012,7 +3013,16 @@ export class AgentSessionWrapper { // Switching writes a session file before answering, so it gets the // generous prompt-ack bound instead of the 5 s poll bound — but it is // still bounded: a wedged child must not pin the request forever. - const result = await this.sendControl<{ cancelled: boolean }>(command as { type: string }, PROMPT_ACK_TIMEOUT_MS); + // A timeout leaves the outcome unknown: the switch may still land after + // this request gives up, so the wrapper's identity is fenced until a + // state read reconciles it (see reconcileFencedIdentity). + let result: { cancelled: boolean }; + try { + result = await this.sendControl<{ cancelled: boolean }>(command as { type: string }, PROMPT_ACK_TIMEOUT_MS); + } catch (error) { + if (error instanceof WebRpcError && error.code === SESSION_SLOW_CODE) this.identityStale = true; + throw error; + } if (!result.cancelled) { const newSessionId = await this.refreshIdentityAfterSessionChange(); return { cancelled: false, newSessionId }; @@ -3088,9 +3098,9 @@ export class AgentSessionWrapper { if (("answers" in rest || pendingAsk) && !isAskAnswers(rest.answers) && !(pendingAsk && rest.cancelled === true)) { throw new WebRpcError("Invalid ask dialog answers", "invalid_ask_answers"); } - // Forgets the pending dialog and retracts its notification for other - // tabs/devices; the cancel frame below settles it in other tabs. - const wasPending = this.settlePendingUiRequest(id); + // Forgets the pending dialog; the cancel frame below settles it in other tabs. + const wasPending = this.pendingUiRequests.has(id); + this.forgetPendingUiRequest(id); const serverRequest = this.serverUiRequests.get(id); if (serverRequest) { this.serverUiRequests.delete(id); @@ -3424,18 +3434,6 @@ function getLocks(): Map Date: Mon, 9 Nov 2026 20:20:35 +0100 Subject: [PATCH 3/5] fix(rpc): fence a timed-out identity read, spare idle children, keep the tool bridge A switch that is acked but whose follow-up get_state times out left the wrapper on the old session id with no fence: the next command acted on the wrong conversation and the raw timeout escaped as an unlabelled 500. The identity read now fences and answers session_slow like a timed-out switch does. The stall watchdog measured silence since the last frame, but an idle omp sends no frames at all: any session left open longer than five minutes was disposed by its first timed-out command. It now measures an unanswered streak, cleared by any frame or any command answer, so a single timeout can never reach the threshold. set_host_tools/set_host_uri_schemes were bounded at 5 s, but their onReply only records the names when omp answers, and a late reply after a timeout is dropped: one slow registration left the bridge rejecting every host_tool_call for the rest of the child's life. Both registrations are unbounded again, as on main. The identity fence ran before the liveness check, so a child that exited while fenced answered session_slow ('the session keeps running') and clients retried a dead session forever. Liveness is checked first, and a reconcile that loses the child reports it gone. A 503 session_slow on load marked a run this tab never dispatched, and the reconcile poll then reported 'the agent stopped without returning a response' even when the child was blocked on non-run work. runUnclaimedRef suppresses that classification while still clearing the spinner. Also: lib/session-routes.test.mjs expected the pre-alive body (CI-red), and scripts/link-hol-probe.ts still keyed on session_state_timeout, so a timed-out get_state was read as a successful one. --- AGENTS.md | 5 + CHANGELOG.md | 1 + hooks/useAgentSession.rpc.test.mjs | 69 +++++++++++ hooks/useAgentSession.ts | 39 +++++- lib/rpc-manager.test.mjs | 188 ++++++++++++++++++++++++++++- lib/rpc-manager.ts | 134 ++++++++++++++------ lib/session-routes.test.mjs | 1 + scripts/link-hol-probe.ts | 8 +- 8 files changed, 398 insertions(+), 47 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7ea44cfe6..a72e93d22 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1274,10 +1274,15 @@ during the wait. ### Running state + reconciliation - The sidebar subscribes to the `running` channel, backed by `subscribeRunningSessions()` in `lib/rpc-manager.ts`, so running badges update without polling. +- **A command timeout is not a dead child.** `AgentSessionWrapper.send` bounds control and passthrough commands (`GET_STATE_TIMEOUT_MS` 5 s, `PROMPT_ACK_TIMEOUT_MS` 30 s for prompt acks and aborts; `UNBOUNDED_PASSTHROUGH_COMMANDS` and the host tool/URI registrations carry no deadline). An expired wait raises `WebRpcError` code `session_slow` and leaves the child, and any run it is executing, alone. `maybeStarted` says the frame is already in omp's stdin (the prompt may still run); `abortUnconfirmed` says Stop may have landed. The client stops rolling back and resending on either, and the outbox marks such a message possibly-sent instead of **Not sent**. `session_slow` is what a *live* session answers: a wrapper whose child has exited answers "Session is no longer running", so retrying clients resume instead of looping on a busy code. +- **The stall watchdog measures unanswered commands, not silence.** `destroyIfStalled` (only ever called from a command-timeout branch) disposes a child whose *unanswered streak* — from the dispatch of its earliest command that drew no answer and saw no frame — has lasted `OMP_WEB_STALL_DESTROY_MS` (5 min; `0` disables). Any frame or any command answer, an `RpcCommandError` included, clears the streak. An idle omp emits no frames at all, so a clock based on silence would condemn every session left open longer than the threshold on its first timeout; the streak makes that impossible. Disposal goes through `destroyAndWait(..., stopShared=true)` so a daemon-owned child is really stopped, and records `exited.detail: "stalled"` like any other exit. +- **A timed-out identity change fences every command.** `new_session`/`switch_session`/`branch` write a session file before answering, so a timeout leaves the outcome unknown. `identityStale` stays set until a `get_state` names the conversation the child now serves (`reconcileFencedIdentity`), and every command reconciles first. The same fence applies when the switch is acked but the follow-up identity read times out (`refreshIdentityAfterSessionChange`): the switch landed, so the wrapper must not keep acting on the old id. A failed reconcile answers `session_slow` only while the child is alive; a read whose link went quiet answers `host_offline` (`delivery: "unknown"`), like every other timeout site, instead of escaping as an unlabelled 500. +- `GET /api/agent/[id]` and `GET /api/sessions/[id]/state` answer `{ running, alive, state?, silentForMs? }`. `alive` is liveness of the child, `running` is an active run; they differ for a freshly spawned idle child (alive, not running). While busy both answer `503 { code: "session_slow", running, alive, silentForMs }`; a child the watchdog disposed answers `running:false, alive:false` (the sessions-state route adds its `exited` record). `silentForMs` counts from the last *frame*, so a command answer does not move it. - An open chat subscribes to `running` too: when its session shows up there while the chat has no `session` stream (the run started after the chat loaded: another tab or device, or a send from a chat instance the user switched away from), it reads `GET /api/agent/[id]` and attaches exactly as on load (`attachLiveRun`). Without it the chat stayed idle beside a running badge until a reload. - The lookup waits for the chat's own work: its mount load while in flight (a stream attached before that load lands would make its `agent_start` drop the load), a stream of its own still connecting (its readiness wait can still fail and close it), and a local send, `!` command, Edit or manual compaction until it settles. The frame is kept meanwhile, and the operation's release rechecks it (`runningRecheckRef`). A local operation that starts during the lookup makes its answer stale (one generation per operation kind). A failed lookup is retried after 1, 2 and 4 s. - Compaction state has one owner at a time. A manual compaction this tab sends holds it until its command settles (`localCompactionsRef`): omp may not have the command yet, so an idle snapshot cannot release it; when it settles during an auto-compaction (`autoCompactingRef`), the control stays with the auto-compaction. Native snapshots (state polls, catch-up, attach, mount) apply only if no compaction started or ended since they were requested (`compactionGenRef`); `setCompacting` keeps `isCompactingRef` and the rendered state together. - `useAgentSession` still treats its `session` channel as primary for chat events, but while a run is active it periodically calls `GET /api/agent/[id]` and also reconciles on `visibilitychange`/`online`. This fixes missed `agent_end` events from background tabs or half-open connections. +- A 503 `session_slow` on the *load* state read is not a failed load: the on-disk transcript stays, the run stays marked, and the observer stream attaches (`markSessionAliveStateUnknown`). Only a load that had no run marked is unclaimed (`runUnclaimedRef`), and only that one suppresses the "stopped without returning a response" classification when it settles: the 503 may come from a child blocked on non-run work (resuming a huge session), and the notice would be false. A run this tab dispatched keeps its claim — the same 503 is also reached by `retrySession`, `/reload`, an external `session_history_changed` and `finishPromptWithoutStream`, where hiding the notice would swallow a genuinely failed run. The settle itself still runs, so the spinner clears. - Prompt runs use a monotonic run id; late SSE or slow reconciliation responses from an old run must be ignored so they cannot resurrect stale streaming bubbles. ### Composer-attached panels (`components/ComposerPanels.tsx`) diff --git a/CHANGELOG.md b/CHANGELOG.md index 33fc53506..b21f80f78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements +- **A busy omp no longer loses the run, the message or the child.** A command that omp does not answer in time now ends only that request: the child keeps running and keeps reporting. The error names what may already have happened (`maybeStarted` for a prompt, `abortUnconfirmed` for Stop), so the composer keeps the send lock instead of rolling back, and a held message is marked possibly-sent rather than **Not sent**. `GET /api/agent/[id]` and `GET /api/sessions/[id]/state` answer `{ running, alive, state?, silentForMs? }` and `503 session_slow` while busy; `alive` is separate from `running`, so a freshly spawned idle child is not read as dead. A timed-out `new_session`/`switch_session` fences every command until a state read names the conversation the child now serves, and a child that has left commands unanswered for `OMP_WEB_STALL_DESTROY_MS` (five minutes) is stopped for real, recorded as `exited.detail: "stalled"`. An idle session is never disposed: the watchdog measures unanswered commands, not silence. Host tool and URI-scheme registrations stay unbounded, so a slow ack cannot leave the browser tool bridge rejecting every call. - **Anthropic stays visible when usage limits are unavailable.** The Provider Usage panel keeps accounts that omp reports without usage data and marks them as unavailable rather than unlimited. - **A delayed archive restore cannot overwrite newer archived work.** Restore now pins the compressed source generation it staged and verifies an atomically captured archive entry before moving artifacts. If another server restored, updated and re-archived that session meanwhile, the stale restore is refused and the newer transcript and artifacts remain available. Captured archives remain discoverable by session ID before publication and after an interrupted restore, so held messages are not falsely failed as belonging to a missing session; orphaned restore claims report their manual-recovery path. - **In-progress archive captures are evidence, not restore targets.** Captures have unique keys and disabled Restore controls, so a capture and a newer archive cannot select the wrong session. Archive discovery rechecks names and source generations after reading to avoid missing a capture during concurrent replacement; a capture encountered while pinning still reports its restore-claim recovery path. diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index b83ffcd27..854cbaa82 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1812,6 +1812,75 @@ test("opening a chat whose state read answers 503 session_slow keeps the transcr assert.ok(lastEs(), "the observer stream attaches to receive the completion frames"); }); +test("a busy 503 on load never claims the agent stopped without a response", async () => { + // The child can be blocked on non-run work (resuming a huge session), so a + // 503 says nothing about an answer. Settling it must clear the spinner + // silently instead of reporting an empty completion this tab never saw. + resetWorld(); + const sid = "busy-open-silent"; + primeSession(sid, [userMsg("u0", "saved history")]); + world.holds.push({ + match: (method, url) => method === "GET" && url === `/api/sessions/${sid}/state`, + produce: async () => ({ + response: Response.json( + { running: false, alive: true, code: "session_slow", error: "omp is busy", silentForMs: 12_000 }, + { status: 503 }, + ), + }), + }); + const w = await mountSession(sid); + assert.equal(w.latest.agentRunning, true, "the run stays marked so the reconcile poll settles it"); + // The child answers the reconcile poll as idle: the run is over. + world.agents.set(sid, { running: false, state: {} }); + await act(async () => { + window.dispatchEvent(new Event("online")); + await sleep(60); + }); + await settle(); + assert.equal(w.latest.agentRunning, false, "the settle still clears the spinner"); + assert.deepEqual( + w.latest.notices.filter((n) => /stopped without returning a response/i.test(n.message)), + [], + "a run this tab never dispatched has no answer to claim missing", + ); +}); + +test("a busy 503 during a run this tab dispatched keeps the empty-stop notice", async () => { + // The same 503 is reached by retrySession, /reload, an external + // session_history_changed and finishPromptWithoutStream. Marking those runs + // unclaimed would hide a genuinely failed run — the inverse of the bug. + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const { w } = await startRun("s1", "new question"); + // The run's own settle reads the state, which answers busy instead. + world.holds.push({ + match: (method, url) => method === "GET" && url === "/api/sessions/s1/state", + produce: async () => ({ + response: Response.json( + { running: true, alive: true, code: "session_slow", error: "omp is busy", silentForMs: 12_000 }, + { status: 503 }, + ), + }), + }); + // retrySession loads with showLoading + state: the dispatched run is still marked. + await act(async () => { w.latest.retrySession(); await sleep(60); }); + await settle(); + assert.equal(w.latest.agentRunning, true, "the busy child keeps the run marked"); + // The child answers the reconcile poll as idle without any saved answer. + world.agents.set("s1", { running: false, state: {} }); + await act(async () => { + window.dispatchEvent(new Event("online")); + await sleep(60); + }); + await settle(); + assert.equal(w.latest.agentRunning, false, "the settle still clears the spinner"); + assert.equal( + w.latest.notices.filter((n) => /stopped without returning a response/i.test(n.message)).length, + 1, + "a run this tab dispatched must not lose its empty-stop notice to the busy 503", + ); +}); + test("a 503 state answer without a busy code stays a load failure", async () => { resetWorld(); const sid = "broken-open"; diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 9ba9fc574..c922a18bf 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -655,6 +655,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // Persisted entries preceding a locally submitted run cannot supply its answer. // Empty on mount; null while a submitted run's boundary is still being read. const runPreviousEntryIdsRef = useRef([]); + // The run being shown was never dispatched by this tab (a 503 `session_slow` + // on load). It may be settled, but never classified as an empty answer: the + // child may be blocked on non-run work, and "stopped without returning a + // response" would be a false failure. + const runUnclaimedRef = useRef(false); const slashCommandRunRef = useRef(false); // Bumped on every roster clear (run end): in-flight get_subagents/history // responses from the finished run must not merge into the cleared (or next @@ -1033,10 +1038,22 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // out. The run must stay marked so the periodic reconcile poll settles it, // and the observer stream attaches (frames are the completion path once omp // answers again). The on-disk transcript is already loaded by the caller. + // + // A load that had no run marked starts one this tab never dispatched: there + // is no answer to claim missing, and the 503 may come from a child blocked on + // non-run work (resuming a huge session), so "stopped without returning a + // response" would be a false failure. The settle itself still runs, so the + // spinner clears. + // + // A run this tab dispatched keeps its claim: the same 503 is also reached by + // `retrySession`, `/reload`, an external `session_history_changed` and + // `finishPromptWithoutStream`, and suppressing the notice there would hide a + // genuinely failed run. const markSessionAliveStateUnknown = useCallback(() => { if (!agentRunningRef.current) { agentRunningRef.current = true; setAgentRunning(true); + runUnclaimedRef.current = true; } syncActionsRef.current?.subscribe(false); }, []); @@ -2031,12 +2048,18 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // error — never leave the user with a disappeared spinner and no // explanation. Builtin slash commands are allowed to complete without // an assistant message, hence allowEmptyResponse above. - // A prompt whose ack timed out may have started late: do not claim it - // failed, repeat the localized hint instead (no error toast). - const message = maybeStartedRunRef.current - ? translate("agentSession.maybeStarted") - : translate("agentSession.responseFailed"); - addNotice({ type: maybeStartedRunRef.current ? "warning" : "error", message }); + // A run this tab never dispatched (a busy 503 on load) has no answer to + // claim missing: the child may have been blocked on non-run work. + if (runUnclaimedRef.current) { + runUnclaimedRef.current = false; + } else { + // A prompt whose ack timed out may have started late: do not claim it + // failed, repeat the localized hint instead (no error toast). + const message = maybeStartedRunRef.current + ? translate("agentSession.maybeStarted") + : translate("agentSession.responseFailed"); + addNotice({ type: maybeStartedRunRef.current ? "warning" : "error", message }); + } } catchUp.invalidate(); eventCoalescer.reset(); @@ -2063,6 +2086,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { independentRunErrorRef.current = null; maybeStartedRunRef.current = false; slashCommandRunRef.current = false; + runUnclaimedRef.current = false; onAgentEnd?.(); } }, [addNotice, addUnconfirmedRunErrorNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, loadSession, onAgentEnd, refreshSubagentHistory, resetSubagentActivityState, surfaceQuotaOnStream]); @@ -2435,6 +2459,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runErrorAssistantRef.current = null; independentRunErrorRef.current = null; maybeStartedRunRef.current = false; + runUnclaimedRef.current = false; break; case "agent_end": { // isTerminal === false means an async delivery resumes this run soon. @@ -2527,6 +2552,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { independentRunErrorRef.current = null; maybeStartedRunRef.current = false; slashCommandRunRef.current = false; + runUnclaimedRef.current = false; if (endedSid) { void loadSession(endedSid, false, false, endedRunId); const endToken = beginAuthoritativeModelSync(); @@ -3269,6 +3295,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runErrorAssistantRef.current = null; independentRunErrorRef.current = null; maybeStartedRunRef.current = false; + runUnclaimedRef.current = false; runPreviousEntryIdsRef.current = sessionIdRef.current ? null : []; agentRunningRef.current = true; slashCommandRunRef.current = isSlashCommandPrompt; diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 05e4ce2f3..eac8f19f4 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -4143,7 +4143,7 @@ test("steer, follow-up and abort timeouts name what may already have happened", assert.equal(wrapper.isAlive(), true); }); -test("the stall watchdog stops the child instead of only dropping membership, and reports it stopped", async (t) => { +test("the stall watchdog stops a child that leaves commands unanswered, and reports it stopped", async (t) => { const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); const { wrapper } = snapshotSession(t, async (command) => { @@ -4151,7 +4151,9 @@ test("the stall watchdog stops the child instead of only dropping membership, an }, SnapshotWrapper, "stalled-child", 0); const disposeCalls = []; wrapper.proc.dispose = async (_grace, stopShared) => { disposeCalls.push(stopShared); }; - // No frame, no answer for longer than the 5-minute threshold: this child is wedged. + // A command that has gone unanswered past the 5-minute threshold: wedged. + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); + assert.deepEqual(disposeCalls, [], "one timeout is still routine: the child stays"); t.mock.timers.tick(5 * 60_000 + 1_000); await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); assert.deepEqual(disposeCalls, [true], "a daemon-owned child is only stopped with stopShared"); @@ -4160,6 +4162,45 @@ test("the stall watchdog stops the child instead of only dropping membership, an assert.equal(exited?.detail, "stalled"); }); +test("an idle child that has sent no frames for hours survives its first timeout", async (t) => { + // The regression the old clock could not see: an idle omp emits no frames at + // all, so "no evidence of life" was true for every session left open longer + // than five minutes, and the first timed-out command killed a healthy child. + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + const { wrapper } = snapshotSession(t, async (command) => { + throw new RpcCommandTimeoutError(command.type, 5_000); + }, SnapshotWrapper, "idle-old", 0); + const disposeCalls = []; + wrapper.proc.dispose = async (_grace, stopShared) => { disposeCalls.push(stopShared); }; + t.mock.timers.tick(6 * 60_000); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); + assert.deepEqual(disposeCalls, [], "silence on an idle child is not evidence of a wedge"); + assert.equal(wrapper.isAlive(), true, "the child keeps running"); +}); + +test("a child that answers again between timeouts never accumulates a stall streak", async (t) => { + const { RpcCommandError, RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + t.mock.timers.enable({ apis: ["setTimeout", "Date"] }); + let answer = false; + const { wrapper } = snapshotSession(t, async (command) => { + if (answer) throw new RpcCommandError(command.type, "omp rejected it", "rejected"); + throw new RpcCommandTimeoutError(command.type, 5_000); + }, SnapshotWrapper, "slow-but-alive", 0); + const disposeCalls = []; + wrapper.proc.dispose = async (_grace, stopShared) => { disposeCalls.push(stopShared); }; + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); + t.mock.timers.tick(4 * 60_000); + // An answer — even a rejection — proves the loop is alive and clears the streak. + answer = true; + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "rejected" }); + answer = false; + t.mock.timers.tick(4 * 60_000); + await assert.rejects(wrapper.send({ type: "get_state" }), { code: "session_slow" }); + assert.deepEqual(disposeCalls, [], "the streak restarted after the answer"); + assert.equal(wrapper.isAlive(), true); +}); + test("a timed-out session switch fences commands until a state read reconciles the identity", async (t) => { const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); const sent = []; @@ -4211,3 +4252,146 @@ test("no more than 32 commands may wait on one child", async (t) => { for (const resolve of resolvers) resolve({}); await Promise.all(pending); }); + +test("a switch that lands but whose identity read times out fences the next command", async (t) => { + // The switch is acked, so the child is already on the new conversation; the + // follow-up get_state then times out. Without a fence the wrapper keeps the + // old id and the next command acts on the wrong conversation — and the raw + // timeout escapes as an unlabelled 500. + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const sent = []; + let stateReads = 0; + const { wrapper } = snapshotSession(t, async (command) => { + sent.push(command.type); + if (command.type === "switch_session") return { cancelled: false }; + if (command.type === "get_state") { + stateReads += 1; + // The first read (identity refresh right after the ack) times out; the + // reconcile read afterwards succeeds and names the new conversation. + if (stateReads === 1) throw new RpcCommandTimeoutError("get_state", 5_000); + return { sessionId: "new-conversation", sessionFile: "/tmp/new.jsonl", isStreaming: false, isCompacting: false, messageCount: 0, queuedMessageCount: 0, todoPhases: [], autoCompactionEnabled: true }; + } + return {}; + }, SnapshotWrapper, "old-conversation"); + await assert.rejects( + wrapper.send({ type: "switch_session", sessionId: "new-conversation" }), + (error) => error.code === "session_slow", + "an unreadable identity answers session_slow, not a bare 500", + ); + assert.equal(wrapper.sessionId, "old-conversation", "the identity is still the old one: the read failed"); + // The fence makes the next command reconcile before it acts. + await wrapper.send({ type: "get_session_stats" }); + assert.deepEqual(sent, ["switch_session", "get_state", "get_state", "get_session_stats"]); + assert.equal(wrapper.sessionId, "new-conversation", "the reconcile applied the identity the switch produced"); +}); + +test("a switch whose identity read loses the link answers host_offline, never a bare 500", async (t) => { + // The switch is acked (the link was alive), then the link goes quiet before + // the identity read is answered. Every other timeout site converts that to + // `host_offline`; the raw timeout here surfaced as an unlabelled 500. + const { startRpcSession } = await import("./rpc-manager.ts"); + const hub = await import("./hosts/hub.ts"); + const { linkHost } = await import("./hosts/link-driver.test-helper.mjs"); + const link = await linkHost("Quiet identity box"); + let session; + t.after(async () => { + hub.closeHostLink(link.id); + await session?.destroyAndWait(); + }); + const kills = []; + const stateAsked = Promise.withResolvers(); + let switched = false; + const answer = ompOverLink(link, "s-switch"); + const omp = async (message) => { + if (message.type === "kill") { + kills.push(message); + return; + } + if (message.type !== "stdin") return; + const command = JSON.parse(message.line); + if (command.type === "switch_session") { + switched = true; + return link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "response", id: command.id, command: "switch_session", success: true, data: { cancelled: false } }) }); + } + // The switch landed, then the lid closes: the identity read is never answered. + if (command.type === "get_state" && switched) { + stateAsked.resolve(); + return; + } + await answer(message); + }; + const ops = spawnOverLink(link, []); + link.serve(ops, omp); + ({ session } = await startRpcSession("s-switch", "", "/w", undefined, false, null, undefined, hub.getHost(link.id))); + + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: Date.now() }); + const switching = session.send({ type: "switch_session", sessionId: "new-conversation" }); + await stateAsked.promise; + // GET_STATE_TIMEOUT_MS: well inside the 30 s offline window, so the host still looks online. + t.mock.timers.tick(5_000); + await assert.rejects( + switching, + (error) => error.code === "host_offline" && error.delivery === "unknown", + "a quiet link answers host_offline, not an unlabelled 500", + ); + t.mock.timers.reset(); + assert.deepEqual(kills, [], "the child is not recycled"); + assert.equal(session.isAlive(), true); +}); + +test("a fenced wrapper whose child died reports the session gone, never session_slow", async (t) => { + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + let dead = false; + const { wrapper } = snapshotSession(t, async (command) => { + if (dead) throw new Error("omp RPC process has exited"); + if (command.type === "switch_session") throw new RpcCommandTimeoutError("switch_session", 30_000); + throw new RpcCommandTimeoutError("get_state", 30_000); + }, SnapshotWrapper, "fenced-dead"); + await assert.rejects(wrapper.send({ type: "switch_session", sessionId: "x" }), { code: "session_slow" }); + // The child exits while the fence is up. `session_slow` promises a running + // session, so retrying clients and the outbox would loop forever instead of + // resuming; the reconcile's own failure must surface as the session being gone. + dead = true; + wrapper.destroy(); + await assert.rejects( + wrapper.send({ type: "get_session_stats" }), + (error) => error.code !== "session_slow" && /no longer running/i.test(error.message), + ); +}); + +test("a fenced wrapper whose child exits mid-reconcile reports the session gone", async (t) => { + // The reconcile read itself times out because the child is gone: the fence + // must not answer the busy code for it. + const { RpcCommandTimeoutError } = await import("./omp/rpc-process.ts"); + const { wrapper } = snapshotSession(t, async (command) => { + if (command.type === "switch_session") throw new RpcCommandTimeoutError("switch_session", 30_000); + wrapper.destroy(); + throw new RpcCommandTimeoutError("get_state", 30_000); + }, SnapshotWrapper, "fenced-exits"); + await assert.rejects(wrapper.send({ type: "switch_session", sessionId: "x" }), { code: "session_slow" }); + await assert.rejects( + wrapper.send({ type: "get_session_stats" }), + (error) => error.code !== "session_slow" && /no longer running/i.test(error.message), + ); +}); + +test("host tool registration is never bounded: a slow ack still records the names", async (t) => { + // omp holds the registration as soon as the frame reaches its stdin, so a + // timeout would leave the wrapper rejecting every host_tool_call for the rest + // of the child's life ("not available in omp-web"). + const deadlines = []; + const { wrapper, emit, sentFrames } = snapshotSession(t, async (command, timeoutMs) => { + deadlines.push([command.type, timeoutMs]); + return {}; + }, SnapshotWrapper, "host-tools-unbounded"); + await wrapper.send({ type: "set_host_tools", tools: [{ name: "open_url" }] }); + await wrapper.send({ type: "set_host_uri_schemes", schemes: [{ scheme: "browser", writable: true }] }); + assert.deepEqual(deadlines, [["set_host_tools", undefined], ["set_host_uri_schemes", undefined]], "both registrations are unbounded"); + // The registration took effect: a call is routed, not rejected. + const calls = []; + const leave = subscribeHostToolCalls((call) => calls.push(call)); + t.after(leave); + emit({ type: "host_tool_call", id: "call-1", toolName: "open_url", arguments: { url: "https://a.test" } }); + assert.deepEqual(calls.map((call) => call.id), ["call-1"]); + assert.deepEqual(sentFrames, [], "nothing was rejected as unregistered"); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index b7551bcb1..83836e3e0 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -97,13 +97,14 @@ const IDLE_DESTROY_MS = 10 * 60 * 1000; */ const DISCONNECT_DESTROY_MS = readNonNegativeMs("OMP_WEB_DISCONNECT_DESTROY_MS", 120_000); /** - * How long a child may go without any positive evidence of life (a frame or a - * successful command answer) before a *timed-out* command is allowed to - * dispose it. omp blocks its event loop for tens of seconds on large sessions, - * so a timeout alone only means "busy"; five minutes of complete silence on a - * child that then misses another answer means wedged. Set - * `OMP_WEB_STALL_DESTROY_MS=0` to disable the watchdog (a stalled child then - * lives until the disconnect reaper or process exit). + * How long a command may stay unanswered before a *timed-out* command is + * allowed to dispose the child. omp blocks its event loop for tens of seconds + * on large sessions, so a timeout alone only means "busy"; a child that has + * left commands unanswered for five minutes is wedged. The clock is the + * unanswered streak, never mere silence: an idle omp sends no frames at all, so + * a session left open for hours is still healthy and must survive its first + * timeout. Set `OMP_WEB_STALL_DESTROY_MS=0` to disable the watchdog (a stalled + * child then lives until the disconnect reaper or process exit). */ const STALL_DESTROY_MS = readNonNegativeMs("OMP_WEB_STALL_DESTROY_MS", 5 * 60_000); /** Refuse a new command while this many are already awaiting omp. Requests @@ -526,12 +527,16 @@ export class AgentSessionWrapper { /** Last frame the child sent. `silentForMs` reports from here: a command * answer is not a frame, so polls never move this clock. */ private lastFrameAt = 0; - /** Last positive evidence that the child's event loop is alive: a frame or a - * successful command answer (an `RpcCommandError` counts too — omp replied). - * Timed-out answers, polls and `send()` writes deliberately do not move it: - * `send()` only feeds the disconnect reaper. Read exclusively by the stall - * watchdog in the command-timeout branches. */ - private lastEvidenceAt = 0; + /** Dispatch time of the first command in the current unanswered streak; `null` + * = no streak. A streak opens when a command starts waiting and is cleared by + * positive evidence: any frame, or any command answer (`RpcCommandError` + * included — omp replied). Read exclusively by the stall watchdog in the + * command-timeout branches. */ + private unansweredSince: number | null = null; + /** How many commands in the current streak timed out; log detail only. The + * elapsed check already guarantees a streak spans at least one full + * `STALL_DESTROY_MS`, so no single timeout can dispose a child. */ + private unansweredTimeouts = 0; /** In-flight `send()` calls: the reaper must never dispose the child out from * under a command that is still awaiting its response. */ private pendingCommands = 0; @@ -641,7 +646,7 @@ export class AgentSessionWrapper { this.launchAdvisor = launchAdvisor; this.fellBack = fellBack; this.lastFrameAt = Date.now(); - this.lastEvidenceAt = this.lastFrameAt; + this.unansweredSince = null; } get sessionId(): string { @@ -1263,7 +1268,7 @@ export class AgentSessionWrapper { // Any frame proves the child's event loop is running (a `ready` frame is // consumed by waitReady, so this covers runtime frames only). this.lastFrameAt = Date.now(); - this.lastEvidenceAt = this.lastFrameAt; + this.unansweredSince = null; const event = frame.type === "available_commands_update" && Array.isArray(frame.commands) ? { ...frame, commands: (frame.commands as RpcAvailableSlashCommand[]).filter((command) => command.name !== SESSION_EDIT_COMMAND) } : frame; @@ -2257,7 +2262,8 @@ export class AgentSessionWrapper { * Single command choke point for the wrapper. Every successful answer — and * every `RpcCommandError`, because omp answered — is positive evidence that * the child's event loop is alive, which is exactly what the stall watchdog - * needs. Timeouts are not evidence and deliberately do not touch the clock. + * needs. A timeout is not evidence: it opens (or continues) the unanswered + * streak the watchdog measures. */ private async sendRpc( command: { type: string; [key: string]: unknown }, @@ -2266,14 +2272,29 @@ export class AgentSessionWrapper { ): Promise { try { const result = await this.proc.sendCommand(command, timeoutMs, onReply); - this.lastEvidenceAt = Date.now(); + this.clearUnansweredStreak(); return result; } catch (error) { - if (error instanceof RpcCommandError) this.lastEvidenceAt = Date.now(); + if (error instanceof RpcCommandError) { + // omp answered: the loop is alive, whatever it said. + this.clearUnansweredStreak(); + } else if (error instanceof RpcCommandTimeoutError) { + // The streak starts at its earliest unanswered command, so the clock + // measures how long *this* child has failed to answer — never how long + // it has merely been idle. A single timeout can therefore never reach + // the threshold on its own. + this.unansweredSince = Math.min(this.unansweredSince ?? error.dispatchedAt, error.dispatchedAt); + this.unansweredTimeouts += 1; + } throw error; } } + private clearUnansweredStreak(): void { + this.unansweredSince = null; + this.unansweredTimeouts = 0; + } + /** * Bounded command for the control paths: a timeout answers `session_slow` * instead of pinning the request forever, and only the liveness watchdog may @@ -2285,10 +2306,9 @@ export class AgentSessionWrapper { command: { type: string; [key: string]: unknown }, timeoutMs: number, timeoutDetails?: Record, - onReply?: (success: boolean, id: string) => void, ): Promise { try { - return await this.sendRpc(command, timeoutMs, onReply); + return await this.sendRpc(command, timeoutMs); } catch (error) { if (!(error instanceof RpcCommandTimeoutError)) throw error; if (this.destroyIfStalled()) throw slowSessionError(); @@ -2299,11 +2319,17 @@ export class AgentSessionWrapper { /** * Liveness watchdog, called only from a command-timeout branch. A timeout * normally means "busy" (omp blocks its loop for tens of seconds); it means - * "wedged" only when the child has produced no frame and answered no command - * for `STALL_DESTROY_MS`. That child is disposed through the regular exit - * path: the exited-session map gets a `detail: "stalled"` record which - * `GET /api/sessions/[id]/state` serves, while `GET /api/agent/[id]` only - * sees `{running:false}` — exactly like a process crash. + * "wedged" only when a command has gone unanswered for `STALL_DESTROY_MS`. + * The clock is the unanswered streak, never mere silence: an idle omp emits + * no frames at all, so a session left open for hours would otherwise be + * disposed by the first command that happens to time out. Any frame or any + * command answer (a `RpcCommandError` included) clears the streak, so a child + * that is merely slow never accumulates one. + * + * The disposed child goes through the regular exit path: the exited-session + * map gets a `detail: "stalled"` record which `GET /api/sessions/[id]/state` + * serves, while `GET /api/agent/[id]` only sees `{running:false}` — exactly + * like a process crash. * * `stopShared` is essential for a daemon-owned child: without it `dispose()` * only drops this web app's membership and the wedged child keeps running on @@ -2313,10 +2339,12 @@ export class AgentSessionWrapper { */ private destroyIfStalled(): boolean { if (STALL_DESTROY_MS <= 0 || !this.isAlive()) return false; - if (Date.now() - this.lastEvidenceAt < STALL_DESTROY_MS) return false; + const since = this.unansweredSince; + if (since === null) return false; + if (Date.now() - since < STALL_DESTROY_MS) return false; const minutes = Math.round(STALL_DESTROY_MS / 60_000); - const idleFor = Math.round((Date.now() - this.lastEvidenceAt) / 1000); - console.warn(`[omp-web] omp child for session ${this._sessionId || "(new)"} produced no evidence of life for ${idleFor}s (>= ${minutes} min); disposing the stalled child.`); + const unansweredFor = Math.round((Date.now() - since) / 1000); + console.warn(`[omp-web] omp child for session ${this._sessionId || "(new)"} left ${this.unansweredTimeouts} command(s) unanswered for ${unansweredFor}s (>= ${minutes} min); disposing the stalled child.`); if (this._sessionId) { // Same record shape as handleProcessExit so every exited-session consumer // (badges, resume prompts) treats it as the child being gone. @@ -2347,10 +2375,29 @@ export class AgentSessionWrapper { } /** After branch/new_session/switch_session the child is on a different - * session file — re-read identity and re-register in the registry. */ + * session file — re-read identity and re-register in the registry. + * + * The read itself can time out on the busy child this PR targets. The switch + * has already landed by then, so the wrapper is left holding the old + * `_sessionId` with no fence: the next command would act on the wrong + * conversation. Fence instead, exactly as a timed-out switch does, and answer + * `session_slow` so the client retries instead of seeing a 500. */ private async refreshIdentityAfterSessionChange(): Promise { const oldId = this._sessionId; - const state = await this.getStateWithTimeout(); + let state: RpcSessionState; + try { + state = await this.getStateWithTimeout(); + } catch (error) { + if (error instanceof RpcCommandTimeoutError) { + // Link lost: the child runs on there and the reconcile on reconnect + // settles it. Every other timeout site answers `host_offline`; a raw + // timeout here would surface as a bare 500 with no code. + if (this.linkLostDuring(error)) throw this.hostOfflineError("unknown"); + this.identityStale = true; + throw slowSessionError(); + } + throw error; + } this.applyIdentity(state); if (oldId && oldId !== this._sessionId) { this.onIdentityChangeCallback?.(oldId, this._sessionId); @@ -2622,7 +2669,7 @@ export class AgentSessionWrapper { this.restarting = false; // The replacement answered its handshake: the stall clock starts here, so // the disposed old child's silence never counts against the new one. - this.lastEvidenceAt = Date.now(); + this.unansweredSince = null; } notifyRunningChange(); } @@ -2753,16 +2800,23 @@ export class AgentSessionWrapper { async send(command: Record): Promise { if (this.restarting) throw new WebRpcError(RESTARTING_MESSAGE, "session_restarting"); + // Liveness first: a fenced identity on a child that has since exited must + // not answer `session_slow` ("the session keeps running") — clients and the + // outbox treat that as retryable-busy and would retry a dead session + // forever instead of resuming it. + if (!this.isAlive()) throw new Error("Session is no longer running"); // A timed-out session switch may still land: never act on a stale identity. if (this.identityStale) { try { await this.reconcileFencedIdentity(); - } catch { + } catch (error) { + if (!(error instanceof RpcCommandTimeoutError)) throw error; + // The child died while fenced: report that, not a busy session. + if (this.destroyIfStalled() || !this.isAlive()) throw new Error("Session is no longer running"); throw slowSessionError(); } } if (this.mcpListInFlight) throw new WebRpcError("MCP management is in progress. Try again when it finishes.", "session_busy"); - if (!this.isAlive()) throw new Error("Session is no longer running"); if (this.pendingCommands >= MAX_PENDING_COMMANDS) { throw new WebRpcError("Too many commands are in flight for this session", "session_busy"); } @@ -3168,8 +3222,13 @@ export class AgentSessionWrapper { this.hostToolsUnknown = false; return null; } - // Applied as the successful reply is read, before a call in the same host-link batch is routed. - await this.sendControl({ type: "set_host_tools", tools: merged }, GET_STATE_TIMEOUT_MS, undefined, (success) => { + // Unbounded on purpose. This is bookkeeping, not a user-facing request: + // the frame is already in omp's stdin, and the names must be recorded + // when the reply is read. Bounding it would leave omp knowing the + // registration while the wrapper still rejects every `host_tool_call` + // ("not available in omp-web") for the rest of the child's life — the + // late reply after a timeout is dropped, so `onReply` never runs. + await this.sendRpc({ type: "set_host_tools", tools: merged }, undefined, (success) => { if (!success) return; this.hostToolNames = new Set(merged.map((t) => t.name as string)); this.registeredHostTools = valid.filter((tool) => !AGENT_TOOL_NAMES.has(tool.name as string)); @@ -3206,7 +3265,10 @@ export class AgentSessionWrapper { this.registeredHostUriSchemes = schemes; return null; } - await this.sendControl({ type: "set_host_uri_schemes", schemes }, GET_STATE_TIMEOUT_MS, undefined, (success) => { + // Unbounded for the same reason as `set_host_tools`: the registration + // must be recorded when omp replies, and a dropped late reply would + // leave the bridge rejecting every URI request. + await this.sendRpc({ type: "set_host_uri_schemes", schemes }, undefined, (success) => { if (!success) return; this.registeredHostUriSchemes = schemes; this.hostUriSchemes = new Map(); diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 87b8b5eb3..1e129bb30 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -81,6 +81,7 @@ test("state reports a retained exit before the session file exists", async (t) = assert.equal(response.status, 200); assert.deepEqual(await response.json(), { running: false, + alive: false, exited: { id, cwd: "/tmp/project", at: 123, code: 1, signal: null, detail: "startup failed" }, outbox: [], outboxScope: outboxScope(), diff --git a/scripts/link-hol-probe.ts b/scripts/link-hol-probe.ts index 0c43d46fd..64695658a 100644 --- a/scripts/link-hol-probe.ts +++ b/scripts/link-hol-probe.ts @@ -128,8 +128,10 @@ async function waitIdle(session: string, timeoutMs = IDLE_TIMEOUT_MS): Promise Promise, c: string): Promis while (running()) { const sent = performance.now(); const { json } = await command(c, { type: "get_state" }, [400]); - if (json.code === "session_state_timeout") timeouts++; + if (json.code === "session_slow" || json.code === "session_state_timeout") timeouts++; else if (json.error) throw new Error(`get_state on ${c}: ${JSON.stringify(json).slice(0, 300)}`); small.push(performance.now() - sent); await sleep(SMALL_EVERY_MS); From 26769123c6bac5b459c0e12a940a2a4a970121ff Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:35:09 +0100 Subject: [PATCH 4/5] docs(rpc): say why the session_state_timeout branch still exists The comments claimed the code came from 0.6.0, which this tree no longer ships. It is reachable only from a wrapper that outlived a bun --hot reload and kept its previous module instance; the branch is kept for that, and the changelog now says so instead of leaving the compat window unexplained. --- CHANGELOG.md | 2 +- app/api/agent/[id]/route.ts | 7 ++++--- app/api/sessions/[id]/state/route.ts | 7 ++++--- hooks/useAgentSession.ts | 13 +++++++------ 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b21f80f78..39066e835 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,7 +36,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements -- **A busy omp no longer loses the run, the message or the child.** A command that omp does not answer in time now ends only that request: the child keeps running and keeps reporting. The error names what may already have happened (`maybeStarted` for a prompt, `abortUnconfirmed` for Stop), so the composer keeps the send lock instead of rolling back, and a held message is marked possibly-sent rather than **Not sent**. `GET /api/agent/[id]` and `GET /api/sessions/[id]/state` answer `{ running, alive, state?, silentForMs? }` and `503 session_slow` while busy; `alive` is separate from `running`, so a freshly spawned idle child is not read as dead. A timed-out `new_session`/`switch_session` fences every command until a state read names the conversation the child now serves, and a child that has left commands unanswered for `OMP_WEB_STALL_DESTROY_MS` (five minutes) is stopped for real, recorded as `exited.detail: "stalled"`. An idle session is never disposed: the watchdog measures unanswered commands, not silence. Host tool and URI-scheme registrations stay unbounded, so a slow ack cannot leave the browser tool bridge rejecting every call. +- **A busy omp no longer loses the run, the message or the child.** A command that omp does not answer in time now ends only that request: the child keeps running and keeps reporting. The error names what may already have happened (`maybeStarted` for a prompt, `abortUnconfirmed` for Stop), so the composer keeps the send lock instead of rolling back, and a held message is marked possibly-sent rather than **Not sent**. `GET /api/agent/[id]` and `GET /api/sessions/[id]/state` answer `{ running, alive, state?, silentForMs? }` and `503 session_slow` while busy; `alive` is separate from `running`, so a freshly spawned idle child is not read as dead. A timed-out `new_session`/`switch_session` fences every command until a state read names the conversation the child now serves, and a child that has left commands unanswered for `OMP_WEB_STALL_DESTROY_MS` (five minutes) is stopped for real, recorded as `exited.detail: "stalled"`. An idle session is never disposed: the watchdog measures unanswered commands, not silence. Host tool and URI-scheme registrations stay unbounded, so a slow ack cannot leave the browser tool bridge rejecting every call. Both routes still accept the old `session_state_timeout` code, because a wrapper that outlived a `bun --hot` reload keeps its previous module instance and keeps raising it. - **Anthropic stays visible when usage limits are unavailable.** The Provider Usage panel keeps accounts that omp reports without usage data and marks them as unavailable rather than unlimited. - **A delayed archive restore cannot overwrite newer archived work.** Restore now pins the compressed source generation it staged and verifies an atomically captured archive entry before moving artifacts. If another server restored, updated and re-archived that session meanwhile, the stale restore is refused and the newer transcript and artifacts remain available. Captured archives remain discoverable by session ID before publication and after an interrupted restore, so held messages are not falsely failed as belonging to a missing session; orphaned restore claims report their manual-recovery path. - **In-progress archive captures are evidence, not restore targets.** Captures have unique keys and disabled Restore controls, so a capture and a newer archive cannot select the wrong session. Archive discovery rechecks names and source generations after reading to avoid missing a capture during concurrent replacement; a capture encountered while pinning still reports its restore-claim recovery path. diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index 0ff1972af..8975507b2 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -52,9 +52,10 @@ export async function GET( return Response.json({ running: session.isRunning(), alive: true, state }); } catch (error) { // omp being slow is not the run ending: answer 503 so clients retry the - // poll instead of treating the session as idle/recovered. Both the code - // this tree raises (`session_slow`) and 0.6.0's own - // `session_state_timeout` mean the same thing to a client. + // poll instead of treating the session as idle/recovered. This tree raises + // `session_slow`; `session_state_timeout` is the code a wrapper that + // outlived a `bun --hot` reload still raises (the old module instance + // keeps its own error class), and it means the same thing to a client. if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { // The liveness watchdog disposes a child that stayed silent past its // threshold; that child is gone, so the busy answer would be a lie. diff --git a/app/api/sessions/[id]/state/route.ts b/app/api/sessions/[id]/state/route.ts index 772ecab66..d0a570106 100644 --- a/app/api/sessions/[id]/state/route.ts +++ b/app/api/sessions/[id]/state/route.ts @@ -30,9 +30,10 @@ async function sessionState(id: string): Promise { return Response.json({ running: rpc.isRunning(), alive: true, state }); } catch (error) { // omp being slow is not the run ending: answer 503 so clients retry - // instead of treating the session as idle/recovered. Both the code - // this tree raises (`session_slow`) and 0.6.0's own - // `session_state_timeout` mean the same thing to a client. + // instead of treating the session as idle/recovered. This tree raises + // `session_slow`; `session_state_timeout` is the code a wrapper that + // outlived a `bun --hot` reload still raises (the old module instance + // keeps its own error class), and it means the same thing to a client. if (error instanceof WebRpcError && (error.code === "session_slow" || error.code === "session_state_timeout")) { // The liveness watchdog disposes a child that stayed silent past its // threshold; that child is gone, so the busy answer would be a lie. diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index c922a18bf..f931fc23a 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -1141,12 +1141,13 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } const { stateRes, agentState } = reply; if (!stateRes.ok) { - // A busy child (503 `session_slow` / `session_state_timeout`) is not - // a failed load: the transcript above is the on-disk copy, the run - // keeps going and the state is merely unknown right now. The code - // comes from the body already parsed above — a Response body can be - // read only once, and re-reading it threw, turning the busy path into - // an HTTP 503 load failure. + // A busy child (503 `session_slow`, or `session_state_timeout` from a + // wrapper that outlived a `bun --hot` reload) is not a failed load: + // the transcript above is the on-disk copy, the run keeps going and + // the state is merely unknown right now. The code comes from the body + // already parsed above — a Response body can be read only once, and + // re-reading it threw, turning the busy path into an HTTP 503 load + // failure. if (stateRes.status === 503 && (agentState.code === "session_slow" || agentState.code === "session_state_timeout")) { if (!hookAliveRef.current || sessionIdRef.current !== sid || contextRequestSeqRef.current !== requestSeq || promptRunIdRef.current !== requestRun) { From 3ceadabd9f31134741cab14f7195bbde944ee356 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:39:00 +0100 Subject: [PATCH 5/5] test(hooks): cover the uncertain prompt and unconfirmed stop branches The two client branches that answer a command timeout had no hook test: deleting them left the suite green (283 pass either way). - a prompt POST answered 400 {code:session_slow, maybeStarted:true} keeps the optimistic turn, keeps sending locked (a second send is rejected and posts nothing) and shows the maybeStarted hint instead of rolling back. - an abort_and_restore_queue answered 400 {abortUnconfirmed:true} warns exactly once, is not retried, sends no fallback abort and rewrites no draft; the per-entry fallback abort's unconfirmed ack warns the same way. Each was verified by deleting its branch in hooks/useAgentSession.ts: the test fails (rejected instead of accepted; 2 attempts instead of 1; no warning), then the branch was restored byte-identically. --- hooks/useAgentSession.rpc.test.mjs | 95 ++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 854cbaa82..474a5d1c5 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -6043,6 +6043,59 @@ test("overlapping Stops share one atomic withdrawal; an image-only entry does no clearDraft("abort-atomic-twice"); }); +// A Stop omp never confirmed (too busy to answer) is not a stopped run: the +// frame may sit in its stdin and the run may still execute. Nothing is known +// about the queue either, so the attempt is not retried — a second 30-second +// window on a busy child only keeps Stop pending — and the user is told once. +test("a Stop whose answer timed out unconfirmed warns once and is not retried", async () => { + const { getDraft, clearDraft } = await import("@/lib/draft-store"); + resetWorld(); + clearDraft("abort-unconfirmed"); + primeSession("abort-unconfirmed", [userMsg("u0", "loaded question")]); + const { w } = await startRun("abort-unconfirmed", "hello agent"); + world.holds.push({ + match: isAtomicStop, + produce: async () => ({ + status: 400, + value: { error: "omp is busy and did not acknowledge the command in time.", code: "session_slow", abortUnconfirmed: true }, + }), + }); + + await act(async () => { await w.latest.handleAbort(); }); + + assert.equal(world.calls.filter((call) => call.body?.type === "abort_and_restore_queue").length, 1, "an unconfirmed stop is not retried"); + assert.equal(world.calls.some((c) => c.body?.type === "abort"), false, "no fallback abort on a child that never answered"); + assert.equal(world.calls.some((c) => c.body?.type === "remove_queued_message"), false, "the per-entry path would guess about a queue nothing reported"); + assert.deepEqual(w.latest.notices.map((notice) => [notice.type, notice.message]), + [["warning", translate("agentSession.abortUnconfirmed")]], "exactly one warning"); + assert.equal(getDraft("abort-unconfirmed"), null, "nothing is put back into the composer on a guess"); + clearDraft("abort-unconfirmed"); +}); + +// An omp without `abort_and_restore_queue` falls back to withdraw-then-abort. +// That abort's ack can time out too: the run may still be going, so say so +// once — and do not send a second abort into the same busy child. +test("a fallback abort whose ack timed out unconfirmed warns once and is not repeated", async () => { + resetWorld(); + primeSession("abort-fallback-unconfirmed", [userMsg("u0", "loaded question")]); + const { w } = await startRun("abort-fallback-unconfirmed", "hello agent"); + // The fake route answers `Unknown command: abort_and_restore_queue`, which + // selects the per-entry fallback; only the abort's answer times out. + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "abort", + produce: async () => ({ + status: 400, + value: { error: "omp is busy and did not acknowledge the command in time.", code: "session_slow", abortUnconfirmed: true }, + }), + }); + + await act(async () => { await w.latest.handleAbort(); }); + + assert.equal(world.calls.filter((c) => c.body?.type === "abort").length, 1, "an unconfirmed abort is not repeated"); + assert.deepEqual(w.latest.notices.map((notice) => [notice.type, notice.message]), + [["warning", translate("agentSession.abortUnconfirmed")]], "exactly one warning"); +}); + function skillDiagnosticsSnapshot(showStartupDiagnostics, name = "review") { return { cwd: "/workspace", @@ -6338,6 +6391,48 @@ test("a fresh chat's first prompt attaches one event stream instead of an observ assert.equal(callsTo("POST", "/api/agent/fresh-send").some((call) => call.body?.type === "prompt"), true); }); +// The prompt frame may already sit in omp's stdin when its ack times out +// (HTTP 400 `session_slow` + `maybeStarted`). That is not a refused send: +// rolling the bubble back would contradict the hint, and offering the text +// again would run it twice. Keep the turn, keep sending locked, say why. +test("a prompt whose ack timed out with maybeStarted keeps its message, stays locked and never resends", async () => { + resetWorld(); + world.holds.push({ + match: (method, url) => method === "POST" && url === "/api/agent/new", + produce: async () => ({ value: { sessionId: "uncertain" } }), + }); + world.holds.push({ + match: (method, url, body) => method === "POST" && url === "/api/agent/uncertain" && body?.type === "prompt", + produce: async () => ({ + status: 400, + value: { error: "omp is busy and did not acknowledge the message in time; it may still be running.", code: "session_slow", maybeStarted: true }, + }), + }); + const w = await mountSession(null, undefined, { newSessionCwd: "/workspace" }); + let sent; + await act(async () => { + sent = w.latest.handleSend("uncertain prompt"); + await sleep(30); // create the runtime and attach the prompt's stream + }); + let receipt; + await act(async () => { + lastEs().open(); + receipt = await sent; + }); + + assert.deepEqual(receipt, { status: "accepted" }, "an unconfirmed prompt is not a refused send"); + assert.deepEqual(w.latest.messages.map((message) => message.content), ["uncertain prompt"], "the optimistic turn stays: omp may be running it"); + assert.equal(w.latest.agentRunning, true, "sending stays locked until a frame or a state read settles the run"); + assert.deepEqual(w.latest.notices.map((notice) => [notice.type, notice.message]), [["warning", translate("agentSession.maybeStarted")]]); + const promptPosts = () => callsTo("POST", "/api/agent/uncertain").filter((call) => call.body?.type === "prompt"); + assert.equal(promptPosts().length, 1); + + // Locked means locked: a second click cannot put the same text into omp twice. + await act(async () => { assert.deepEqual(await w.latest.handleSend("uncertain prompt"), { status: "rejected" }); }); + assert.equal(promptPosts().length, 1, "no resend"); + w.unmount(); +}); + test("upload continuity: a fresh chat sends completion proof only with its direct prompt", async () => { resetWorld(); world.holds.push({