Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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.
Expand Down
27 changes: 24 additions & 3 deletions app/api/agent/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,35 @@ export async function GET(
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 });
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. 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.
if (!session.isAlive()) return Response.json({ running: false, alive: false });
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;
}
Expand Down
24 changes: 23 additions & 1 deletion app/api/agent/new/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
);
}
Expand Down Expand Up @@ -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.
Expand Down
34 changes: 30 additions & 4 deletions app/api/sessions/[id]/state/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,48 @@ async function sessionState(id: string): Promise<Response> {
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. 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.
// 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,
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<string, unknown>), alive: false });
} catch (error) {
return apiErrorResponse(error);
}
Expand Down
Loading