Skip to content

fix(terminal): recover degraded daemon spawn routing - #12277

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/recover-degraded-pty-routing
Aug 3, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/recover-degraded-pty-routing

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Recover fresh terminal routing from the non-persistent local fallback when the preserved daemon can spawn PTYs again.
  • Revalidate the durable host before deriving session IDs, host environment, hooks, persistence, and terminal-handle semantics.
  • Preserve fresh-session intent for runtime-owned terminals with stable pre-minted IDs while keeping restored and stable-pane sessions on the explicit adoption/reattach path.
  • Forward owner-sensitive Git-guard and authoritative-buffer-snapshot capabilities after recovery so recovered daemon terminals remain parkable.
  • Coalesce concurrent probes and apply a 30-second retry cooldown after failures so degraded-mode terminal creation does not repeatedly pay the health timeout.
  • Keep existing fallback and daemon sessions on their original owners; SSH behavior is unchanged.
  • Avoid retaining recovered daemon ownership when a PTY exits before its spawn reply.

Root cause

After a transient PTY spawn-health failure, DegradedDaemonPtyProvider permanently routed every later fresh terminal to the local fallback until restart. Those non-persistent PTYs cannot participate in durable terminal parking, allowing hidden renderer panes and memory pressure to accumulate.

The design follows the existing durable-host ownership model: host readiness is revalidated authoritatively, the provider route changes once, and downstream consumers derive from that route. Renderer observation is not used as runtime truth.

Reliability contract

  • Invariant — agent-session.provider-ownership: fresh local spawns may switch back to the durable daemon only after authoritative health recovery; attach/adopt paths and already-owned fallback/daemon sessions keep their exact owner; an exited spawn reply must not recreate stale ownership.
  • Failure source: a transient daemon health timeout left all later fresh terminals on the non-persistent fallback until app restart, defeating parking and allowing hidden renderer/resource growth.
  • Oracle: deterministic tests force failed recovery, later recovery, concurrent probes, cooldown, stable-ID fresh creation, restored-session reattach, stable-pane adoption, owner-sensitive capability routing, hidden-at-spawn timing, and exit-before-spawn-reply ordering.
  • Gate: config/reliability-gates.jsonc → agent-session.provider-ownership.
  • Provider/platform coverage: local and daemon behavior are covered by provider/controller tests and macOS Electron evidence. SSH/remote recovery remains excluded by connectionId and existing owners remain provider-routed. WSL and folder workspaces use the shared main routing contracts. Linux and Windows are covered by CI unit/type/package and native-smoke jobs; live SSH/WSL recovery is an accepted gap.
  • Performance budget: recovery adds no polling, inventory scan, subprocess fanout, renderer wake loop, or unbounded cache. Concurrent probes share one promise; failed probes are suppressed for 30 seconds; successful recovery becomes a constant-time fast path. Tests assert one probe for concurrent callers and no repeat during cooldown.
  • Diagnostics: successful recovery emits one bounded daemon-routing log, and deterministic tests identify provider ownership, probe count, and early-exit cleanup.
  • Residual gaps: the production UI has no safe switch for forcing daemon degradation/recovery, so Electron evidence proves the real fresh-terminal surface and live PTY state while the transition itself remains a deterministic lower-layer oracle. Live SSH/WSL and Linux/Windows recovery journeys were not run.

Testing

  • 2,403 reliability-gate tests passed, 1 skipped.
  • 1,541 directly affected tests passed, 1 skipped.
  • Node typecheck passed.
  • Changed-file oxlint and oxfmt checks passed.
  • Max-lines ratchet and diff checks passed.
  • GitHub PR checks are green, including Node 24/26 shards, macOS/Linux/Windows native smoke, typecheck, Git compatibility, and packaging.

Coverage includes failed recovery, later recovery, concurrent probe coalescing, retry cooldown, daemon endpoint wiring, management warning state, runtime-controller ordering, renderer-IPC ordering, stable-ID fresh runtime creation, restored-session reattach, stable-pane adoption, Git-guard/snapshot capability routing, hidden-at-spawn timing, pane materialization deduplication, and exit-before-spawn-reply ownership cleanup.

Electron QA

Validated current HEAD d779e9d in the actual Orca dev app through CDP-only Electron automation on macOS.

  • Confirmed the intended amphipod worktree and branch identity.
  • Selected the PR workspace and used New tab → New Terminal.
  • Typed through the rendered xterm and visibly received the expected branch and HEAD.
  • Backing state reported two bound PTYs, two listed sessions, both live at 135×58, with zero renderer console errors.

PR #12277 Electron fresh-terminal validation

The degraded-to-recovered transition itself is covered by the deterministic recovery/provider tests because production Electron has no safe UI control for inducing that fault.

AI review report

