Skip to content

Hibernate completed runtime-owned agents - #5473

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/investigate-memory-usage
Jun 16, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/investigate-memory-usage

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Teach agent hibernation to consider fresh runtime-backed PTY liveness by worktree, so completed resumable agents are not missed when renderer ptyIdsByTabId is empty.
  • Add a fail-closed exact-stop path for runtime-owned terminals: fresh liveness is required, the live PTY set must match the expected PTY, and sleep-visible state is committed only after post-stop verification succeeds.
  • Preserve SSH/remoting safety by routing daemon/remote shutdown through exact runtime stops, keeping history checkpoints, synthesizing runtime exits for ordinary kills, and cold-spawning slept remote runtime panes instead of reattaching preserved dead handles.

Design and review

  • Design doc: .agents/tmp/agent-hibernation-liveness-design.md (scratch pipeline context, intentionally not committed).
  • Design-review outcome: reviewed before implementation; retained the conservative all-or-nothing planner rule, fresh runtime liveness, typed RuntimeTerminalSummary.ptyId, exact-stop verification, and fail-closed handling for missing/error/truncated liveness.
  • Implementation completed against the design. Follow-up review findings were fixed around stale suppression, remote raw/wrapped PTY IDs, exact-stop proof handling, daemon history checkpointing, ordinary daemon kill runtime exits, and remote-runtime slept wake behavior.

Completeness verification

  • Runtime-backed planner candidates are covered when renderer live PTYs are missing.
  • Layout-only stale records, extra live PTYs, mobile-locked PTYs, truncated/error liveness, stop failures, and post-stop verification failures all stay fail-closed.
  • Store/coordinator exact hibernation precomputes sleeping records, suppresses expected exits during stop, rolls back on failure, and commits sleep state only after exact stop success.
  • Remote runtime wake now clears the stale preserved PTY binding and launches a fresh resumable shell.

Code review

  • Fresh two-reviewer review-code round completed after the final fixes.
  • Reviewer Darwin: No issues found.
  • Reviewer Erdos: No issues found.

Brennan test changes

Verdict: land.

Evidence:

  • Electron app identity verified on brennanb2025/investigate-memory-usage, root /Users/thebr/orca/workspaces/orca/horseshoe.
  • Local terminal.stopExact({ keepHistory: true }): before stop, both terminal.list(requireFreshPtyLiveness) and pty.listSessions showed the PTY live; stop returned postStopVerified: true; after stop, both lists were empty. This retested the prior blocker.
  • Ordinary local daemon-backed pty.kill(..., { keepHistory: true }): before kill the PTY was live in runtime and PTY session lists; after kill both were empty.
  • SSH/remoting: disposable Linux Docker target orca-ssh-test-1781587136, repo /work/demo-project; Orca connected, relay deployed, remote repo/worktree created, remote PTY listed live, terminal.stopExact({ keepHistory: true }) returned postStopVerified: true, and after stop both runtime list and pty.listSessions were empty.
  • Cleanup completed: removed app SSH target, remote worktree/branch artifacts, Docker container, temp SSH keys, temp local demo clone, isolated Electron profile, and stopped the Electron app.

Tests

  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts -t "cold-spawns slept remote runtime PTYs|remote runtime PTY handles|restored encoded remote"
  • pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty.test.ts -t "ordinary daemon-backed pty kill|stopAndWait"
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-hibernation-coordinator.test.ts src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts src/renderer/src/store/slices/store-cascades.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/runtime-rpc.test.ts src/main/ipc/pty.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/terminal-host.test.ts src/main/daemon/daemon-pty-adapter.test.ts (11 files, 918 tests)
  • pnpm run typecheck:node
  • pnpm run typecheck:web
  • pnpm run typecheck:cli
  • pnpm run typecheck
  • pnpm run lint
  • pnpm exec oxlint $(git diff --name-only)
  • pnpm build:relay
  • git diff --check

Assumptions and residual risk

  • Agent hibernation remains gated by the existing hibernation setting and conservative all-or-nothing worktree eligibility.
  • Exact runtime hibernation currently requires a single live expected PTY; multi-PTY worktrees remain skipped rather than risk stopping unknown shells.
  • No product-authored agent prompt/workflow text was added.

Open in Stage

@ghost

ghost commented Jun 16, 2026 •

Copy link
Copy Markdown

@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4f7ad1d6-05bd-4c5c-a176-32b707b4d9d7

📥 Commits

Reviewing files that changed from the base of the PR and between 24d776d59bf784a549d70f712d1cfb0d65c80474 and faf934e.

📒 Files selected for processing (17)
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-provider.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/types.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration/groups.test.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/runtime-rpc.test.ts
🚧 Files skipped from review as they are similar to previous changes (15)
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-provider.ts
  • src/main/daemon/daemon-server.ts
  • src/main/runtime/orchestration/groups.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/runtime/runtime-rpc.test.ts
  • src/main/daemon/types.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/pty.test.ts
  • src/main/runtime/orca-runtime.test.ts

