Skip to content

fix(agent-hooks): save a pane's turn changes within a second so a crash or Relaunch keeps idle mail flowing - #47887

Merged
Jinwoo-H merged 8 commits into
mainfrom
fix/save-hook-turn-edges
Nov 24, 2026
Merged

Jinwoo-H merged 8 commits into
mainfrom
fix/save-hook-turn-edges

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Refs #45906, #41143

Problem

After Orca restarts, an idle Claude terminal can stop receiving orchestration mail. The sender sees "Orca can't notify the agent … with the evidence it has", and the mail waits until the agent works again.

  • How status comes back: an idle Claude prints nothing after a reattach, so Orca learns it is at rest only from the pane's last hook report saved in last-status.db (restoreReattachedAgentStatus).
  • Why that report is old: since perf(agent-hooks): save agent status as per-pane SQLite rows, every few minutes #39995, saved hook rows are written at most every 3 minutes unless a pane's launch token changes, and a normal quit writes the rest. A turn's Stop is not a launch-token change, so it waits.
  • When it is lost: an exit that skips the normal quit loses it: a crash, a force kill, the in-app Relaunch (app:relaunch calls app.exit(0)), or the update-install watchdog.
  • Result: the restart restores the earlier SessionStart row, or none. That row does not count as idle, Claude has no screen rule to fall back on, and the pane stays unverified.

Fix

  • Turn changes save within a second. When a pane's lead turn changes (idle, working, waiting on permission, or no turn), that pane's row is saved within a second. This uses the same hookLeadTurnState reading that restore uses.

  • Only the panes whose turn changed are written. Other panes' pending updates (tool events, prompt text, replies) stay with perf(agent-hooks): save agent status as per-pane SQLite rows, every few minutes #39995's 3-minute batch, so the saved row is still the one source of truth.

  • The batch keeps its own clock. Turn-change saves never postpone it, and a failed batch is retried as a full batch.

  • Coalescing: turn changes are combined to at most one save per second. A single change after a quiet spell saves at once.

  • Authority saves are unchanged: launch-token changes still save everything immediately.

  • Moves: hookLeadTurnState moves unchanged to src/shared/agent-status/lifecycle/hook-lead-turn-state.ts, and buildStatusFile moves unchanged into server-status-file.ts to keep files under the size cap.

  • Tests: server-turn-edge-persistence.test.ts uses fake timers and covers three cases:

    • a turn change saves at 1 s, and only for that pane;
    • the batch still runs while turn changes keep arriving;
    • a failed batch is retried as a batch.

    Each case fails when its part is reverted.

Verification

Isolated dev Orca with its own profile and HOME, with real Claude Code 2.1.330 (Sonnet). Steps: one short turn in a Claude pane, a restart that keeps the terminal host (daemon) running, then mail 10 s later, watched for 90 s.