The latest main branch was merged and conflicts in PTY spawn routing/runtime creation were reconciled without dropping stable-pane adoption or fresh-session recovery semantics.

A same-model, same-effort independent reviewer audited the full post-merge diff for correctness, ownership/reattach behavior, failure ordering, security, SSH/WSL/folder-workspace/cross-platform behavior, and performance. It found one material issue: a recovered daemon PTY that exited before its spawn reply could be reinserted into the session-provider map after the exit callback removed it, retaining stale ownership and memory. Commit d779e9d adds the liveness guard and regression test.

The reviewer reran the full diff after the fix and returned CLEAN with no remaining in-scope correctness, regression, security, cross-platform, SSH/folder-workspace, or performance findings.

Security audit

  • Reuses the existing authenticated local daemon health protocol and socket/token paths; no new IPC channel, network listener, command construction, or credential surface.
  • The recovery hook runs only for fresh native degraded spawns. SSH and restored/adopted reattach paths are excluded.
  • Owner-sensitive capabilities remain routed to the provider that owns each session.
  • No secrets or raw paths are added to logs.
  • No dependency changes.

Notes

  • Existing fallback-owned PTYs remain on the fallback because live PTY processes cannot be migrated safely between owners. Only later fresh spawns recover to the daemon.
  • This PR has no mobile UI changes, so mobile-emulator QA is not applicable.

@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Degraded daemon providers route fresh PTY spawns through a fallback until a current-daemon health probe succeeds. Recovery probes use retry backoff and coalesce concurrent requests. Existing sessions retain their recorded providers. Session discovery is shared across daemon adapters. Runtime and renderer PTY spawn paths await recovery before provider selection. New-session metadata distinguishes new sessions from reattachments. Degraded status reflects active local fallback routing.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% 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
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.
Title check ✅ Passed The title clearly and concisely describes recovery of degraded daemon spawn routing, which is the main change.
Description check ✅ Passed The description covers the summary, testing, AI review, security audit, platform risks, and Electron evidence with detailed validation results.
✨ Finishing Touches 💡 1
📝 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.

@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/daemon/degraded-daemon-session-routing.ts (1)

4-17: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Run adapter discovery concurrently to reduce startup latency.

discoverDegradedDaemonSessions awaits adapter.listProcesses() one adapter at a time inside the loop at line 10. daemon-init.ts awaits this function (await routedAdapter.discoverDaemonSessions()) before completing daemon initialization, so sequential RPCs add up when there is more than one adapter (current + legacy).

Run the per-adapter listing concurrently, for example with Promise.allSettled, while keeping the existing per-adapter try/catch and warning.

