Repository navigation
fix(terminal): recover live panes after renderer restart (STA-3536) - #12776
Conversation
…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.
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/main/daemon/daemon-pty-liveness-probe.ts (2)
4-29: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winGuard the empty-
consultedcase to avoid a vacuous-truth "dead" verdict.If
consultedends up empty,resultsis[].results.every(...)returnstrueon an empty array (vacuous truth), so the function returnsfalse("confirmed dead") instead ofnull("unknown"). Afalseverdict causes callers to retire and delete a persisted PTY owner.Today, both call sites always keep the current daemon out of
inventoriedOwnersand always include it inpossibleOwners, soconsultedis 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 ifpossibleOwnersis 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 winGuard the empty-
consultedcase to avoid a vacuous-truth "dead" verdict.If
consultedends up empty,resultsis[].Array.prototype.every()returnstrueon an empty array (vacuous truth per ECMA-262), so the function returnsfalse("confirmed dead") instead ofnull("unknown"). Afalseverdict causes callers, such asattachStablePaneOwnerinpty.ts, to retire and delete a persisted PTY owner.Today both call sites always keep the current daemon out of
inventoriedOwnersand always include it inpossibleOwners, soconsultedis 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 ifpossibleOwnersis 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
📒 Files selected for processing (11)
src/main/daemon/daemon-pty-liveness-probe.tssrc/main/daemon/daemon-pty-router.test.tssrc/main/daemon/daemon-pty-router.tssrc/main/daemon/degraded-daemon-pty-provider.test.tssrc/main/daemon/degraded-daemon-pty-provider.tssrc/main/daemon/degraded-daemon-session-routing.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/renderer/src/components/terminal-pane/TerminalErrorToast.test.tssrc/renderer/src/components/terminal-pane/TerminalErrorToast.tsxsrc/renderer/src/i18n/locales/en.json
Live Electron validation (fresh isolated profile, this branch)Ran the full failure sequence end-to-end in an isolated dev instance (
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. |
Post-review Electron QA —
|
|
Final validation for Exact Electron reproduction
Before renderer reload: After renderer reload and persistence repair: Automated validation
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
src/main/daemon/daemon-errors.test.ts (1)
10-12: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the decoded session identifier.
This test checks only the error class. It does not check that
pty-1remains inSessionNotFoundError.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 valueRemove the unreachable
ownerbranch inprobe.Line 144 returns
truewhenevercandidatesBySessionIdhas any candidate forsessionId. SoresolveInventoryat Line 147 always runs with an empty candidate list. With no candidates,providersis empty,exactProviderandsoleProviderstayundefined, andresolveInventorycan only returnunknownorabsent. Thekind === 'owner'branch at Lines 148-150 cannot execute.Collapse the tail to the absent/unknown decision, or move the candidate short-circuit into
resolveInventoryif therouted-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 winPin the clock in this test to remove a wall-clock dependency.
This test asserts that each of the 51
listProcessesmocks is called exactly once across 40 sequentialresolvecalls. That holds only while the incomplete-inventory cache stays valid.OWNER_INVENTORY_CACHE_MSandFAILED_PROVIDER_COOLDOWN_MSare both 1000ms and are compared against the realDate.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, andtoHaveBeenCalledOncefails.Use the same
Date.nowspy 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 valueMake 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 returnsinc-live-owner, attempt 2 returnsinc-wrong-owner, and attempt 3 returnsinc-live-owneragain. 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
📒 Files selected for processing (19)
src/main/daemon/client.tssrc/main/daemon/daemon-errors.test.tssrc/main/daemon/daemon-errors.tssrc/main/daemon/daemon-pty-adapter-subscription-fanout.tssrc/main/daemon/daemon-pty-liveness-probe.tssrc/main/daemon/daemon-pty-router.test.tssrc/main/daemon/daemon-pty-router.tssrc/main/daemon/daemon-session-owner-resolution.test.tssrc/main/daemon/daemon-session-owner-resolution.tssrc/main/daemon/degraded-daemon-owner-recovery.tssrc/main/daemon/degraded-daemon-pty-provider.test.tssrc/main/daemon/degraded-daemon-pty-provider.tssrc/main/daemon/degraded-daemon-session-routing.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/persistence.test.tssrc/main/persistence.tssrc/main/providers/local-pty-provider.tssrc/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
| 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) | ||
| } |
There was a problem hiding this comment.
🩺 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.
| 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) | |
| } |
|
CI follow-up: current head is 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 |
|
Final CI status on
The terminal changes have no remaining CI-owned failure. I intentionally did not expand this PR to edit unrelated mobile code. |
…ied-error-on-latest-hourly-build
…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




Summary
Fixes restored terminal panes that reported
terminal_pane_owner_changedafter 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
isReattachresult, then repair stale persistence only after spawn admission succeeds.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