Skip to content

fix(terminal): recover live panes after renderer restart (STA-3536) - #12776

Merged
brennanb2025 merged 5 commits into
mainfrom
brennan/sta-3536-terminal-pane-owner-unverified-error-on-latest-hourly-build
Aug 6, 2026
Merged

brennanb2025 merged 5 commits into
mainfrom
brennan/sta-3536-terminal-pane-owner-unverified-error-on-latest-hourly-build

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes restored terminal panes that reported terminal_pane_owner_changed after an Orca renderer restart even though their exact PTY was still alive.

Regression

Introduced by #11789 (fix: preserve live agent PTYs through graph hydration). That PR correctly made host/runtime-owned PTYs authoritative during graph hydration, but its ownership fence also treated a persisted-incarnation versus runtime-incarnation mismatch as an immediate conflict. After renderer restart or recovery, persistence can legitimately be one incarnation behind while the exact same PTY remains alive, so this affects release users rather than only development environments. Whether it appears depends on retained-pane state and recovery timing, which explains why the same RC may reproduce for one user but not others.

Root cause

Renderer recovery could load a persisted pane binding whose incarnation was stale while the same PTY ID remained live under its current daemon incarnation. The previous restore path successfully reached that exact PTY, then rejected the reattach because it treated the persisted incarnation as permanent runtime authority.

Startup process inventory was also being used too strongly. Other authenticated clients can create sessions after startup, and a failed or incomplete multi-daemon listing cannot prove that a session is absent.

Fix

  • Treat the runtime incarnation as authoritative and the persisted incarnation as a recovery hint.
  • Require an exact same-ID isReattach result, then repair stale persistence only after spawn admission succeeds.
  • Fence the repair with a host-, worktree-, tab-, leaf-, PTY-, and prior-incarnation compare-and-swap so a competing owner cannot be overwritten.
  • Publish the repaired in-memory incarnation only after the durable write succeeds.
  • Preserve repaired incarnations across renderer full-session snapshots and reloads by advancing the terminal topology fence.
  • Resolve daemon ownership with bounded, concurrent, coalesced inventory; unique positive evidence is routed, incomplete or duplicate evidence stays fail-closed.
  • Decode typed session-not-found responses. A sole provider's exact attach refusal can prove absence; multi-provider listing omission cannot.
  • Invalidate routes and brief fail-closed inventory caches on daemon identity changes, exits, and typed route refusal.

There is no sleep/retry ladder and no remote wire-format change. The new spawn options are internal main-process routing metadata and are not serialized. The implementation also preserves SSH host partitioning and folder-workspace behavior.

Validation

  • 1,263 focused daemon routing, provider, IPC, and persistence tests
  • TypeScript typecheck
  • Changed-code quality and type-aware quality gates
  • React Doctor
  • Max-lines ratchet
  • Reliability gate manifest
  • Desktop production build
  • Isolated Electron renderer-reload reproduction with the same PTY ID and an injected stale persisted incarnation; the live PTY reattached, persistence repaired to the live incarnation, and terminal input/output remained interactive without owner-change or owner-unverified errors
  • Two independent final senior reviews returned CLEAN

…s (STA-3536)

terminal_pane_owner_unverified fired for every restored pane whenever one
liveness probe answer went missing: a cold-start daemon draining an attach
stampede misses the 2s getSize deadline, and a wedged superseded daemon
(protocol upgrades leave them running) turns every unmapped fan-out probe
null forever.

- probePtyOwners now skips legacy daemons whose startup inventory listing
  succeeded: fresh sessions never route to them, so they provably don't own
  an unmapped id and one wedged zombie can't poison every pane's verdict.
- attachStablePaneOwner retries the probe over a short backoff ladder before
  surfacing unverified, so a single missed deadline resolves to a verdict.