♻️ Proposed refactor for concurrent discovery
 export async function discoverDegradedDaemonSessions(
   adapters: readonly DaemonPtyAdapter[],
   sessionProviders: Map<string, IPtyProvider>
 ): Promise<void> {
-  for (const adapter of adapters) {
-    try {
-      for (const session of await adapter.listProcesses()) {
-        sessionProviders.set(session.id, adapter)
-      }
-    } catch (error) {
-      console.warn('[daemon] Failed to discover degraded daemon sessions', error)
-    }
-  }
+  await Promise.allSettled(
+    adapters.map(async (adapter) => {
+      try {
+        for (const session of await adapter.listProcesses()) {
+          sessionProviders.set(session.id, adapter)
+        }
+      } catch (error) {
+        console.warn('[daemon] Failed to discover degraded daemon sessions', error)
+      }
+    })
+  )
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 32f90d63-f6d3-49a7-953c-e44ff9e7c1cf

📥 Commits

Reviewing files that changed from the base of the PR and between 6f7a30a and 0e424f6.

📒 Files selected for processing (11)
  • src/main/daemon/daemon-init.test.ts
  • src/main/daemon/daemon-init.ts
  • src/main/daemon/degraded-daemon-fresh-spawn-routing.ts
  • src/main/daemon/degraded-daemon-pty-provider.test.ts
  • src/main/daemon/degraded-daemon-pty-provider.ts
  • src/main/daemon/degraded-daemon-session-routing.ts
  • src/main/ipc/pty-management.test.ts
  • src/main/ipc/pty-management.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/providers/pty-provider-contract.ts

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/daemon/degraded-daemon-fresh-spawn-routing.ts (1)

48-63: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Bound the recovery probe.

checkDaemonHealth has a finite timeout when it reaches the health socket, but probeCurrentDaemonSpawn is not required to timeout before calling recoverFreshSpawnRouting(). If a later implementation uses a custom probe that can hang, concurrent callers await this.recovery forever. Enforce a finite timeout around this.probeCurrent() and add a regression test for a never-settling probe.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 12ff8bfb-2b7c-4d1b-ab54-d5c7af7e462a

📥 Commits

Reviewing files that changed from the base of the PR and between 0e424f6 and 129549e.

📒 Files selected for processing (7)
  • src/main/daemon/degraded-daemon-fresh-spawn-routing.ts
  • src/main/daemon/degraded-daemon-pty-provider.test.ts
  • src/main/daemon/degraded-daemon-pty-provider.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
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/daemon/degraded-daemon-pty-provider.test.ts
  • src/main/daemon/degraded-daemon-pty-provider.ts
  • src/main/ipc/pty.test.ts

…degraded-pty-routing

# Conflicts:
#	src/main/ipc/pty.ts
#	src/main/runtime/orca-runtime.ts
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron reproduction and control validation

Validated in an isolated Orca dev profile attached through CDP to this exact PR branch.

Real degraded-state reproduction

  1. Created a daemon-backed terminal and wrote ORCA_DEGRADED_REPRO_SEED through the visible terminal.
  2. Restarted Electron while temporarily making only this worktree node-pty helper unavailable. The persistent daemon retained the live PTY and Orca entered degraded-new-pty-fallback with degraded: true.
  3. Restored the helper. The preserved terminal remained visible and writable.
  4. Created the next fresh terminal. The app logged PTY spawn health recovered; fresh terminals are daemon-backed, management changed to degraded: false, and the new terminal received a durable daemon session ID.

Preserved session while degraded:

degraded-preserved-session.png

Fresh daemon terminal after automatic recovery:

recovered-new-daemon-terminal.png

Old-latch reproduction versus daemon control

I then used a temporary uncommitted E2E health override to emulate the pre-fix permanent fallback latch. No override or source change remains in the branch.

  • Latched run: 2 preserved daemon terminals plus 22 fresh local-fallback terminals, 6x renderer CPU throttling, 4,000 then 5,000 deterministic lines per fallback, and rapid tab cycling.
  • Result: the visible terminal and main-owned headless snapshot both contained duplicated/out-of-order rows. App RSS grew from about 1.21 GB to 2.33 GB; worktree-session RSS grew from 29.6 MB to 357.6 MB. Delivery diagnostics recorded 2,054,823 hidden characters dropped from direct delivery and recovered through snapshots.
  • Control run: 25 daemon-backed terminals under the same output/throttling/cycling load.
  • Result: the visible frame and authoritative snapshot remained strictly sequential (4944 through 5000), with degraded: false.

Latched fallback artifact:

latched-fallback-cpu-throttled.png

Daemon-backed control:

daemon-pressure-control.png

This confirms the reported rendering corruption can be reproduced from the permanently latched fallback ownership state under scheduler pressure, and that returning fresh terminals to the durable daemon preserves authoritative snapshot ordering under the same stress.

Remaining boundary: if the daemon is genuinely still unable to spawn PTYs, Orca must continue using the local fallback. Extreme pressure can still expose the fallback snapshot weakness in that legitimately degraded state; this PR fixes the transient-health permanent latch without expanding into a separate fallback-output subsystem rewrite.

Cleanup completed: temporary source override removed, helper files restored, isolated terminal sessions and daemon processes stopped, and the worktree is clean.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron QA — PASS

Validated current HEAD d779e9d07b in the actual Orca dev app via CDP-only Electron automation on macOS.

  • Confirmed app identity: amphipod @ brennanb2025/recover-degraded-pty-routing.
  • Selected the PR worktree, then used the real New tab → New Terminal surface.
  • Typed through the rendered xterm and visibly received the expected branch and HEAD output.
  • Backing state reported 2 bound PTYs, 2 listed sessions, both live at 135×58; the renderer logged 0 console errors.

The degraded→recovered daemon transition has no production UI toggle, so that transition is covered by the deterministic recovery/provider tests and agent-session.provider-ownership gate rather than claimed from this screenshot.

PR #12277 Electron fresh-terminal validation

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Current-head AI review

The requested same-model and same-effort reviewer re-audited the PR after the origin/main merge and the additional d779e9d07b exited-before-reply cleanup.

  • Confirmed exited-before-reply sessions are not retained in degraded routing, matching DaemonPtyRouter semantics.
  • Confirmed merged stable-pane adoption avoids recovery for live reattach and recovers before genuine fresh fallback.
  • Confirmed SSH, folder-workspace, cross-platform, security, and cooldown-performance boundaries remain unchanged.
  • No scope expansion or additional fix was needed.

Validation at current head:

  • 1,494 focused tests passed, 1 skipped
  • Node typecheck passed
  • Changed-file lint and formatting passed
  • Max-lines and diff checks passed
  • Branch clean and synchronized

Final verdict: CLEAN.

@brennanb2025
brennanb2025 merged commit 866bcda into main Aug 3, 2026
48 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(terminal): recover degraded daemon spawn routing

* fix(terminal): preserve fresh-session recovery semantics

* fix(terminal): avoid retaining exited recovery sessions
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