Restart main (ed88fc21704) this PR
In-app Relaunch held, 2 of 2 delivered in 4 s, 2 of 2
SIGKILL of the main process (crash) held, 2 of 2 delivered in 4 s, 2 of 2 (saved row was the turn's Stop)
Normal quit delivered in 4 s delivered in 4 s

In a dev build, Relaunch exits through the same app.exit(0) as production, but the respawned dev process does not stay up, so the rig starts the app again after that exit.

Performance

Same rig, 10 minutes per run, with stand-ins posting Claude's real hook events through the installed hook script.

  • 24 agents: about 90 turns per minute, much busier than real use.
  • 5 agents, realistic: turns of about 50 s with a tool call every 6 s, then 45–105 s idle.

Disk numbers are bytes written by every Orca process (Electron main, helpers, renderer, daemon), from proc_pid_rusage.

24 agents, main 24 agents, PR 5 agents, main 5 agents, PR
Whole-app disk writes 1.28 MB/min 2.02 MB/min 0.23 MB/min 0.27 MB/min
Added by this PR +0.74 MB/min (44 MB/h) +0.04 MB/min (2.4 MB/h)
last-status.db saves 0.3/min 60/min 0.3/min 5/min
Rows per save 24 3.0 6 1.2
WAL written 16 KB/min 690 KB/min 7 KB/min 23 KB/min
Main-thread time in saves 0.15 ms/min 14 ms/min 0.11 ms/min 1.1 ms/min
Event-loop delay p50 / worst-minute p99 1.16 / 1.70 ms 1.16 / 1.62 ms 1.17 / 1.45 ms 1.17 / 1.71 ms
Typing round trip p50 (CLI send to screen) 996 ms 920 ms 882 ms 864 ms
Printing 300k lines in a pane 327–359 ms 307–323 ms 317–328 ms 305–324 ms
  • Responsiveness: event-loop delay, typing and output rendering show no change beyond run-to-run noise. The typing round trip is mostly CLI overhead, so it only catches large changes.
  • Against perf(agent-hooks): save agent status as per-pane SQLite rows, every few minutes #39995: that PR removed about 120 MB/hour of rewrites. At the busiest load this adds back about a third of that (44 MB/h). At the realistic load it adds about 2% (2.4 MB/h).
  • SSD endurance: a full day of the 24-agent load adds about 1 GB. A small 256 GB Mac SSD is rated for roughly 150 TB of writes, so that would take centuries to matter. The realistic load adds about 60 MB a day.

Risk

  • Writes scale with turns: writes now follow how often agents start and finish turns, capped at one save per second. Tool events don't add writes.
  • Small crash window: a crash within a second of a turn change can still lose that change. Before, the window was up to 3 minutes.
  • Coverage: this fixes the restore input only. Mail to a pane whose saved report is truly gone is still held, as before.
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​94 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​94
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​284 $\color{#cf222e}{\Huge{\mathbf{−}}}$​171 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​113

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The change moves lead-turn state classification to a shared lifecycle module and uses it to detect authority and turn edges in restored server state. Persistence now separates turn-edge saves from full status batches and applies a distinct throttle to turn-edge saves. Status-file construction moves to AgentHookServerStatusFile. New tests cover turn-edge writes and continued full-batch persistence.

Merge Risk: Minimal · previous review fe4b5

Turn changes are now saved within about a second, so idle panes keep their orchestration mail after a restart. Full status batches keep their three-minute schedule, and a failed batch is retried as a whole batch. No concrete merge-blocking risk remains.

Pre-merge checks: Passed 3 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description follows the repository template closely. It covers ELI5-style problem and fix framing, What Changed (turn-edge saves within one second, pane-scoped writes, batch clock kept separate), … 1) Replace 'Refs #45906, #41143' with a 'Fixes #' line that links an actual issue, or confirm the linked issue requirement is satisfied for this contributor. 2) Add the Risk level (Low, Medium, or High) under 'Level:'. 3) State the back…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title names the main change: turn changes for a pane are saved within a second so a crash or Relaunch keeps idle mail flowing. This matches the raw summary, which adds turn-edge persistence with a…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: turn changes for a pane are saved within a second so a crash or Relaunch keeps idle mail flowing. This matches the raw summary, which adds turn-edge persistence with a 1,000 ms interval, and the PR objectives, which describe the same fix. The title uses the conventional fix(scope) prefix and is a single sentence. It is long at 107 characters, but it stays specific.

Full details: Description check

Explanation

The description follows the repository template closely. It covers ELI5-style problem and fix framing, What Changed (turn-edge saves within one second, pane-scoped writes, batch clock kept separate), Why (restart loses the last hook report saved in last-status.db), Linked Issue (refs #45906 and #41143, but no 'Fixes #' issue link), Visual Proof (N/A is not written; a before/after table of real-Claude restart results is given instead), Testing (test file named with three cases and a real-Claude verification rig, but the template checkboxes are not ticked), Performance (detailed measurements and a trade-off discussion), Risk (crash window, write scaling, coverage limits, with a risk level missing), and AI Disclosure (not filled in, which is acceptable for an external contributor only if not required). Missing or incomplete items: the Linked Issue section uses 'Refs' rather than an actual 'Fixes #' link, which the template says is required for outside contributors; the Risk section lacks the Level: value and does not say how to back the change out (plain revert or what it would not undo); the Review and Agent skill upstream boundary sections are not addressed; the template checklist is not ticked; and the AI Disclosure section is blank.

Resolution

  1. Replace 'Refs #45906, #41143' with a 'Fixes #' line that links an actual issue, or confirm the linked issue requirement is satisfied for this contributor. 2) Add the Risk level (Low, Medium, or High) under 'Level:'. 3) State the back-out path: a plain revert, and note anything a revert would not undo, such as already-written rows in last-status.db. 4) Complete the AI Disclosure section, or confirm it does not apply. 5) Address the 'Agent skill upstream boundary' checkbox. 6) Tick the testing and checklist items that were completed, and note the platforms tested (macOS was used for the rig, but Linux, Windows, and SSH coverage is not mentioned).