📝 Walkthrough

Walkthrough

This PR implements runtime-backed agent hibernation with exact PTY stop verification. The daemon IPC protocol is bumped to version 14 with an immediate flag added to KillRequest, propagated through TerminalHost.kill (branching to forceKillAndDisposeSubprocess), DaemonServer, DaemonPtyProvider, and DaemonPtyAdapter (which also performs a final history checkpoint when keepHistory is set). DaemonPtyRouter.listProcesses switches from Promise.allSettled to Promise.all. A new stopAndWait PTY controller method is added that shuts down a PTY, polls to confirm it stopped, then emits runtime.onPtyExit. The runtime service gains stopExactTerminalsForWorktree (which refreshes PTY liveness, verifies the live set exactly matches expected IDs, calls stopAndWait, then re-verifies post-stop) and listTerminals gains requireFreshPtyLiveness filtering. RuntimeTerminalSummary gains a ptyId field and a terminal.stopExact RPC method is added. The renderer hibernation planner gains runtime PTY ID normalization and liveness gating; the coordinator becomes async with tickInFlight guarding and collects fresh runtime liveness before planning. The store's shutdownWorktreeTerminals gains an exact-stop path that suppresses PTY exits during the stop window, calls terminal.stopExact, and merges sleeping session records on success. Notification dispatch respects suppressed PTY IDs. A cold-spawn path is added for slept remote runtime PTYs on pane mount.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.22% which is insufficient. The required threshold is 80.00%. 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 'Hibernate completed runtime-owned agents' accurately reflects the main objective and primary change: enabling agent hibernation for runtime-owned agents with fresh PTY liveness consideration.
Description check ✅ Passed The description comprehensively explains the changes, design rationale, testing, and verification—it is clearly related to the changeset and provides meaningful context about the implementation.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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 and usage tips.

@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: 4

🧹 Nitpick comments (3)
src/main/daemon/daemon-pty-router.ts (1)

124-125: ⚡ Quick win

Add a short “why” comment for fail-closed aggregation.

This change is intentionally non-obvious (one adapter failure now rejects the whole call), so please document the rationale inline to prevent future regressions.

Suggested patch
   async listProcesses(): Promise<{ id: string; cwd: string; title: string }[]> {
+    // Why: runtime exact-stop/liveness flows must fail closed if any adapter
+    // cannot provide a trustworthy process list.
     const results = await Promise.all(this.allAdapters().map((adapter) => adapter.listProcesses()))
     return results.flat()
   }

As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

Source: Coding guidelines

src/renderer/src/lib/agent-hibernation-planner.test.ts (1)

180-210: ⚡ Quick win

Add a regression test where runtime liveness is empty but renderer PTY state is stale/non-empty.

Please add a case with runtimeLivenessRequiredWorktreeIds: ['wt-bg'], runtimeLivePtyIdsByWorktreeId: { 'wt-bg': [] }, and ptyIdsByTabId: { 'tab-1': ['pty-1'] } to assert no candidate is produced.

src/renderer/src/store/slices/terminals.ts (1)

1703-1735: 💤 Low value

Consider extracting the suppression rollback pattern.

The same rollback logic (set + loop deleting from suppressedPtyExitIds) appears three times in the exact-stop error handling paths. A small helper function would reduce duplication and make the intent clearer.

♻️ Suggested helper extraction
+  const clearSuppressedPtyExits = (ptyIds: string[]) => {
+    set((s) => {
+      const next = { ...s.suppressedPtyExitIds }
+      for (const ptyId of ptyIds) {
+        delete next[ptyId]
+      }
+      return { suppressedPtyExitIds: next }
+    })
+  }

Then each rollback becomes clearSuppressedPtyExits(shutdownPtyIds).


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 68b87ed1-8ff4-4b46-bd90-f71039b5965d

📥 Commits

Reviewing files that changed from the base of the PR and between 1ccc07c and 29090fdf20898c48f7320c223df960be9f480d54.

📒 Files selected for processing (29)
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-provider.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/types.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration/groups.test.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/runtime-rpc.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.ts
  • src/renderer/src/lib/agent-hibernation-coordinator.test.ts
  • src/renderer/src/lib/agent-hibernation-coordinator.ts
  • src/renderer/src/lib/agent-hibernation-planner.test.ts
  • src/renderer/src/lib/agent-hibernation-planner.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/renderer/src/store/slices/store-cascades.test.ts
  • src/renderer/src/store/slices/terminals.ts
  • src/shared/runtime-types.ts

Comment thread src/main/daemon/daemon-pty-adapter.ts Resolved
Comment thread src/main/ipc/pty.ts Resolved
@brennanb2025
brennanb2025 force-pushed the brennanb2025/investigate-memory-usage branch from 24d776d to faf934e Compare June 16, 2026 07:06
@brennanb2025
brennanb2025 merged commit ee8327d into main Jun 16, 2026
6 checks passed
@brennanb2025
brennanb2025 deleted the brennanb2025/investigate-memory-usage branch June 16, 2026 17:15
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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