Skip to content

fix(runtime): resume terminal agents in headless serve after a daemon loss or sleep - #27527

Closed
outof-place wants to merge 1 commit into
stablyai:mainfrom
outof-place:fix/headless-agent-resume
Closed

outof-place wants to merge 1 commit into
stablyai:mainfrom
outof-place:fix/headless-agent-resume

Conversation

@outof-place

Copy link
Copy Markdown
Contributor

ELI5

When orca serve runs with no desktop window, a terminal agent (Claude Code, Codex, …) does not come back after the terminal daemon dies or after "Close Terminals". The tab returns, but as a plain shell, and the conversation is gone from the UI. The desktop app avoids this because its window keeps a small "how to resume this pane" record and starts claude --resume <id> when the pane starts again. This PR gives the headless host the same records and the same resume.

What Changed

Before: after a daemon loss (crash, reboot) the restored agent tabs are pending; opening one starts a bare shell, idle or mid-turn alike. A mid-turn agent also loses its session id, because the startup sweep (reapRestoredClaudeSubagentsWithoutLiveAgent) deletes hook rows whose PTY died. worktree.sleep does nothing without a window.

After, on a host with no renderer:

  • Resume on open. When session.tabs.activate starts a pending pane, the runtime looks for the pane's resume identity: its record in sleepingAgentSessionsByPaneKey, else its hook status row, in the renderer's cold-restore order. It launches the existing buildAgentResumeStartupPlan command through the same terminal creation as a new agent tab and passes resumeProviderSession. The resume only re-opens the conversation; nothing is sent to the agent. It does not resume a session whose agent already exited under its shell, nor a session captured on another host (the renderer's guard, moved to src/shared/agent-resume-origin-host.ts). A sleep record is spent by its resume.
  • One start per pane. A second open of a pane that is already starting waits for that start instead of spawning again.
  • Live anchors under serve. The renderer writes a live record per status update; under serve the host keeps the same records from status-row changes, in batches, and writes them synchronously before the startup sweep drops rows whose PTY died. A Claude SessionEnd that ends the process and a closed tab retire the pane's records. Nothing is written while an authoritative window exists, so the renderer stays the only writer on desktop.
  • Headless sleep. worktree.sleep with no notifier records each agent as worktree-sleep (finished panes lazy, as the renderer's manual sleep) and stops the PTYs through the existing sleepTerminalsForWorktree. Automatic activations stay refused while the sleep is held; a user open resumes.
  • Outcome for clients. The terminal tab carries an optional agentResume { agent, outcome } after the host started it: resumed, or unavailable when an agent ran in the pane but its session cannot be resumed here. The pane then opens as a plain shell, and a client can say so instead of showing a silent shell. A tab whose agent never ran keeps the [Bug]: Creating a Claude tab from mobile spawns it on the desktop, then reaps it ~10s later — mobile tab creation broken #7587 fresh launch.
  • Kill switch. ORCA_HEADLESS_AGENT_RESUME=0 restores today's behavior.

Why

The records and the resume command already exist and are what the desktop uses; the headless host was the only path without them, so this reuses them rather than adding a format. A window opened later reads the same records.

This builds on the approach of #23919 by @JustTalDevelops, which resumes a pending pane from the host's hook record. Thanks for that groundwork. This PR extends it to the panes that approach cannot reach: agents that were working or waiting at the crash (their rows are gone after the startup sweep), worktree sleep, and the anchors that keep the identity across restarts.

On the remote-server rework mentioned in #21743: the change is self-contained (two new runtime files, a mixin, and small hooks at the activation, sleep, close and startup call sites) and sits behind ORCA_HEADLESS_AGENT_RESUME, so it can be switched off or removed in one piece once the rework lands.

Trade-offs.

Gain Cost
CPU none under serve, one compare per status-row change; no work while a window owns the session
Session writes none measured with 5 agents, each taking a turn every 10 s (477 hook posts per minute): 47 to 48 workspace-session writes per minute; 0 while idle. Batching caps it at one write per second per worktree. Real turns are longer, so expect far fewer
Memory none one record per resumable agent pane in the workspace session, as on desktop
Merge risk desktop unchanged: every new write is gated on serve mode, no notifier, or no authoritative window activateMobileSessionTab now prefers a resume over the #7587 fresh launch when an identity exists, and serializes concurrent starts of the same pane
Maintenance resume rules restated once in agent-resume-records.ts, next to the renderer's two writers of the same record type (renderer on desktop, host under serve), kept apart by the window check

Linked Issue

Fixes #21743

Visual Proof

N/A: headless host, no UI. The before/after is the stand-in claude's recorded argv in the table below.

Testing

macOS only. SSH and Windows were not run: SSH origins go through the existing host-scope guard (unit-tested), and the command builder is the existing cross-platform one.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Manual check, on main 0df25b7 with and without this commit:

  • an isolated --serve runtime with E2E user data and home, a mock keychain, and a local-only loopback pin so nothing listens beyond 127.0.0.1;
  • a stand-in claude on PATH that records its argv;
  • hook events posted to the hook endpoint the way the managed hook does.

Agent A was idle (Stop), agent B mid-turn. Then: SIGKILL of the runtime and the daemon, relaunch, open both tabs (A twice at once); then worktree.sleep, an automatic activation, a user activation.

Step main this PR
open A after daemon loss (two concurrent opens) plain shell one claude --dangerously-skip-permissions --resume <A>
open B after daemon loss plain shell claude --dangerously-skip-permissions --resume <B>
worktree.sleep no-op, terminals stay terminals stopped, tabs pending
automatic activation after sleep refused (after terminal.sleep) refused
open A / B after sleep plain shell --resume <A'> / --resume <B>

Commands run on this branch:

  • pnpm run tc
  • ORCA_CODE_QUALITY_BASE=upstream/main pnpm run check:code-quality:changed
  • pnpm run build:electron-vite
  • pnpm run build:cli && pnpm run verify:built-skills-cli
  • node config/scripts/run-vitest.mjs run --config config/vitest.config.ts --maxWorkers=4 src/main/runtime src/main/startup src/main/agent-hooks src/shared plus the renderer host-scope, cold-restore and sleep-flow tests: 26430 passed, 2 failed. The 2 failures are run-terminal-shell-alone.node-pty.test.ts, which fails the same way on clean main (0df25b7) on this machine.
  • After rebasing onto 7dfa4d6: pnpm run tc, the changed-code gate, and the new tests plus orca-runtime.test.ts (1363 passed).

Not run: full pnpm lint, full pnpm test, pnpm build.

AI Disclosure

Claude Opus 5.5 (Claude Code) investigated, wrote the change and the tests, and ran the manual check above.

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security: no new RPC; the only wire change is the optional agentResume field. Records hold the same provider session ids the desktop already persists.
  • Mobile: a phone opening a restored tab on a headless host now gets the agent back, or an explicit unavailable.
  • Backward compatibility: records use the existing schema, so an older host or a desktop window reads them as its own. Old clients ignore the new optional field.
  • Size: about 820 source lines and 600 test lines; most of the source is the two new runtime files.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

🤖 Generated with Claude Code

… loss or sleep

A headless runtime (`orca serve`) had no renderer to keep resume records or
issue `--resume`, so a pane restored after the terminal daemon died came back
as a plain shell, and `worktree.sleep` did nothing.

- Starting a pending pane resumes its agent with the saved session id: the
  pane's sleeping record, else its status row, in the renderer's cold-restore
  order. A session that ended under its shell, or one captured on another
  host, is not resumed. A sleep record is spent by its resume.
- A second open of a pane that is already starting waits for that start, so
  one pane never starts two agents.
- Under serve, the host keeps the renderer's `live` resume anchors, written in
  batches (at most one session write per second per worktree, none when
  nothing changed) and synchronously before startup reaping drops rows whose
  PTY died with the daemon. A Claude SessionEnd that ends the process and a
  closed tab retire the pane's records.
- `worktree.sleep` with no renderer records each agent (`worktree-sleep`,
  lazy for finished panes) and stops the PTYs through the host's own sleep.
- The terminal tab carries `agentResume { agent, outcome }` after the host
  started it: `resumed`, or `unavailable` when an agent ran there but cannot
  be resumed here (the pane opens as a plain shell). A tab whose agent never
  ran keeps the fresh launch.
- The resume host-scope guard moves to shared so main uses the same rule.
- ORCA_HEADLESS_AGENT_RESUME=0 turns all of it off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

Walkthrough

The changes add host-side helpers and runtime logic to resolve and persist agent resume records without a renderer. Headless pane startup can use status rows or saved records to restore an agent, and terminal creation receives the resumed agent and provider-session metadata. Serve-mode startup synchronizes resume anchors. Mobile-session tabs can include whether an agent resumed or was unavailable.


Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to d5134

No confirmed behavior issue blocks merging. Whether every status-row removal safely retires its resume record remains unverified.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 43.48% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 19 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check Passed The title clearly identifies the primary change: resuming terminal agents in headless serve after daemon loss or sleep.
Description check Passed The description is complete and follows the required template. It explains the user impact, implementation, rationale, linked issue, testing, AI use, compatibility considerations, and known test limit…
Linked Issues check Passed Issue #21743 requires idle managed-agent panes on headless orca serve to resume after a runtime restart. The PR persists headless resume anchors, synchronizes them before startup reaping, resolves t…
Out of Scope Changes check Passed The added mid-turn handling, worktree sleep capture, close/session-end retirement, concurrent-open coordination, host checks, client outcome, tests, and kill switch support the same headless agent-res…

  • Fix all pre-merge checks with AI
  • 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

Comment @coderabbitai help to get the list of available commands.

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

🔇 Additional comments (20)
src/main/runtime/orca-runtime-perform-mobile-session-pty-records-refresh.ts (2)

164-176: Begin the in-flight registration before the first await, or every exit path must call finishMaterialization.

beginPaneMaterialization is called synchronously after joinPaneMaterialization, so the concurrent-open guard holds. Two code paths still need checks:

  • Line 194: when resolvePaneAgentResumeStartup returns an unavailable plan, agentResume is non-null. The code then skips the tab.launchAgent re-resolve. The pane opens as a plain shell, which is the intended result.
  • Lines 177-204: if resolveTerminalWorkspaceLaunchScope throws, the inner try/catch swallows it. No await between line 176 and the try at line 205 can throw without that guard. The only exception is resolvePaneAgentResumeStartup, and the .catch on that call handles it.

The finally block always releases the entry, so the materialization is not leaked.


181-243: LGTM!

src/main/runtime/agent-resume-records.ts (1)

1-214: LGTM!

src/shared/agent-resume-origin-host.ts (1)

1-59: LGTM!

src/renderer/src/lib/sleeping-record-execution-host-scope.ts (1)

2-2: LGTM!

Also applies to: 8-8

src/main/runtime/agent-resume-records.test.ts (1)

1-181: LGTM!

src/main/runtime/headless-agent-resume-anchors.ts (1)

1-161: LGTM!

src/main/startup/main-process-runtime-service.ts (1)

180-192: LGTM!

src/main/startup/main-process-pty-startup.ts (1)

101-105: LGTM!

src/main/runtime/orca-runtime-headless-agent-resume.ts (1)

1-313: LGTM!

src/main/runtime/orca-runtime-create-runtime-owned-mobile-session-terminal.ts (1)

5-8: LGTM!

Also applies to: 64-64, 117-119

src/main/runtime/orca-runtime-list-managed-worktrees.ts (1)

208-217: LGTM!

src/main/runtime/orca-runtime-migration-catalog.ts (1)

16-21: LGTM!

src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts (1)

128-128: LGTM!

src/main/runtime/orca-runtime-headless-agent-resume.test.ts (1)

1-293: LGTM!

src/shared/runtime-mobile-session-tab-contracts.ts (1)

24-25: LGTM!

Also applies to: 36-40

src/main/runtime/runtime-mobile-session-projection-contract.ts (1)

10-10: LGTM!

Also applies to: 37-37

src/main/runtime/orca-runtime-prune-mobile-session-tab-group-layout.ts (1)

119-119: LGTM!

src/main/runtime/runtime-mobile-session-projection.ts (1)

292-292: LGTM!

Also applies to: 304-304

src/main/runtime/headless-agent-resume-anchors.test.ts (1)

99-99: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

⚠️ Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Remove the debug console.log from the test.

Line 99 prints output on every test run. This output adds noise to CI logs. The assertions already check the write budget.

Proposed fix
-    console.log(`anchor writes per minute, 5 agents: ${anchors.writes} for ${events} events`)

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a1defa57-6440-4092-af15-f23714f48342
📥 Commits

Reviewing files that changed from the base of the PR and between 7dfa4d6 and d51347b.

📒 Files selected for processing (19)
  • src/main/runtime/agent-resume-records.test.ts
  • src/main/runtime/agent-resume-records.ts
  • src/main/runtime/headless-agent-resume-anchors.test.ts
  • src/main/runtime/headless-agent-resume-anchors.ts
  • src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts
  • src/main/runtime/orca-runtime-create-runtime-owned-mobile-session-terminal.ts
  • src/main/runtime/orca-runtime-headless-agent-resume.test.ts
  • src/main/runtime/orca-runtime-headless-agent-resume.ts
  • src/main/runtime/orca-runtime-list-managed-worktrees.ts
  • src/main/runtime/orca-runtime-migration-catalog.ts
  • src/main/runtime/orca-runtime-perform-mobile-session-pty-records-refresh.ts
  • src/main/runtime/orca-runtime-prune-mobile-session-tab-group-layout.ts
  • src/main/runtime/runtime-mobile-session-projection-contract.ts
  • src/main/runtime/runtime-mobile-session-projection.ts
  • src/main/startup/main-process-pty-startup.ts
  • src/main/startup/main-process-runtime-service.ts
  • src/renderer/src/lib/sleeping-record-execution-host-scope.ts
  • src/shared/agent-resume-origin-host.ts
  • src/shared/runtime-mobile-session-tab-contracts.ts

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

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.

[Bug]: headless orca serve never captures sleeping-agent records, so idle agent panes are not resumed after a restart

1 participant