- The renderer replaces the raw error code with actionable copy.
@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change centralizes PTY ownership resolution across daemon providers. It adds inventory caching, coalescing, incarnation matching, attach-only spawning, liveness probing, route invalidation, and startup reconciliation. Stable-pane recovery now uses persisted-incarnation fences and distinguishes unverified ownership from confirmed absence. Persistence rejects stale bindings and handles durability failures. RPC and local attach errors use typed errors. Terminal error toasts display localized retry guidance. Tests cover routing, recovery, persistence, and error handling.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the root cause, fix, and validation, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add all required template sections, state whether there is visual change, document testing checklist results, and summarize AI review, security audit, and platform risks.
✅ Passed checks (3 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 identifies the terminal recovery fix and the affected user scenario.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • 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 (2)
src/main/daemon/daemon-pty-liveness-probe.ts (2)

4-29: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Guard the empty-consulted case to avoid a vacuous-truth "dead" verdict.

If consulted ends up empty, results is []. results.every(...) returns true on an empty array (vacuous truth), so the function returns false ("confirmed dead") instead of null ("unknown"). A false verdict causes callers to retire and delete a persisted PTY owner.

Today, both call sites always keep the current daemon out of inventoriedOwners and always include it in possibleOwners, so consulted is never empty in practice. The function relies only on the doc comment ("Callers must never inventory the current daemon") to prevent this path, with no guard in the function itself. Add an explicit guard so the function stays correct even if a future caller violates that contract, or if possibleOwners is empty for another reason.

🐛 Proposed fix
   const consulted = inventoriedOwners
     ? possibleOwners.filter((provider) => !inventoriedOwners.has(provider))
     : possibleOwners
+  if (consulted.length === 0) {
+    return null
+  }
   const results = await Promise.all(consulted.map((provider) => provider.probePtyLiveness(id)))

4-29: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Guard the empty-consulted case to avoid a vacuous-truth "dead" verdict.

If consulted ends up empty, results is []. Array.prototype.every() returns true on an empty array (vacuous truth per ECMA-262), so the function returns false ("confirmed dead") instead of null ("unknown"). A false verdict causes callers, such as attachStablePaneOwner in pty.ts, to retire and delete a persisted PTY owner.

Today both call sites always keep the current daemon out of inventoriedOwners and always include it in possibleOwners, so consulted is never empty in practice. The function relies only on its own doc comment ("Callers must never inventory the current daemon") to prevent this path. There is no guard inside the function. Add an explicit guard so the function stays correct even if a future caller violates that contract, or if possibleOwners is empty for another reason.

🐛 Proposed fix
   const consulted = inventoriedOwners
     ? possibleOwners.filter((provider) => !inventoriedOwners.has(provider))
     : possibleOwners
+  if (consulted.length === 0) {
+    return null
+  }
   const results = await Promise.all(consulted.map((provider) => provider.probePtyLiveness(id)))

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f924dafc-4f90-434b-a344-d588ef5112ac

📥 Commits

Reviewing files that changed from the base of the PR and between 7f4570c and 6231700.

📒 Files selected for processing (11)
  • src/main/daemon/daemon-pty-liveness-probe.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.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.test.ts
  • src/main/ipc/pty.ts
  • src/renderer/src/components/terminal-pane/TerminalErrorToast.test.ts
  • src/renderer/src/components/terminal-pane/TerminalErrorToast.tsx
  • src/renderer/src/i18n/locales/en.json

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Live Electron validation (fresh isolated profile, this branch)

Ran the full failure sequence end-to-end in an isolated dev instance (ORCA_DEV_USER_DATA_PATH temp profile, CDP-driven, own daemon — production state untouched):

  1. Healthy baseline — repo added via IPC, terminal tab opened, daemon-backed PTY live.
  2. Simulated computer restart (killed the daemon between app sessions, exactly Jinjing's trigger): pane restored to a live shell, no error banner.
  3. Wedged legacy daemon (planted a half-open daemon-v31.sock that accepts connections but never answers — the unverifiable-from-boot case the fix deliberately does NOT auto-retire): pane shows the new actionable copy instead of the raw terminal_pane_owner_unverified code, after riding the full retry ladder.
  4. App restart with the wedge gone: stale v31 socket/token cleaned up at launch, pane recovered to a live shell.

One caveat verified live: a legacy adapter that was unreachable from startup stays conservative for the whole app session (remount alone doesn't clear it; app restart does). That matches #12393's "absence must be proven" principle — only a captured inventory authorizes skipping a daemon.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Post-review Electron QA — 09fe9878a6

Launched this exact PR worktree with an isolated ORCA_DEV_USER_DATA_PATH and CDP port, then verified the dev identity matched the STA-3536 branch.

  1. Created a real daemon-backed terminal and proved input/output on the reviewed commit.

Initial live terminal

  1. Flushed the persisted pane, stopped only the isolated app and daemon to simulate a reboot, relaunched the same profile, and typed through the restored terminal. The pane mounted and remained interactive; terminal_pane_owner_unverified was absent from the rendered UI.

Restored terminal interactive after restart

Review follow-up validation also passed: 525 focused tests, typecheck, native/type-aware lint, reliability manifest, and max-lines ratchet. A second same-model senior review returned CLEAN.

@brennanb2025 brennanb2025 changed the title fix(terminal): stop transient probe blips from erroring restored panes (STA-3536) fix(terminal): recover live panes after renderer restart (STA-3536) Aug 6, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final validation for 687656020d.

Exact Electron reproduction

  1. Launched the branch in an isolated Orca dev profile and created one daemon-backed terminal.
  2. Verified the live pane and printed STA3536-FINAL-BEFORE through the terminal UI.
  3. Preserved the exact worktree, tab, leaf, and PTY ID, but replaced its persisted incarnation with a fake stale UUID.
  4. Reloaded the renderer while leaving the PTY alive.
  5. Verified the pane exact-reattached, persistence repaired from the fake UUID to the live incarnation, the pre-reload scrollback remained, and STA3536-FINAL-AFTER executed interactively.
  6. Verified the UI contained no terminal_pane_owner_changed, terminal_pane_owner_unverified, or owner-unverified notification.

Before renderer reload:

sta3536-final-before.png

After renderer reload and persistence repair:

sta3536-final-after.png

Automated validation

  • Focused daemon/client/provider/router/IPC/persistence suite: 9 files, 1,263 tests passed
  • Final routing/cache regression suite after commit formatting: 3 files, 83 tests passed
  • TypeScript typecheck passed
  • Changed-code quality: 0 findings across 19 files
  • Type-aware quality: 0 findings
  • React Doctor: 0 findings
  • Max-lines ratchet passed
  • Reliability gate manifest passed
  • Desktop production build passed
  • Two independent final senior reviews of the latest tree: CLEAN

@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

🧹 Nitpick comments (4)
src/main/daemon/daemon-errors.test.ts (1)

10-12: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the decoded session identifier.

This test checks only the error class. It does not check that pty-1 remains in SessionNotFoundError.message. Add that assertion so the diagnostic contract is covered.

Suggested test update
-    expect(decodeDaemonResponseError('Session not found: pty-1')).toBeInstanceOf(
+    const error = decodeDaemonResponseError('Session not found: pty-1')
+    expect(error).toBeInstanceOf(
       SessionNotFoundError
     )
+    expect(error.message).toBe('Session not found: pty-1')
src/main/daemon/daemon-session-owner-resolution.ts (1)

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

Remove the unreachable owner branch in probe.

Line 144 returns true whenever candidatesBySessionId has any candidate for sessionId. So resolveInventory at Line 147 always runs with an empty candidate list. With no candidates, providers is empty, exactProvider and soleProvider stay undefined, and resolveInventory can only return unknown or absent. The kind === 'owner' branch at Lines 148-150 cannot execute.

Collapse the tail to the absent/unknown decision, or move the candidate short-circuit into resolveInventory if the routed-vs-other-owner distinction is still wanted.

♻️ Proposed simplification
     if ((inventory.candidatesBySessionId.get(sessionId)?.length ?? 0) > 0) {
       return true
     }
-    const resolution = this.resolveInventory(inventory, sessionId)
-    if (resolution.kind === 'owner') {
-      return resolution.provider === routed ? null : true
-    }
-    return resolution.kind === 'absent' ? false : null
+    return this.resolveInventory(inventory, sessionId).kind === 'absent' ? false : null
   }
src/main/daemon/daemon-session-owner-resolution.test.ts (1)

51-72: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Pin the clock in this test to remove a wall-clock dependency.

This test asserts that each of the 51 listProcesses mocks is called exactly once across 40 sequential resolve calls. That holds only while the incomplete-inventory cache stays valid. OWNER_INVENTORY_CACHE_MS and FAILED_PROVIDER_COOLDOWN_MS are both 1000ms and are compared against the real Date.now. If the 40 awaited iterations over 51 mocked providers take more than 1000ms on a loaded CI machine, the cache expires, a second inventory runs, and toHaveBeenCalledOnce fails.

Use the same Date.now spy pattern as the test at Lines 91-113 so the assertion depends only on call counts.

♻️ Proposed fix
   it('bounds restore inventory requests across many panes and daemon generations', async () => {
+    const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000)
     const inventories = Array.from({ length: 51 }, (_, index) =>
       vi.fn(async () => {
         if (index === 50) {
           throw new Error('offline')
         }
         return []
       })
     )
     const resolver = new DaemonSessionOwnerResolver(
       inventories.map((inventory) => provider(inventory)),
       new Map()
     )
 
-    for (let index = 0; index < 40; index += 1) {
-      await resolver.resolve(`pane-${index}`)
-    }
-
-    for (const inventory of inventories) {
-      expect(inventory).toHaveBeenCalledOnce()
+    try {
+      for (let index = 0; index < 40; index += 1) {
+        await resolver.resolve(`pane-${index}`)
+      }
+
+      for (const inventory of inventories) {
+        expect(inventory).toHaveBeenCalledOnce()
+      }
+    } finally {
+      clock.mockRestore()
     }
   })
src/main/ipc/pty.test.ts (1)

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

Make the per-attempt incarnation sequence explicit.

attachAttempt++ === 1 ? 'inc-wrong-owner' : 'inc-live-owner' encodes three distinct attempts in one counter expression. A reader must trace the post-increment and the call order to learn that attempt 1 returns inc-live-owner, attempt 2 returns inc-wrong-owner, and attempt 3 returns inc-live-owner again. An indexed list states the same contract directly.

♻️ Proposed refactor
-    let attachAttempt = 0
+    let attachAttempt = 0
+    // Attempt order: repair, superseded owner, repaired owner.
+    const incarnationsByAttempt = ['inc-live-owner', 'inc-wrong-owner', 'inc-live-owner']
     const providerSpawn = vi.fn(async (options: { attachOnly?: boolean; sessionId?: string }) => ({
       id: options.sessionId ?? 'unexpected-fresh-id',
-      incarnationId: attachAttempt++ === 1 ? 'inc-wrong-owner' : 'inc-live-owner',
+      incarnationId: incarnationsByAttempt[attachAttempt++] ?? 'inc-live-owner',

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 61c08075-569f-435d-8df9-4b025fdb79ed

📥 Commits

Reviewing files that changed from the base of the PR and between 09fe987 and 6876560.

📒 Files selected for processing (19)
  • src/main/daemon/client.ts
  • src/main/daemon/daemon-errors.test.ts
  • src/main/daemon/daemon-errors.ts
  • src/main/daemon/daemon-pty-adapter-subscription-fanout.ts
  • src/main/daemon/daemon-pty-liveness-probe.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/daemon-session-owner-resolution.test.ts
  • src/main/daemon/daemon-session-owner-resolution.ts
  • src/main/daemon/degraded-daemon-owner-recovery.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.test.ts
  • src/main/ipc/pty.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/pty-provider-contract.ts
💤 Files with no reviewable changes (2)
  • src/main/daemon/daemon-pty-liveness-probe.ts
  • src/main/daemon/degraded-daemon-session-routing.ts

Comment on lines +39 to +46
for (const id of result.alive) {
alive.push(id)
const providers = aliveProviders.get(id) ?? new Set<DaemonPtyAdapter>()
providers.add(adapter)
aliveProviders.set(id, providers)
}
killed.push(...result.killed)
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not spread result.killed into push.

Line 45 spreads result.killed into push. The equivalent loop in src/main/daemon/daemon-pty-router.ts Lines 246-253 explicitly avoids this and carries the reason: daemon startup can reconcile many restored sessions, and spreading those arrays into push can exceed the JavaScript argument limit. A large killed array then throws RangeError and aborts startup reconciliation.

result.killed is the set of sessions whose worktrees no longer validate, so it can be larger than result.alive after a bulk worktree cleanup. Use the same element-wise loop already used for alive.

🐛 Proposed fix
       for (const id of result.alive) {
         alive.push(id)
         const providers = aliveProviders.get(id) ?? new Set<DaemonPtyAdapter>()
         providers.add(adapter)
         aliveProviders.set(id, providers)
       }
-      killed.push(...result.killed)
+      // Why: spreading a large reconciliation result into push can exceed the argument limit.
+      for (const id of result.killed) {
+        killed.push(id)
+      }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for (const id of result.alive) {
alive.push(id)
const providers = aliveProviders.get(id) ?? new Set<DaemonPtyAdapter>()
providers.add(adapter)
aliveProviders.set(id, providers)
}
killed.push(...result.killed)
}
for (const id of result.alive) {
alive.push(id)
const providers = aliveProviders.get(id) ?? new Set<DaemonPtyAdapter>()
providers.add(adapter)
aliveProviders.set(id, providers)
}
// Why: spreading a large reconciliation result into push can exceed the argument limit.
for (const id of result.killed) {
killed.push(id)
}

@brennanb2025

Copy link
Copy Markdown
Contributor Author

CI follow-up: current head is 9b252d6566.

The only change after the Electron evidence and root-cause commit is a behavior-preserving extraction of the three identical attach abort guards so the new resolver satisfies the 300-line static-analysis limit without a suppression. Targeted oxlint is now clean, the resolver is exactly 300 lines, routing tests remain 83/83, typecheck passes, and the final same-model review returned CLEAN.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final CI status on 9b252d6566:

  • All 40 non-aggregate PR Checks jobs passed (Node 24/26 test shards, typecheck, packaging, Git compatibility, cross-version wire compatibility, shell contracts, and repository gates).
  • Native smoke passed on Ubuntu, macOS, and Windows.
  • static analysis / aggregate verify are red only because the merge result includes the current main file mobile/src/session/use-mobile-native-chat-controller.ts, which is independently over the 300-line lint limit. The check annotation points exclusively to that unrelated mobile file; this PR does not modify it. Current main is still 79896cb9a6, so rerunning would reproduce the same baseline failure.

The terminal changes have no remaining CI-owned failure. I intentionally did not expand this PR to edit unrelated mobile code.

@brennanb2025
brennanb2025 merged commit 81e7a2d into main Aug 6, 2026
49 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#12776)

* fix(terminal): stop transient probe blips from erroring restored panes (STA-3536)

terminal_pane_owner_unverified fired for every restored pane whenever one
liveness probe answer went missing: a cold-start daemon draining an attach
stampede misses the 2s getSize deadline, and a wedged superseded daemon
(protocol upgrades leave them running) turns every unmapped fan-out probe
null forever.

- probePtyOwners now skips legacy daemons whose startup inventory listing
  succeeded: fresh sessions never route to them, so they provably don't own
  an unmapped id and one wedged zombie can't poison every pane's verdict.
- attachStablePaneOwner retries the probe over a short backoff ladder before
  surfacing unverified, so a single missed deadline resolves to a verdict.
- The renderer replaces the raw error code with actionable copy.

* fix(terminal): stop retrying definitive owner probes

* fix(terminal): recover live panes after renderer restart

* refactor(terminal): share owner resolution abort guard
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