Repository navigation
fix(agent-hooks): deliver hook events that fire while Orca is restarting (STA-5329) - #16685
Conversation
bab3b6e to
140701b
Compare
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review. 📝 WalkthroughWalkthroughPOSIX agent hook scripts now spool events when hook context is unavailable or HTTP delivery fails. Spool records use bounded JSONL storage with launch-token validation and safe concurrent draining. Agent hook and relay servers reconstruct and replay valid records during startup. Replay events receive dedicated status and runtime-observation handling. Codex state reconciliation preserves omitted root prompts across lifecycle updates. Tests cover serialization, malformed records, token fencing, restart replay, unavailable receivers, outside-Orca execution, and provider-specific event filtering. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed and covers the change, motivation, linked issue, testing, platform scope, limitations, and compatibility considerations. Some template sections are not explicitly completed, but the required technical context is mostly complete. ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/codex/hook-service.ts (1)
851-863: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winTreat HTTP error responses as failed delivery. All seven POSIX hooks use curl’s exit status to select
spool_hook_event, but curl returns success for HTTP 4xx/5xx responses unless--failis set. Add--failto each POST command, includingpost_codex_hook, so rejected events reach the spool fallback on native and WSL paths.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 40e45904-7bfd-4084-bede-d012e0b57d54
📒 Files selected for processing (16)
src/main/agent-hooks/hook-script-outside-orca.test.tssrc/main/agent-hooks/hook-stdin-contract.tssrc/main/agent-hooks/server.tssrc/main/agent-hooks/spool.test.tssrc/main/agent-hooks/spool.tssrc/main/antigravity/hook-script.tssrc/main/claude/hook-service.tssrc/main/codex/hook-service.tssrc/main/command-code/command-code-managed-script.tssrc/main/copilot/copilot-managed-script.tssrc/main/cursor/hook-service.tssrc/main/devin/hook-service.tssrc/main/droid/hook-service.tssrc/main/gemini/hook-service.tssrc/main/grok/grok-hook-script.tssrc/main/kimi/hook-service.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| ' { printf \'\\n{"paneKey":"%s","tabId":"%s","worktreeId":"%s","env":"%s","version":"%s","launchToken":"%s","source":"%s","receivedAt":%s,"payload":\' "$(spool_json_escape "${ORCA_PANE_KEY:-}")" "$(spool_json_escape "${ORCA_TAB_ID:-}")" "$(spool_json_escape "${ORCA_WORKTREE_ID:-}")" "$(spool_json_escape "${ORCA_AGENT_HOOK_ENV:-}")" "$(spool_json_escape "${ORCA_AGENT_HOOK_VERSION:-}")" "$(spool_json_escape "${ORCA_AGENT_LAUNCH_TOKEN:-}")" "$(spool_json_escape "'.concat( | ||
| source, | ||
| '")" "$spool_now"; printf "%s}\\n" "$payload"; } >> "$spool_file" 2>/dev/null || :' | ||
| ) | ||
| return [ | ||
| 'spool_hook_event() {', | ||
| ' case "$payload" in *\'"PreToolUse"\'*|*\'"PostToolUse"\'*|*\'"PostToolUseFailure"\'*) return 0 ;; esac', |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Preserve the provider event name. Antigravity gets its event name from ORCA_ANTIGRAVITY_EVENT, not payload, so PreToolUse is spooled and replay lacks the hookEventName sent by the live POST; pass and serialize the provider event name before filtering.
| try { | ||
| const fd = openSync(candidate.path, 'r+') | ||
| try { | ||
| // Keep the inode so a concurrent append handle cannot silently orphan writes. | ||
| ftruncateSync(fd, 0) | ||
| } finally { | ||
| // fstat keeps the descriptor operation observable in tests and documents the inode contract. | ||
| fstatSync(fd) | ||
| closeSync(fd) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Prevent loss during concurrent spool writes. ftruncateSync can erase an append that occurs after readSpoolRecords completes; use a shared writer/drainer lock or acknowledged offset protocol before truncation.
- claude: pass the literal source; options.agent does not exist (typecheck) - kimi: the windows-local ordering runs its guard pre-stdin and before the function exists, so it no longer spools there (printed command-not-found) - writer: require a readable endpoint file before creating a spool tree - antigravity: carry its out-of-band event name into the record and filter on it - drain: truncate only the bytes consumed, preserving concurrent appends and a torn trailing line
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0abbc80d-8951-4707-9fa3-c56ce6af1f0b
📒 Files selected for processing (6)
src/main/agent-hooks/hook-script-outside-orca.test.tssrc/main/agent-hooks/hook-stdin-contract.tssrc/main/agent-hooks/spool.tssrc/main/antigravity/hook-script.tssrc/main/claude/hook-service.tssrc/main/kimi/hook-service.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
Windows high-spec + WSL POSIX-hook validation (STA-5329)Isolated Writer works. While the receiver was down, the real POSIX Codex hook inside Ubuntu-24.04 spooled a Drain ingest does not apply writer-shaped records. Replay left the child row in Production code was not changed. Full notes: Before restart (working Codex + worker child)After restart (spool drained, child still present — idle/hydrate, not settled)Contrast: live HTTP SubagentStop after restart (child gone) |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 5d58b3bb-3f78-4f9b-904c-cf88571f1b25
📒 Files selected for processing (5)
src/main/agent-hooks/server.tssrc/main/agent-hooks/spool.test.tssrc/relay/agent-hook-server.test.tssrc/relay/agent-hook-server.tssrc/shared/agent-hook-spool.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
Windows high-spec + WSL POSIX-hook re-validation (STA-5329) —
|
|
Review complete for PR #16685. Final pushed SHA: What changed during review:
Verification:
CI:
Residual risk (non-blocking): the pre-existing in-place spool compaction algorithm has a very narrow append-after- The older comment documenting the pre-fix failure at |
|
Additional real-agent validation completed at exact SHA
All runs used disposable profiles/endpoints. Original user hook/config files were restored and verified byte-for-byte, temporary auth copies and harnesses were removed, and no branch files changed. |
…ing (STA-5329) (stablyai#16685) * fix(agent-hooks): correct durable spool delivery * fix(agent-hooks): spool curl failures after retries * fix(agent-hooks): keep replay out of runtime observations * test(agent-hooks): pin managed hooks inert outside an Orca terminal * fix(agent-hooks): address review findings on the durable spool - claude: pass the literal source; options.agent does not exist (typecheck) - kimi: the windows-local ordering runs its guard pre-stdin and before the function exists, so it no longer spools there (printed command-not-found) - writer: require a readable endpoint file before creating a spool tree - antigravity: carry its out-of-band event name into the record and filter on it - drain: truncate only the bytes consumed, preserving concurrent appends and a torn trailing line * fix(agent-hooks): ignore spool events without pane attribution * fix(agent-hooks): make spool replay and appends robust * test(agent-hooks): type spool replay records * fix(agent-hooks): defer unterminated spool records * fix(agent-hooks): replay spool events through relays * fix(agent-hooks): preserve Codex prompt across child replay * fix(relay): keep startup alive when spool replay fails * fix(relay): simplify spool replay startup guard (cherry picked from commit aaef5e8)
Codex fails closed on a hook whose stdout is not valid JSON, so every session started from an Orca terminal reported "invalid session start/stop hook JSON output" even though the POST to Orca's listener succeeded (stablyai#16356). The managed Codex script never wrote anything to stdout. Its siblings all do: claude (stablyai#14818), gemini, copilot and antigravity each emit neutral JSON as the first line, before any early-exit guard. Codex was the only one without it. Rebased onto the module split from stablyai#17260: the builder moved from hook-service.ts to codex-hook-script.ts, so the two lines land there instead. hook-script-outside-orca.test.ts (added in stablyai#16685, after this PR was opened) asserted the managed Codex hook stays silent outside an Orca terminal. Silence is exactly the failure stablyai#16356 reports, and every sibling hook already prints "{}" unconditionally, so the stdout assertions now expect the neutral JSON. The inertness those tests really guard - exit 0, empty stderr, no spool tree written - is unchanged and still asserted.
…ing (STA-5329) (stablyai#16685) * fix(agent-hooks): correct durable spool delivery * fix(agent-hooks): spool curl failures after retries * fix(agent-hooks): keep replay out of runtime observations * test(agent-hooks): pin managed hooks inert outside an Orca terminal * fix(agent-hooks): address review findings on the durable spool - claude: pass the literal source; options.agent does not exist (typecheck) - kimi: the windows-local ordering runs its guard pre-stdin and before the function exists, so it no longer spools there (printed command-not-found) - writer: require a readable endpoint file before creating a spool tree - antigravity: carry its out-of-band event name into the record and filter on it - drain: truncate only the bytes consumed, preserving concurrent appends and a torn trailing line * fix(agent-hooks): ignore spool events without pane attribution * fix(agent-hooks): make spool replay and appends robust * test(agent-hooks): type spool replay records * fix(agent-hooks): defer unterminated spool records * fix(agent-hooks): replay spool events through relays * fix(agent-hooks): preserve Codex prompt across child replay * fix(relay): keep startup alive when spool replay fails * fix(relay): simplify spool replay startup guard
Codex fails closed on a hook whose stdout is not valid JSON, so every session started from an Orca terminal reported "invalid session start/stop hook JSON output" even though the POST to Orca's listener succeeded (stablyai#16356). The managed Codex script never wrote anything to stdout. Its siblings all do: claude (stablyai#14818), gemini, copilot and antigravity each emit neutral JSON as the first line, before any early-exit guard. Codex was the only one without it. Rebased onto the module split from stablyai#17260: the builder moved from hook-service.ts to codex-hook-script.ts, so the two lines land there instead. hook-script-outside-orca.test.ts (added in stablyai#16685, after this PR was opened) asserted the managed Codex hook stays silent outside an Orca terminal. Silence is exactly the failure stablyai#16356 reports, and every sibling hook already prints "{}" unconditionally, so the stdout assertions now expect the neutral JSON. The inertness those tests really guard - exit 0, empty stderr, no spool tree written - is unchanged and still asserted.
Codex fails closed on a hook whose stdout is not valid JSON, so every session started from an Orca terminal reported "invalid session start/stop hook JSON output" even though the POST to Orca's listener succeeded (stablyai#16356). The managed Codex script never wrote anything to stdout. Its siblings all do: claude (stablyai#14818), gemini, copilot and antigravity each emit neutral JSON as the first line, before any early-exit guard. Codex was the only one without it. Rebased onto the module split from stablyai#17260: the builder moved from hook-service.ts to codex-hook-script.ts, so the two lines land there instead. hook-script-outside-orca.test.ts (added in stablyai#16685, after this PR was opened) asserted the managed Codex hook stays silent outside an Orca terminal. Silence is exactly the failure stablyai#16356 reports, and every sibling hook already prints "{}" unconditionally, so the stdout assertions now expect the neutral JSON. The inertness those tests really guard - exit 0, empty stderr, no spool tree written - is unchanged and still asserted.
Codex fails closed on a hook whose stdout is not valid JSON, so every session started from an Orca terminal reported "invalid session start/stop hook JSON output" even though the POST to Orca's listener succeeded (stablyai#16356). The managed Codex script never wrote anything to stdout. Its siblings all do: claude (stablyai#14818), gemini, copilot and antigravity each emit neutral JSON as the first line, before any early-exit guard. Codex was the only one without it. Rebased onto the module split from stablyai#17260: the builder moved from hook-service.ts to codex-hook-script.ts, so the two lines land there instead. hook-script-outside-orca.test.ts (added in stablyai#16685, after this PR was opened) asserted the managed Codex hook stays silent outside an Orca terminal. Silence is exactly the failure stablyai#16356 reports, and every sibling hook already prints "{}" unconditionally, so the stdout assertions now expect the neutral JSON. The inertness those tests really guard - exit 0, empty stderr, no spool tree written - is unchanged and still asserted.





ELI5
When an agent finishes a turn it tells Orca over a tiny local HTTP call. If Orca happens to be restarting at that moment, nobody is listening, the message is thrown away, and the sidebar keeps showing "working" forever. This makes the agent write that message to a file instead, and Orca reads it on next launch.
What Changed
Writer (shared, 11 POSIX providers).
buildPosixHookSpoolLinesinagent-hooks/hook-stdin-contract.tsadds aspool_hook_eventshell function, wired into antigravity, claude, codex, command-code, copilot, cursor, devin, droid, gemini, grok and kimi. It runs only on failure paths: the missing-endpoint guard, and a POST that failed after the Windowscurl.exeretry. Nothing is written when the POST succeeds.Per-pane JSONL beside the endpoint file (
<endpointDir>/spool/pane-<id>.jsonl), path derived in-script fromORCA_AGENT_HOOK_ENDPOINTso it follows the WSL-guest and SSH-remote relocations automatically. Leading newline per record so a torn write costs exactly one line. 5 MB cap and a 7-day mtime truncate, both enforced by the writer. Tool-progress events (PreToolUse/PostToolUse/PostToolUseFailure) are skipped — highest volume, largest payloads, worthless to replay.Drain (
agent-hooks/spool.ts, wired inserver.ts). Runs at startup before the listener binds, so replay cannot race a live hook. Each record is re-ingested through the existingingestRemotepath withisReplay: true, which already suppresses the side effects that must not re-fire.Why
The completion hook is fire-and-forget with no retry. Verified on a dev build rather than assumed:
curl: (7) Failed to connect— the event ceases to exist.PORT/TOKENare still set and the script's existing guard does not fire. This is why spooling has to happen on the curl-failure path, not only when the endpoint is missing.workingwith the subagent stillworking.This repairs delivery rather than guessing after the fact. A delivered event carries its own launch token, so nothing has to infer which agent generation a pane holds — an inference that is not soundly possible once the event is lost.
Three safety properties, each pinned by a test:
SubagentStopclears a newer generation's row and overwrites the pane's authority hash.runtimeObservedStatusPaneKeys. Without this, downtime-era evidence marks a pane runtime-observed and permanently masks both the liveness sweep and transcript confirmation — re-creating this very bug through the replay path.Linked Issue
Fixes STA-5329
Visual Proof
N/A — no UI surface changes. The visible effect is an existing sidebar row reaching its correct state instead of remaining
working; there is no new or altered component.Testing
src/main/agent-hooks/spool.test.ts(6) andhook-script-outside-orca.test.ts(3). Fullsrc/main/agent-hooks/suite: 74 files, 732 passed, 6 skipped. oxfmt + oxlint clean on all 16 changed files.Both critical tests were confirmed to fail before their fix by reverting the production file and re-running — real assertion failures, not import errors:
does not mark a non-terminal downtime replay as runtime-observed→expected true to be falsespools when the endpoint is present but the receiver is unavailable→ fails against the pre-fix scriptManaged hooks run outside Orca too (they live in the user's agent config), so
hook-script-outside-orca.test.tsasserts exit status, stdout, stderr and that no files are created, across three cases: no Orca env, pane key without an endpoint, and an endpoint path that does not exist. All silent, exit 0, nothing written.Manual verification used an isolated dev instance with its own user-data profile.
Platforms: macOS verified end to end. WSL / SSH inherit the derived path but were not exercised. Windows — see below.
Not covered
cmdwriter is not implemented.cmdcannot capture stdin into a variable (the payload streams via--data-urlencode "payload@-"), so it needs the tee-to-temp-file approachclaude/statusline-script.tsalready uses. Windows agents get no spooling from this PR. Tracking separately.Relationship to #16538
Complementary, opposite halves of the same restart gap: this recovers terminal events that were lost, #16538 re-derives "still working" when no event fired at all. Neither subsumes the other. A trial merge shows one trivial import-line conflict; either can land first.
Two deliberate points of compatibility: replayed records pass
connectionId: nullso they are not excluded by that PR's local-only transcript predicate, and this PR stripsisReplayat persist time so replay provenance never survives another restart.