Finishing Touches

Fix failing CI checks

  • Commit to this branch
  • Create a new PR
  • 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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a33bd0ab-f762-4436-b76f-58a53cd3b916
Commits

Reviewing files that changed from the base of the PR and between 5d7f57a and fe4b529.

Files selected for processing: 1

  • src/main/agent-hooks/server/testing/persistence/server-turn-edge-persistence.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nitpick comments: 1

src/main/agent-hooks/server/testing/persistence/server-turn-edge-persistence.test.ts: 1

47-47: Trivial · Maintainability & Code Quality · Quick win

Use a controllable clock to check both persistence intervals.

The fixed 1500-ms delay does not deterministically check the background scheduler. The 3000-ms polling timeouts also let a two-second turn save pass a test named “within a second.”

Advance a controllable clock across the 1000-ms boundary. Check the saved turn after the scheduled work completes. Then advance beyond that boundary for a same-turn update and check that the saved prompt remains unchanged.

Based on learnings, fixed delays do not synchronize with asynchronous background completion; a controllable clock is an accepted alternative.

Source: Learnings

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 13f3cfc8-e2b9-4878-9537-126b6dc767e4
Commits

Reviewing files that changed from the base of the PR and between ab304f7 and 94f82e4.

Files selected for processing: 8

  • src/main/agent-hooks/server/server-constants.ts
  • src/main/agent-hooks/server/server-persistence.ts
  • src/main/agent-hooks/server/server-state.ts
  • src/main/agent-hooks/server/status-restored-state.ts
  • src/main/agent-hooks/server/testing/persistence/server-turn-edge-persistence.test.ts
  • src/main/runtime/terminal/output/terminal-buffer-operations.ts
  • src/main/runtime/terminal/wait/tui-idle-hook-lane.ts
  • src/shared/agent-status/lifecycle/hook-lead-turn-state.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit nitpick in bdc15e0: the test now uses fake timers and checks the save at exactly 999 ms (not yet) and 1000 ms (saved), then that a same-turn update stays unsaved 60 s later, and that a turn change after a quiet spell saves at once. It still fails when turn-change saving is reverted.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1e0bbe7f-8fb0-40f7-9a14-d668603c769e
Commits

Reviewing files that changed from the base of the PR and between bdc15e0 and d12d3c9.

Files selected for processing: 5

  • src/main/agent-hooks/server/server-persistence.ts
  • src/main/agent-hooks/server/server-state.ts
  • src/main/agent-hooks/server/server-status-file.ts
  • src/main/agent-hooks/server/status-restored-state.ts
  • src/main/agent-hooks/server/testing/persistence/server-turn-edge-persistence.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@Jinwoo-H
Jinwoo-H merged commit b5b84ae into main Nov 24, 2026
57 checks passed
Luoqiu1 added a commit to Luoqiu1/orca that referenced this pull request Nov 26, 2026
Main now saves a lead's turn-state edge within a second (stablyai#47887) and
moved the status file build and row-cache types out of the files this
branch changed. This branch drops its own immediate full save: prompt,
turn-opening and completion facts that leave the lead's turn state as it
was now count as turn edges, so they take main's one-second save of the
edged rows. The persist-cadence tests main already covers are removed,
and the rest wait for that window.

The BLOB key read is dropped: Node 24 in the shipped Electron reads NUL
keys whole (only Node 22 truncated them), so its test passed without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

1 participant