Skip to content

fix(rpc): keep the omp child on every command timeout - #436

Open
RoyaLemonade wants to merge 5 commits into
ompweb-dev:mainfrom
RoyaLemonade:pr2/rpc-timeouts
Open

RoyaLemonade wants to merge 5 commits into
ompweb-dev:mainfrom
RoyaLemonade:pr2/rpc-timeouts

Conversation

@RoyaLemonade

Copy link
Copy Markdown
Contributor

Bun port of #325, supersedes #325. Rebased onto current origin/main (shared-daemon lifecycle).

What

  • Control and passthrough commands share one bounded path: at most 32 may wait on a child (else session_busy), and an expired wait answers session_slow instead of hanging the request.
  • The error carries maybeStarted (the frame is already in omp's stdin, so the message may still run) or abortUnconfirmed (Stop may have landed) — the client stops rolling back and resending, and the outbox marks such an entry as possibly-sent instead of "Not sent".
  • A timeout no longer recycles the child. Only a child with no frame and no command answer for five minutes is disposed, and that disposal goes through destroyAndWait(..., stopShared=true) so a daemon-owned child is really stopped, recorded as exited.detail: "stalled".
  • 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, and a child the watchdog disposed answers the dead state (with its stalled exit record) instead of a busy 503.
  • A timed-out new_session/switch_session fences commands until a state read reconciles which conversation the child serves, so a later command cannot act through a stale wrapper identity.

Why

A busy omp blocks its event loop for tens of seconds on large sessions. Recycling it ended a live run and lost the prompt outcome; the client also needs alive/session_slow to tell "busy" from "gone".

Review follow-ups (this push)

  • State body read once: the 503 busy branch in hooks/useAgentSession.ts re-read stateRes.json() after the request had already parsed it; the second read threw and a busy chat became an HTTP 503 load failure. The code now comes from the parsed body.
  • Outbox uncertainty: refused honours the wrapper's explicit maybeStarted, so a session_slow ack timeout (HTTP 400) fails as possibly-sent.
  • Watchdog honesty: destroyIfStalled stops the child with stopShared; it no longer only detaches membership while claiming the child was stopped.
  • Identity fence: a timed-out session switch keeps commands fenced until get_state reconciles the identity.
  • Dead state after disposal: both routes answer running:false, alive:false when the watchdog disposed the child; the sessions-state route includes the detail:"stalled" exit record.
  • running migration: hook Slow-mode consumers read alive (falling back to running for servers that do not send it), so an idle live child keeps its session-scoped support.
  • Dropped unrelated payloads: goal types/passthrough, notification-answer helpers, the ownership helper, the unhandled-rejection policy change, reminder i18n strings, the ?systemPrompt=0 option (that is feat(sessions): navigation-only reads, context ETag and a prompt-less state #415) and the RunAgentCommandOptions refactor.

Tests

  • bun test --timeout 30000 lib/rpc-manager.test.mjs — 166 pass.
  • bun test --timeout 30000 lib/message-outbox.test.mjs lib/agent-command.test.mjs — 68 pass.
  • bun test --timeout 30000 hooks/useAgentSession.rpc.test.mjs — 253 pass.
  • bun test --timeout 30000 server/routes.test.ts — 5 pass.
  • npm run typecheck clean; npm run lint clean on every changed file.
  • Mutation probes (each reverted): stopShared → false fails the watchdog test; removing the identity fence fails the switch test; dropping maybeStarted from the outbox classification fails the uncertain-delivery test; re-reading the state body fails the busy-chat hydration test.
  • New coverage: busy-chat hydration through the hook against a real Response (a second read throws there), outbox session_slow with/without maybeStarted, the watchdog's stopShared + stalled exit record, the identity fence, and a transport-boundary deadline assertion replacing the previous source-string check.
  • Known: lib/rpc-manager.test.mjs + lib/message-outbox.test.mjs in one process show 4–5 failures in host-tool/adoption tests. The same files on unmodified origin/main fail identically (verified), so it is pre-existing cross-file fixture interference, not this change. Each file passes alone.

Reopened as a new PR: #408 was closed automatically when its branch ref was briefly recreated during the review update (GitHub does not allow reopening it). Review history and the follow-up reply are on #408.

@coderabbitai

coderabbitai Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 16 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 814ef48e-b31c-40cb-b2b1-005989e1509d
Commits

Reviewing files that changed from the base of the PR and between 165fe04 and 3ceadab.

Files selected for processing: 19

  • AGENTS.md
  • CHANGELOG.md
  • app/api/agent/[id]/route.ts
  • app/api/agent/new/route.ts
  • app/api/sessions/[id]/state/route.ts
  • hooks/useAgentSession.rpc.test.mjs
  • hooks/useAgentSession.ts
  • lib/agent-client.ts
  • lib/agent-command.test.mjs
  • lib/agent-command.ts
  • lib/i18n/locales/en.json
  • lib/i18n/locales/ja.json
  • lib/i18n/locales/zh-CN.json
  • lib/message-outbox.test.mjs
  • lib/message-outbox.ts
  • lib/rpc-manager.test.mjs
  • lib/rpc-manager.ts
  • lib/session-routes.test.mjs
  • scripts/link-hol-probe.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@kilo-code-bot

kilo-code-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Code Review Roast 🔥

Verdict: 1 Issue Found | Recommendation: Address before merge

Overview

Severity Count
🚨 critical 0
⚠️ warning 1
💡 suggestion 0
🤏 nitpick 0
Issue Details (click to expand)
File Line Roast
lib/rpc-manager.ts 2395 The timed-out identity read answers host_offline based on linkLostDuring, a host-link check that says nothing about whether the session switched — a linked host that pinged after the command went down gets "the run continues there" while the wrapper holds a stale _sessionId.

⚠️ The one thing to fix: The fence in refreshIdentityAfterSessionChange fires on the host link, not on the switch outcome being unknown. linkLostDuring is the same check every other timeout site uses to excuse a wedged child; here it excuses the exact wrong-conversation hazard this function exists to prevent. Set identityStale and answer session_slow on any timeout, and only reach for host_offline when the link genuinely dropped.

📊 Overall: Like a seatbelt that fastens but then unfastens itself in a crash — the fence logic is the right idea, but it's checking the wrong sensor.

Files Reviewed (19 files)
  • lib/rpc-manager.ts - 1 issue
  • hooks/useAgentSession.ts - 0
  • app/api/agent/[id]/route.ts - 0
  • app/api/agent/new/route.ts - 0
  • app/api/sessions/[id]/state/route.ts - 0
  • hooks/useAgentSession.rpc.test.mjs - 0
  • lib/agent-client.ts - 0
  • lib/agent-command.test.mjs - 0
  • lib/agent-command.ts - 0
  • lib/i18n/locales/en.json - 0
  • lib/i18n/locales/ja.json - 0
  • lib/i18n/locales/zh-CN.json - 0
  • lib/message-outbox.test.mjs - 0
  • lib/message-outbox.ts - 0
  • lib/rpc-manager.test.mjs - 0
  • lib/session-routes.test.mjs - 0
  • scripts/link-hol-probe.ts - 0
  • AGENTS.md - 0
  • CHANGELOG.md - 0
Previous Review Summary (commit a2dbac9)

Current summary above is authoritative. Previous snapshots are kept for context only.

Previous review (commit a2dbac9)

Verdict: 3 Issues Found | Recommendation: Address before merge

Severity Count
🚨 critical 0
⚠️ warning 1
💡 suggestion 1
🤏 nitpick 1
Issue Details (click to expand)
File Line Roast
hooks/useAgentSession-notices.ts 74 Dismissed notices linger in pending and get resurrected into the visible queue on the next notice retirement — "dismissed" means "come back later".
lib/rpc-manager.ts 2382 The session-switch fence clears on any successful state read, even one naming the old conversation, so a late-landing switch leaves commands acting through a stale identity onto the new conversation.
CHANGELOG.md — A release-note entry ("A failed run no longer shows its error three times") was deleted from the changelog; deleted lines can't take an inline comment, so it's summary-only.

🏆 Best part: The timeout contract is genuinely well thought through — a busy child stays alive instead of getting recycled mid-run, and a Response body is finally read exactly once rather than twice. Oh wait, part of this is actually clean. I need to sit down.

💀 Worst part: Dismissed notices rising from the dead in hooks/useAgentSession-notices.ts — a UI that forgets a dismissal is one step from gaslighting its users.

📊 Overall: Like a second pancake — the batter finally cooked through, but one side is still stuck to the pan.

Files Reviewed (17 files)
  • CHANGELOG.md - 1 issue (summary-only)
  • hooks/useAgentSession-notices.ts - 1 issue
  • lib/rpc-manager.ts - 1 issue
  • app/api/agent/[id]/route.ts - 0
  • app/api/agent/new/route.ts - 0
  • app/api/sessions/[id]/state/route.ts - 0
  • hooks/useAgentSession.rpc.test.mjs - 0
  • hooks/useAgentSession.ts - 0
  • lib/agent-client.ts - 0
  • lib/agent-command.test.mjs - 0
  • lib/agent-command.ts - 0
  • lib/i18n/locales/en.json - 0
  • lib/i18n/locales/ja.json - 0
  • lib/i18n/locales/zh-CN.json - 0
  • lib/message-outbox.test.mjs - 0
  • lib/message-outbox.ts - 0
  • lib/rpc-manager.test.mjs - 0

Fix these issues in Kilo Cloud


Reviewed by free · Input: 2.2M · Output: 146.9K · Cached: 4M

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.
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.
…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.
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.
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.
@RoyaLemonade

Copy link
Copy Markdown
Contributor Author

Follow-up at 3ceadab. Rebased onto current main with a semantic merge in hooks/useAgentSession.ts (main's terminal/current-run error handling is kept byte-identical; this branch's maybeStartedRunRef/runUnclaimedRef are layered on it), plus fixes found in our own pre-review:

  • The stall watchdog counts an unanswered streak, cleared by any frame or any command answer, instead of time since the last frame. An idle child that sends nothing for hours is no longer disposed on its first timeout.
  • A switch/new session whose post-ack identity read times out sets the identity fence and answers session_slow; if the link dropped meanwhile it answers host_offline. It no longer leaves a stale identity or a bare 500. A dead child is reported as gone, not slow.
  • set_host_tools/set_host_uri_schemes stay unbounded as on main, so a late ack still records the names.
  • A busy 503 on load no longer produces "The agent stopped without returning a response" for a run this tab did not dispatch, while a run this tab did dispatch keeps that notice.
  • New hook tests: a prompt answered session_slow + maybeStarted keeps its message, stays locked and is never resent; a Stop answered abortUnconfirmed warns once and is not retried (atomic and fallback path). Deleting either client branch fails its test.
  • lib/session-routes.test.mjs expectation updated (alive), scripts/link-hol-probe.ts accepts both codes, CHANGELOG/AGENTS entries.

@kilo-code-bot kilo-code-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test

Comment thread lib/rpc-manager.ts
// 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");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test comment

@kilo-code-bot kilo-code-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incremental review of the identity-fence, stall-watchdog, and run-error notice work.

Comment thread lib/rpc-manager.ts
// 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");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔥 The Roast: You finally added a fence for the timed-out identity read — good. But the timeout branch still answers host_offline based on linkLostDuring, which checks lastUplinkAt. That's the same host-link check used to excuse every timeout elsewhere, and it has nothing to do with whether the session switched. A linked host that sent a heartbeat after the command went down gets "the run continues there" while the wrapper is actually holding a stale _sessionId — the exact wrong-conversation hazard this whole function exists to prevent. The fence should fire on the switch outcome being unknown, not on the host link.

🩹 The Fix: On a timeout here, set this.identityStale = true and throw slowSessionError(), and reserve host_offline for when the link genuinely dropped. The child runs on either way; the only question is whether the identity is settled.

📏 Severity: warning

@andrebrait

Copy link
Copy Markdown
Collaborator

Hi @RoyaLemonade, thank you for your contribution, and apologies for the long wait on this PR. We really appreciate the time and effort you have put into it.

We are working through a major refactor of ompweb, including switching to our own build of omp. We are close to finishing that work; once the refactor is complete, we will turn our attention back to the pending PRs, including this one.

Thank you for your patience and for helping improve ompweb!

@kahme247

Copy link
Copy Markdown
Collaborator

Hi, thanks for this PR. It currently conflicts with main and can't be merged as-is — please rebase it onto current main and resolve the conflicts. Once it's rebased I'll re-run the checks.

After the rebase this still needs a first maintainer review — it's a core-path change (+434/−61 in lib/rpc-manager.ts) — and reconciliation with #415's agent/state contract.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants