Repository navigation
fix(terminal): move the recovery ledger onto the tab row and gate it on observed outcome - #20025
Conversation
There was a problem hiding this comment.
Important
The direct-SSH snapshot merge path can still drop the recovery ledger on a routine host echo-back, restoring the fresh remount allowance this PR exists to eliminate. See the inline comment on remote-workspace-session-merge.ts.
Reviewed changes
Reviewed the move of the terminal pane recovery budget from module-level Maps onto the tab row as a TerminalTabRecoveryLedger field, and the switch from count-based to outcome-gated admission.
- Ledger on the row —
remountTerminalTabForRecoverynow writes the generation bump and the ledger in oneset(); the disposal-releaseunregisterblock and both module Maps are deleted. - Outcome-gated admission —
admitTerminalRecoveryRemountrefuses anunsettledre-request and asettled-failurewith the same reason until a new trigger (generation move or user Retry); the 3-per-5-min cap survives as a breadcrumb backstop. - Unified settle —
settleDirectSshPaneRetryAttemptis renamedsettlePaneAttachAttemptand settles both ledgers from one call, so the five existing failure points and the success path all settle recovery. viewModemirrored to the row — the OR'd chat-ownership guard collapses to a row-only read;patchTerminalTabRowgeneralizes the pin helper and serves all four toggles.- Host-rebuild preservation —
terminal-build.tsandremote-workspace-session-merge.tspreserverecovery, which is stripped from persistence (transient keys +buildSanitizedTabsByWorktree).
ℹ️ Nitpicks
reattach-result-handler.ts:167-170— the comment says the no-PTY-id and session-expired branches "settle themselves", but only the no-PTY-id branch settles (and only whensession.connectionIdis set); the session-expired branch leaves the ledgerpendingto age out. Worth tightening the wording so a reader doesn't expect a settle that doesn't happen.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| // Why: the recovery ledger is client-local and travels with generation — | ||
| // a remote snapshot that dropped it would hand the tab a fresh remount | ||
| // allowance on every republication, which is the storm again (b5cfc6ca). | ||
| ...(local.recovery ? { recovery: local.recovery } : {}) |
There was a problem hiding this comment.
recovery is only preserved when preserveNewerLocalTerminalFields runs, and that function is only reached when local.generation > remote.generation (the guard at line 166 uses <=). generation is persisted and echoed by the host while recovery is stripped, so on the direct-SSH echo-back (local.generation === remote.generation) the guard returns the remote row verbatim and drops the ledger. That restores the !ledger → ADMITTED fresh-remount allowance this PR exists to remove, and can wedge a pane that captured the pre-drop epoch (refused as stale-generation, no retry scheduled).
Technical details
# Preserve `recovery` on the direct-SSH snapshot echo-back, not just when local is strictly newer
## Affected sites
- `src/renderer/src/hooks/remote-workspace-session-merge.ts:21` — `recovery` preserved only inside `preserveNewerLocalTerminalFields`
- `src/renderer/src/hooks/remote-workspace-session-merge.ts:164-170` — the guard that returns the remote tab verbatim when `local.generation <= remote.generation`
## Why this happens
- `generation` round-trips: it is not stripped by `buildSanitizedTabsByWorktree` (`workspace-session.ts:212`) and `tabToRemote` keeps it (`remote-workspace-session-projection.ts:34-39`), so a local remount bump `N → N+1` is uploaded and echoed.
- `recovery` is stripped from persistence, so the host never carries it and the echo never restores it.
- `isSupersededLedger` uses strictly-forward `>` (`terminal-tab-recovery-ledger.ts:79`), so `N+1 === N+1` is not supersession — yet the merge's `<=` treats equality as remote-authoritative and drops the ledger.
## Required outcome
- The ledger must survive an echo that carries the client's own generation (`local.generation === remote.generation`); only a strictly-forward host move (`remote.generation > local.generation`) is a legitimate supersession that may drop it. This matches `terminal-build.ts:177`, which preserves `recovery` unconditionally when the row exists.
## Suggested approach
- Preserve `recovery` whenever `local.generation >= remote.generation` (i.e. also on equality), or hoist the `recovery` preservation out of the `local.generation > remote.generation` condition entirely.There was a problem hiding this comment.
Important
The direct-SSH echo-back still drops the recovery ledger — the prior finding is unaddressed, and the new client-local recovery ledger test does not pin it (see the inline comment). The rest of this commit is a correct fix for the chat-ownership guard.
Reviewed changes
Reviewed the delta since the prior review (64dbbfe → 19f4927): the viewMode persistence fix and the reverted chat-ownership guard.
- Persisted
viewModeon the terminal row —terminalTabSchemanow declaresviewMode, so the row survives the persist/parse boundary instead of readingundefinedafter a restart. - Re-read both indices for chat ownership — the guard in
requestTerminalPaneRecoveryreverts torow || unifiedTab, so a pre-existing session withviewModeonly on the unified tab still refuses to remount a hidden chat surface. - Pinned the only
successsettle —reattach-success-settle.test.tsasserts the settle and its placement past the no-PTY-id / session-expired branches; the settle comment was tightened to name which branches actually settle. - Added ownership + rebuild-preservation tests —
terminal-pane-surface-ownership.test.ts(including a real persist/parse round trip),mirrored-terminal-recovery-ledger.test.ts, and theclient-local recovery ledgerblock.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| } | ||
|
|
||
| it('survives a reconnect the host snapshot knows nothing about', () => { | ||
| const local = terminalTab('agent', { generation: 1, recovery: ledger }) |
There was a problem hiding this comment.
The recovery ledger is still dropped on the direct-SSH echo-back, and this test reads as covering that without driving it. local carries generation: 1 while the remote tab carries none, so the merge takes the local.generation > remote.generation branch and reaches preserveNewerLocalTerminalFields. The echo-back case (local.generation === remote.generation) is never exercised — there, the <= guard at remote-workspace-session-merge.ts:166 returns the remote row verbatim and drops recovery, which is stripped from persistence while generation round-trips.
Technical details
# The new test misses the echo-back case where the ledger is actually dropped
## Affected sites
- src/renderer/src/hooks/remote-workspace-session-merge-local-survival.test.ts:398 — remote tab carries no `generation`, so only the `>` branch runs
- src/renderer/src/hooks/remote-workspace-session-merge.ts:166 — `(local.generation ?? 0) <= (tab.generation ?? 0)` returns the remote row verbatim on equality, dropping `recovery`
## Why this happens
- `generation` round-trips: not stripped by `buildSanitizedTabsByWorktree` (`workspace-session.ts:203`), kept by `tabToRemote` (`remote-workspace-session-projection.ts:34`).
- `recovery` is stripped by `buildSanitizedTabsByWorktree` before upload (`remote-workspace-target-sync.ts:195` exports `buildWorkspaceSessionPayload`).
- A recovery remount that bumps `N → N+1` is echoed back with `generation: N+1` and no `recovery`; the `<=` guard treats equality as remote-authoritative.
## Required outcome
- The test must drive `local.generation === remote.generation` (both carry the bumped generation) and assert `recovery` survives, or the merge must preserve `recovery` on `>=` rather than only `>`.
## Suggested approach
- Add a case with `terminalTab('agent', { generation: 1 })` on BOTH sides, expecting `merged.tabsByWorktree[WORKTREE][0].recovery` to equal the ledger. Then fix the merge: preserve `recovery` whenever `local.generation >= remote.generation`, or hoist the preservation out of the strict-newer condition.…on outcome The recovery budget lived in module-level Maps keyed by tabId. Anything keyed outside the row needs a release path, and that release fired on every remount-driven pane disposal, so each remount erased the budget it had just consumed (crash b5cfc6ca). Put the ledger on TerminalTab and write it in the same set() as the generation bump: reading the budget is now reading the tab, so releasing it independently has no expression. Counting was also the wrong control. Every remount mounts a pane that captures a FRESH recovery epoch, so the epoch check can never refuse its request — recovery re-requested the exact action that had just failed with no evidence anything changed. Gate on an observed outcome instead, reusing the direct-SSH pane retry vocabulary (success | failed | timed-out | superseded) and its settle call sites: an unsettled attempt blocks the next one, and a settled failure refuses the same reason until a new trigger arrives (generation move, or the user's Retry). The 3-per-5min cap stays as a breadcrumb-emitting backstop, not the control. viewMode now also lands on the row from the local toggles, mirroring how pin already does it, so the chat-ownership guard reads one index instead of OR-ing two.
…p reads The narrowed chat-ownership guard read a field the session schema strips: terminalTabSchema never declared viewMode, so the terminal row lost it on every load while the unified tab kept it. After a restart the row read undefined and recovery would remount a chat-owned tab's hidden surface — the race #19745's guard exists to prevent. Declare viewMode on terminalTabSchema so the row is durable, and keep the disjunction rather than replacing it. The schema cannot retroactively add the field to sessions already on disk, so the first load after upgrade still has it only on the unified tab; and for a safety check over two partly-redundant sources, a hole in either index should err toward declining a heal. Also cover three structural guards that no test was holding: both remote ledger-carry paths (terminal-build, remote-workspace-session-merge) and the only success settle in the state machine, including its placement past the failure branches.
19f4927 to
61f0a10
Compare
|
Too many files changed for review (1000 files, 100 file limit). |
… guard across a reload spawn-left-pane-unbound was the one recovery reason with no success settle: its remount heals by spawning, not reattaching, so it reached none of the reattach settle points and left the attempt 'pending' for the full 31s bound. A fresh spawn that binds a PTY now reports it, the dual of the unbound settle that already reported failure. Two tests outside src/ still called remountTerminalTabForRecovery by its old boolean contract and broke CI; both are updated to the admission result. Also strips the client-local recovery ledger at the remote-workspace projection boundary, in the type as well as the destructure, so a future producer cannot put another machine's Date.now() on the wire.
📝 WalkthroughWalkthroughThe change adds a terminal-tab recovery ledger with admission, generation tracking, cooldowns, caps, and settlement outcomes. PTY attach, reattach, spawn, and retry paths now report recovery results through shared settlement APIs. Recovery state remains client-local across session projection, merges, and mirrored tab rebuilds. Terminal row view mode and pin state now stay synchronized with unified tabs. Tests cover ledger rules, ownership guards, settlement ordering, and recovery storms. Priority: ⬇️ Low Merge Risk: 🟡 Moderate · up to Passive-hibernation recovery can be marked successful even when its replacement terminal fails, allowing incorrect subsequent recovery behavior. This should be fixed before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives extensive technical context, rationale, implementation details, testing results, and known gaps. However, it does not follow the repository template and omits required or expected items such as an explicit ELI5, a Resolution Reformat the description using all template headings. Add an explicit
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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.
ℹ️ No critical issues — one minor documentation nit inline.
Reviewed changes
Reviewed the delta since the prior review (19f4927/61f0a10 → 9381a9b): the fresh-spawn success settle, the remote-projection recovery strip, and the test-harness extraction.
- Fresh-spawn
successsettle —fresh-spawn-start.tsnow settlessuccesson the bound-PTY arm oftrackedPromise.then, the dual ofsettleSpawnThatLeftPaneUnbound'sfailedsettle, closing the last observation-gate hole forspawn-left-pane-unbound. - Remote projection strips
recovery—tabToRemoteand theRemoteWorkspaceTerminalTabtype now omitrecovery, keeping this client's in-flight heal (and its clock) off the wire. - Test harness extraction — the recovery suite's fake store and request/settle cycle moved to
terminal-recovery-ledger-test-store.ts/terminal-recovery-ledger-test-driver.ts; the newterminal-pane-recovery-unsettled-fallback.test.tspins the aged-out-pendingsoftening, andterminal-tab-recovery-remount.test.tsgained adescribe.eachover repo worktree, folder workspace, and floating bucket.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| return { recordRendererCrashBreadcrumb: store.recoveryLedgerMocks.recordRendererCrashBreadcrumb } | ||
| }) | ||
|
|
||
| /** The one reason with no `success` settle path, and the one this bound exists for. */ |
There was a problem hiding this comment.
Stale in the same commit that added it: fresh-spawn-start.ts now settles success on the bound-PTY arm, so spawn-left-pane-unbound does report success (the new test in pty-connection-spawn-left-pane-unbound.test.ts asserts it). The softening is still correct — the residual no-report case is a spawn that never resolves (cf. #19318), not this reason — but this doc comment and the header at lines 17–21 should name that instead.
…the main merge #20034 replaced connect-pane-pty's inline tab resolution with findTerminalTabForPane, and this branch had rewritten the line below it to read the recovery epoch off the row that block used to bind. The merge was textually clean and semantically broken: `terminalTab` no longer existed, so typecheck failed and every test that connects a pane threw ReferenceError. Resolve the row once through the new helper and feed both epochs from it, which keeps #20034's refactor and this branch's reason for reading the row here — a second lookup would put another tabsByWorktree scan on the connect path. captureTabRecoveryGeneration is narrowed to the one field it reads so the helper's record type can carry it.
There was a problem hiding this comment.
ℹ️ No new issues in this delta — the merge-conflict resolution is correct and restores the pre-merge epoch reads.
Reviewed changes
- Merge resolution for
connectPanePty— #20034 (now onmain) replaced the inline tab resolution withfindTerminalTabForPane, which left the mergedconnectPanePtyreferencing aterminalTabthat no longer existed (typecheck failure and aReferenceErroron every pane connect). The row is now resolved once and bothtabGenerationandterminalRecoveryGenerationare read off it, matching the pre-merge behavior without a secondtabsByWorktreescan. TerminalTabRecordcarriesrecovery— thefindTerminalTabForPanerecord type gainsrecovery?: TerminalTab['recovery']so the single resolved row can feed the recovery epoch.captureTabRecoveryGenerationnarrowed — the parameter is narrowed toPick<TerminalTab, 'recovery'>to match the one field it reads.
I traced the equivalence against the pre-merge code: findTerminalTabForPane's unified-tab fallback { id, generation } carries no recovery, so terminalRecoveryGeneration degrades to 0 exactly as the old terminal-row-only read did when the row was absent, and tabGeneration reads the same generation in both shapes. The prior open finding on the direct-SSH echo-back and the stale-comment nitpick are unchanged by this delta and remain outstanding.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts (1)
172-172: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert that the external remount returns generation 0.
remountTerminalTabForRecovery(tabId)uses the external branch when no request is supplied. That branch must not create a recovery ledger entry. Without this assertion, the test can pass if host hydration consumes a recovery budget and returns a nonzero ledger generation.- expect(remountResult).toMatchObject({ remounted: true }) + expect(remountResult).toMatchObject({ remounted: true, generation: 0 })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 5c27abf8-9b71-494f-b07a-e307a7324556
📒 Files selected for processing (46)
src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsxsrc/renderer/src/components/terminal-pane/pty-connection-hidden-delivery-gate.test.tssrc/renderer/src/components/terminal-pane/pty-connection-spawn-left-pane-unbound.test.tssrc/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.test.tssrc/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.tssrc/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.tssrc/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-connect.tssrc/renderer/src/components/terminal-pane/pty-connection/direct-ssh-reattach-recovery.test.tssrc/renderer/src/components/terminal-pane/pty-connection/direct-ssh-reattach-recovery.tssrc/renderer/src/components/terminal-pane/pty-connection/direct-ssh-retry-status.tssrc/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.tssrc/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.tssrc/renderer/src/components/terminal-pane/pty-connection/reattach-success-settle.test.tssrc/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.tssrc/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.test.tssrc/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.tssrc/renderer/src/components/terminal-pane/terminal-pane-recovery-unsettled-fallback.test.tssrc/renderer/src/components/terminal-pane/terminal-pane-recovery.test.tssrc/renderer/src/components/terminal-pane/terminal-pane-recovery.tssrc/renderer/src/components/terminal-pane/terminal-pane-surface-ownership.test.tssrc/renderer/src/components/terminal-pane/terminal-recovery-ledger-test-driver.tssrc/renderer/src/components/terminal-pane/terminal-recovery-ledger-test-store.tssrc/renderer/src/hooks/remote-workspace-session-merge-local-survival.test.tssrc/renderer/src/hooks/remote-workspace-session-merge.tssrc/renderer/src/lib/session-write-subscriber.test.tssrc/renderer/src/lib/session-write-subscriber.tssrc/renderer/src/lib/workspace-session-patch.test.tssrc/renderer/src/lib/workspace-session.tssrc/renderer/src/runtime/web-session-tabs-sync/mirrored-terminal-recovery-ledger.test.tssrc/renderer/src/runtime/web-session-tabs-sync/terminal-build.tssrc/renderer/src/store/slices/tab-view-mode.test.tssrc/renderer/src/store/slices/tabs/tabs-host-mirroring.tssrc/renderer/src/store/slices/tabs/tabs-label-actions.tssrc/renderer/src/store/slices/terminal-tab-recovery-remount.test.tssrc/renderer/src/store/slices/worktree-helpers.tssrc/renderer/src/store/slices/worktrees.tssrc/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.tssrc/renderer/src/store/terminals/terminal-tab-recovery-ledger.tssrc/shared/remote-workspace-session-projection.test.tssrc/shared/remote-workspace-session-projection.tssrc/shared/remote-workspace-types.tssrc/shared/terminal-tab-types.tssrc/shared/workspace-session-schema.tssrc/shared/workspace-session-terminal-schema.test.tstests/e2e/paired-runtime-rejected-input-remount.unit.test.tstests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| // when `session.connectionId` is set (:120). The local arm and the | ||
| // sessionExpired arm fall through to startFreshColdRestoreAgentResume and | ||
| // leave the attempt pending, which the 31s bound then ages out. | ||
| session.settlePaneAttachAttempt?.(undefined, 'success') |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Settle attach success after the passive-hibernation replacement check.
When resumeComesFromPassiveHibernation is true, the handler disconnects the reattached PTY, starts a replacement spawn, and returns false. The earlier settlePaneAttachAttempt(undefined, 'success') marks the recovery as successful before the replacement completes. A failed replacement then cannot record failed, so a later automatic recovery can bypass the settled-failure refusal.
Move the success settlement below this branch. Let fresh-spawn-start.ts settle the replacement as success or failed.
| ).toBe(false) | ||
|
|
||
| // Closing the tab drops the row, and the budget with it — same object. | ||
| setTerminalTabs([{ id: 'tab-1' }]) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Exercise the missing-row path before reopening the tab.
The recovery ledger lives on the tab row, and captureTerminalPaneRecoveryGeneration reads the ledger from the located row. The current replacement keeps tab-1 present and only removes its recovery field. A regression that fails to remove the closed row can therefore pass this test.
- setTerminalTabs([{ id: 'tab-1' }])
+ setTerminalTabs(terminalTabs().filter((tab) => tab.id !== 'tab-1'))
+ expect(captureTerminalPaneRecoveryGeneration('tab-1')).toBe(0)
+ setTerminalTabs([...terminalTabs(), { id: 'tab-1' }])📝 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.
| setTerminalTabs([{ id: 'tab-1' }]) | |
| setTerminalTabs(terminalTabs().filter((tab) => tab.id !== 'tab-1')) | |
| expect(captureTerminalPaneRecoveryGeneration('tab-1')).toBe(0) | |
| setTerminalTabs([...terminalTabs(), { id: 'tab-1' }]) |

Its base #19745 has since been squash-merged as
7d367b2aa, so this now targetsmaindirectly. This does not supersede #19745. That PR is correct and is unchanged here; it collapsed two divergent tab lookups into one primitive,locateTerminalTab. This builds on it.The reframed root cause
#19745 fixed the thing that triggered the storm. This fixes the mechanism.
The trigger was an index mismatch:
getTabreadsunifiedTabsByWorktree,remountTerminalTabForRecoveryreads and mutatestabsByWorktree, and on the direct-SSH path the two drift. But the mismatch only mattered because of what it was allowed to reach. The recovery budget lived in module-level Maps keyed by tabId (recoveryTimestampsByTabId,recoveryGenerationByTabId) with their own lifecycle. Because they outlived the row, something had to garbage-collect them — and that garbage collector wasunregister's "if the tab is gone, delete the budget". Every remount disposes a pane, every disposal ran that check, and a wrong answer erased the budget the remount had just consumed.Anything with a release path can release wrongly. Fixing which index the release consults leaves the release. So: the ledger moves onto the tab row, and the release is deleted rather than corrected.
The second half is that counting was the wrong shape to begin with. Each remount mounts a new pane that captures a fresh recovery epoch (
connect-pane-pty.ts); its reattach fails;recoverUnverifiableDirectSshReattachre-requests with that current epoch, so the epoch check passes every time. Recovery was re-requesting the exact action that had just failed, with no evidence anything had changed. A cap can only bound how fast that happens, never stop it.What changed
1. The ledger is a field on the row.
TerminalTabRecoveryLedger(attemptedAt,generation,outcome,startedAt,reason,tabGeneration) onTerminalTab, stripped on persist exactly likependingActivationSpawn(buildSanitizedTabsByWorktree, and the transient-keys set insession-write-subscriber.tsso ledger churn does not rewrite the durable session).remountTerminalTabForRecoverynow takes a request, runs admission inside itsset(), and writesgeneration + 1and the ledger in one object. Both module Maps and theunregistercleanup block are deleted.activeTerminalRecoveryInstanceIdsandpendingRetryByTabIdstay module-level: they are keyed by mounted xterm instance, which genuinely outlives no store row, so they have nothing to shadow.The action returns a result rather than a boolean, because the caller needs the decline reason to decide whether to schedule a retry.
2. Admission gates on an observed outcome. A request is admissible only when the last attempt has settled. After a settled
failed, an automatic request with the same reason is refused until a new trigger arrives — atab.generationmove (authority change, SSH pane retry, activation respawn, external lifecycle remount) or the user's explicit Retry in the error toast. The 3-per-5-min cap survives as a breadcrumb-emitting backstop (terminal_pane_recovery_window_cap), not as the control: if it fires, the outcome gate let a loop through, and that is a bug worth a trace.3.
viewModeis mirrored to the row, persisted, and read from both indices.viewModewas already declared on both types and already written to the row by host-sync; only the local toggles skipped it, which is an authoring gap, not a design choice.patchTerminalTabPinnedis generalized topatchTerminalTabRow(tabsByWorktree, tabId, patch)and now servessetTabViewMode,toggleTabViewMode,pinTabandunpinTab.terminalTabSchemanow declaresviewModeso the row survives the load boundary. The chat-ownership guard keeps reading both indices — see below. Checked the host-echo reconcile:terminal-build.tsalready doesexisting ? existing.viewMode : host…, so it does not fight the local write.Unrepresentability, not a stronger guard
The claim this PR is making is that "the budget erased itself" has no expression, not that it is now checked more carefully. The evidence:
tab.recoveryare the singleset()increateRemountTerminalTabForRecoveryandsettleTerminalTabRecovery.locateTerminalTab(...).tab.Existence and budget are now one object reached through one lookup. That is the difference between fixed-by-convention and fixed-by-construction, and it is the point of the PR.
Reuse: what was reused, and what I declined to generalize
Reused from the existing direct-SSH pane retry mechanism rather than rebuilt: the outcome vocabulary (
success | failed | timed-out | superseded, nowTerminalPaneRecoveryOutcomein shared), the 31sDIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MSbound, thetabGenerationkeying, and — the one that matters — the existing settle entry point.session.settleDirectSshPaneRetryAttemptis renamedsettlePaneAttachAttemptand settles both ledgers from one call, so all five existing concrete failure points settle recovery too with no new plumbing:deferred-session-reattach-connect.ts:93,156direct-ssh-retry-status.ts:58(the existing 31s timer)unbound-pane-spawn-recovery.ts:22direct-ssh-reattach-recovery.ts:9successsettles atreattach-result-handler.ts, placed after the no-PTY-id and session-expired branches rather than at theauthoritativeReattachGenerationbump — at the bump it would have marked the storm's own failure path as a success and reopened the loop.recoverUnverifiableDirectSshReattachnow settles before re-requesting, matching the shapeunbound-pane-spawn-recovery.tsalready used. That ordering is the fix: settling after would ask for a repeat while the ledger still readpending.Declined: generalizing
directSshPaneRetryByTabIditselfThe brief asked me to generalize that ledger rather than add a second one. I didn't, deliberately.
It is authority-scoped.
DirectSshAuthoritythreads throughpruneObsoleteAuthorityState,directSshAuthoritiesEqual,liveBindingMatchesandisCurrentDirectSshAuthorityacross roughly six modules and their tests. Recovery has no authority, so generalizing means making that parameter optional or polymorphic everywhere — a large, risky change to the live SSH retry path for no behavioural gain.The warning behind the instruction was that a second settle ledger would repeat the shadow-store mistake. It doesn't, and the distinction is exactly the one this PR turns on:
directSshPaneRetryByTabIdis a store-level map keyed by tabId that outlives its row and needs pruning — it has the shadow-store shape. The recovery ledger is a field on the row and has no independent lifecycle. Reusing the settle call sites gets the coupling the instruction was actually protecting; reusing the record would have imported the shape the instruction was warning about.Declined: treating an aged-out
pendingas an observed failurereadTerminalRecoveryOutcomereports apendingledger older than the 31s settlement bound astimed-out, but admission deliberately checks the recordedledger.outcome, not the derived one, when applying the settled-failure refusal. Only an explicitfailed/timed-outsettle closes a reason.Why: the settlement points above cover the SSH and spawn paths, but they are not exhaustive across every pane kind. If an aged-out
pendingcounted as an observed failure, a pane kind with no settle path would leave its tab's recovery wedged permanently — refusing that reason until something bumpedtab.generationor the user pressed Retry. That trades a remount storm for a silently unrecoverable terminal, which is the wrong trade. The cooldown and the window cap bound the aged-out case instead: worst case is roughly one remount per 31s, ceiling 3 per 5 minutes, versus the ~1110 per tab in the report.Readiness review: the chat-ownership guard (P1, fixed)
An earlier revision of this PR narrowed the native-chat guard to read the terminal row alone, on the theory that the new row mirror made #19745's two-index
||redundant. A readiness review caught that it isn't, and the review was right.terminalTabSchema(workspace-session-schema.ts) never declaredviewMode. Zod strips undeclared keys, so the terminal row lostviewModeon every session load while the unified tab schema kept it — it declaresviewModeexplicitly "so 'chat' survives reload / session restore". Nothing re-derived the row's value after load. So after a restart a chat-owned tab's row readundefined, the narrowed guard saw "not chat-owned", and recovery would remount the hidden surface — exactly the race #19745's guard exists to prevent, on the Claude Code path, with no user workaround.The PR's own test asserted the narrowed behaviour, so the suite structurally could not catch it.
Both halves of the fix, because the schema change alone is not sufficient:
terminalTabSchemanow declaresviewMode: z.enum(['terminal','chat']).catch('terminal').optional(), matching the unified tab's declaration and its degradation rationale. The row is durable going forward, which is what the mirror was for and what any future row reader needs.||stays. The schema cannot retroactively addviewModeto sessions already on disk — every session written by any build up to and including fix(terminal): stop the recovery budget erasing itself during a remount #19745 has it only on the unified tab, so the row still loadsundefinedon the first launch after upgrade and the narrowed guard would be wrong for exactly the population most likely to hit it. Beyond that transition, this is a disjunction over two partly-redundant sources for a safety check: a hole in either index errs toward declining a heal on a hidden surface, never toward remounting a chat-owned one. One direction of error is a declined recovery; the other is the race. For that asymmetry, reading both is the right shape regardless of how durable either index becomes.This is a deviation from the review's suggested fix ("the schema addition makes the narrowing correct rather than reverting to the OR") and it is deliberate — the upgrade transition is the reason, and it is now pinned by a test.
Schema behaviour is covered four ways in
workspace-session-terminal-schema.test.ts:'chat'survives the parse,'terminal'survives, a row from an older build staysundefinedrather than failing, and an unrecognised mode from a newer build degrades to'terminal'instead of dropping the whole session.The guard's tests moved to a dedicated
terminal-pane-surface-ownership.test.tsand now cover: row says chat, unified says chat with the row blank (the upgrade transition), row says chat withgetTabblind, both agree on terminal, and — the case a same-process test cannot reach — a real persist/parse round trip throughparseWorkspaceSession, withgetTabdeliberately blind so only the reloaded row can refuse.Original-storm reproduction
I extracted
terminal-pane-recovery.tsat7af0f109537^(pre-#19745) into a scratch module and drove the reported cycle: 200 iterations at the observed 10ms median gap,getTabblind, dispose and re-register each cycle.Pre-#19745: 200 remounts. Storm reproduced. Scratch files deleted afterwards.
The same cycle against this design is four in-repo tests, each landing on 1 remount:
getTab→ null)attemptedAt: [1],outcome: 'failed'Why the 20s variant exists
The 10ms test does not discriminate the settled-failure rule on its own — at that gap the 15s cooldown also catches it, so the test passes with the rule reverted. The 20s variant sits above the cooldown, where counting would have waved three remounts through before noticing and evidence stops at one. Mutation-checking the suite is what surfaced this; without the second variant the headline test would have been asserting less than it appeared to.
Mutation results
Every new test was checked by reverting the production change it covers and confirming failure.
viewModeremoved fromterminalTabSchemastill refuses a chat-owned tab after a real persist/parse round triprefuses a chat-owned tab whose row lost viewMode across a restartunsettledrefusalrefuses a second request while the last remount has reported nothingsettled-failurerefusalrefuses the same reason again once a pane reported it failed,reopens a settled failure when the row moves to a new generation,stops a slow failure chain the cooldown would have waved throughstays capped for a tab the unified index cannot see>→!==does not reopen a settled failure when a host rebuild drops generationterminal-build.tsledger carry deletedcarries the client-local ledger across a host snapshot rebuildremote-workspace-session-merge.tsledger carry deletedsurvives a reconnect the host snapshot knows nothing aboutsuccesssettle deletedreports success once the attach payload is authoritativesuccesssettle moved back to theauthoritativeReattachGenerationbumpdoes not report success for a reattach that returned no PTY id,does not report success for an expired sessionviewModerow patchpatches the row in the same writetestssanitizes terminal tabs…,ignores recovery-ledger-only changesremounts over the preserved PTY when no retry lease existsThe last four rows of that table were the review's other two findings: both remote ledger-carry guards and the only
successsettle in the state machine were deletable with zero failures across 38,311 tests. They were correct and load-bearing but nothing was holding them, which is the same class of gap as the P1 — a claim defended by construction in prose but not by a test. All three now fail when reverted.The
successsettle's placement is covered too, not just its presence: moving it back to theauthoritativeReattachGenerationbump makes the storm's own failure path (reattach returned no PTY id) report success and reopen the loop, and two negative cases now catch that.Two holes found beyond the brief (both now covered)
Host-snapshot rebuilds drop client-local fields.
terminal-build.tsandremote-workspace-session-merge.tsreconstruct rows from host snapshots. Without carryingrecovery, a remote-runtime pane would get a fresh remount allowance on every republication — the storm, restored on a timer. Both now preserve it, following the patternpendingActivationSpawnalready established inremote-workspace-session-merge.ts.terminal-buildemits nogenerationat all, so supersession is(tab.generation ?? 0) > ledger.tabGeneration, strictly forward — not!==. This is worth naming as the same defect class as the original bug: a comparison that treats missing data as signal.!==would have read a rebuilt row's absentgenerationas "the generation moved, this is a new trigger" and handed back the allowance, exactly as the old existence check read a drifted index as "the tab is gone, release the budget". Both are a reader inferring an event from a hole.Verification
pnpm tcclean (run alone — concurrent typechecks OOM this machine).oxlintclean.pnpm run check:code-quality:changed: 0 new findings across 37 files.pnpm formatapplied.max-linesdisable, twice.pty-connection-terminal-input-gating.test.tswent over the 800-line limit because the remount fake grew from a one-line boolean to a result object at three call sites — resolved by hoisting the fakes and the shared matcher into module consts.terminal-pane-recovery.test.tsthen went over while adding the guard coverage — resolved by splitting the surface-ownership tests intoterminal-pane-surface-ownership.test.ts, which is a real seam (who owns the surface vs. the budget/outcome gate), not a size dodge.captureTerminalPaneRecoveryGenerationscanstabsByWorktree, and an existing ratchet test caught it firing on the pane-connect path.connect-pane-ptynow reads the epoch off the row it had already resolved, so connect costs no extra scan.Live verification (added after the readiness review)
The readiness review's central reservation was that nothing had been run end to end. That is now
addressed for SSH and for the local recovery paths, against a real Docker
sshdcontainer and areal Electron renderer driven over CDP (
electron-headless,ORCA_BACKGROUND_LAUNCH=1, nowindow activation).
ssh-docker-transport-drop-recovery.spec.ts— 6/6 in 4.6mThis is the spec that matters: it does not reconnect politely, it injects faults under a live
session. Killing sshd's per-connection forks leaves the listening daemon and every relay process
alive, so the session must survive and the pane must keep its PTY; SIGKILLing the relay leaves sshd
reachable but the sessions genuinely gone. The two must not be confused, which is exactly the
live/unverifiable/exiteddistinction the ledger's outcome gate now encodes.The other specs CI routes for this PR
pty-input-write-queue-ssh,ssh-docker-reconnect-pane-restore,ssh-cold-activation-restore,ssh-docker-half-open-link,ssh-reconnect-tab-destruction— 6 passed / 1 failed in oneback-to-back batch. The single failure (
keeps a tab created right after a reconnect alive across the next one) reran 3/3 green standalone and passed in CI on this branch; this PR's only edit tothat path adds one field to an already-preserved tab and cannot delete one. Flake under consecutive
container churn, recorded rather than hidden.
Local recovery paths, also live:
terminal-quick-command-pre-bind-recovery1/1,terminal-wedged-write-pipeline-recovery2/2,terminal-stuck-occlusion-recovery1/1.spawn-left-pane-unbound— correcting the earlier assessmentThe "Declined: treating an aged-out
pendingas an observed failure" section above rests on therebeing a pane kind that cannot report. Re-derived, that was half right, and the half that was
wrong is now fixed.
The failure half already settled.
settleSpawnThatLeftPaneUnboundcallssettlePaneAttachAttempt(attempt, 'failed')unconditionally, before requesting the remount, so aspawn that keeps failing is refused as
settled-failureafter one remount. Only success had noreport: the remount for this reason heals by spawning, not reattaching, so it never reaches
handleReattachResult— the only placesuccesswas settled. A pane that healed therefore satpendingfor the full 31s bound, blocking the tab's next recovery for any other reason.It now reports.
fresh-spawn-start.tsalready branches on whether the spawn bound a PTY; thesuccess arm settles
successthere — the exact dual of the failure report, at the same observationpoint, generation-gated in the store so a spawn with no attempt in flight writes nothing. Deleting
the line fails
settles the tab recovery attempt as a success when the spawn binds a PTY.This closes the last hole in the observation gate. Every recovery reason now reports an outcome,
so the cooldown-and-cap fallback is a backstop for all of them rather than the sole control for one.
For what it is worth, the reason is not exotic: every
pty:spawnthrow in main is converted toundefinedby the renderer transport (ipc-pty-connect.ts:165-209), so a missing cwd, a bad shellbinary, or
No PTY provider for connection(SSH target offline or dropped mid-spawn) all land here —as do a paired-runtime
terminal.creategiving up after its retry deadline and the inert transportused for an unresolved host. The originating incident (#19223) was three concurrent field panes
parked just past the 64KB pre-handler warn threshold.
The softening's bound, traced
terminal-pane-recovery-unsettled-fallback.test.tsdrives a pane that reports nothing, ever, andpins the exact fallback:
unsettled(past the cooldown, inside the 31s bound)pendingages out, falls through, cooldown elapsed → admittedwindow-cap, with theterminal_pane_recovery_window_capbreadcrumbThree remounts per rolling five minutes, each breadcrumbed. A stuck-but-not-capped pane reopens
on all three real triggers: the user's Retry, a
successsettle (PTY rebind), and anauthority-change generation bump.
The nuance to read carefully
Once the cap is hit, a user Retry and an authority bump are both refused. The window cap is
deliberately unconditional and is checked before the
trigger === 'user'escape — otherwiseanything that bumps
generationeach cycle would lift the ceiling along with it, which is thestorm's own shape. Only an
externallifecycle remount (host hydration, which writes no ledger) sitsabove the cap, together with the retry scheduled for when the window reopens.
So "the user pressing Retry reopens it" is true of a settled failure and of an unsettled attempt, and
not true of a capped tab. That distinction is now pinned by
keeps the cap above every trigger but the external lifecycle remount.Two CI-breaking callers outside the verification sweep
CI failed on two earlier heads with identical, deterministic, non-flaky failures. Both were the same
cause and both were missed for the same reason:
remountTerminalTabForRecoverychanged fromreturning
booleanto returning an admission result and gained a request argument, and theverification sweep covered the renderer and shared suites but not
tests/e2e/, where two callerslive.
tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts:420— three assertions oftoHaveBeenCalledWith('tab-1')against a call that now carries a second argument. (test / tests node 24 1/8)tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts:170—expect(remounted).toBe(true)against
{ remounted: true, generation: 0 }. (e2e / changed e2e specs)Both are updated to the new contract; the e2e spec passes live. Worth stating plainly because a
"38,327 tests pass" number read as whole-repo coverage is what let these through.
Remaining gaps, stated so they are not read as covered
buildMirroredTerminalTabsemits nogeneration, supersession-by-generation effectively cannotfire on that topology, so a settled failure stays closed for its reason until the user presses
Retry. It is degraded, not regressed —
generationwas never mirrored there before this PReither — and it has a visible workaround and a hard brake. It is now unit-covered
(
mirrored-terminal-recovery-ledger.test.ts), but no real reconnect cycle has been run. This isthe one thing I would want before calling the remote path proven.
a run: the repo's own path router (
pr-e2e-source-routing.mjs --wsl-source) returnsfalseforthis diff; CI's
real WSL terminaljob was skipped on both runs for that reason; and the wholepty-connection/tree contains no WSL branch — twowslAvailablediagnostic fields and a comment.WSL panes are local panes over the same
connectPanePtysession and inherit the same settlepoints. That is a structural argument, not a test.
describe.eachdrives a repo worktree, a
folder:-keyed workspace andFLOATING_TERMINAL_WORKTREE_IDthroughadmit → pending-blocks → settle-failed → refuse → user-reopen, plus close-drops-the-ledger.
Restricting
locateTerminalTabto::-shaped keys fails exactly the folder and floating cases andleaves the worktree case passing.
Conflict warning: #19318
#19318 (
fix(terminal): bound a pane's wait on a spawn that never settles) is open againstmainand touches the same code: it rewrites
unbound-pane-spawn-recovery.tsfrom 40 to 119 lines andedits the same
fresh-spawn-start.tsblock this PR adds thesuccesssettle to. The two arecomplementary — that PR bounds a
pty:spawninvoke that never resolves at all, this one reports theoutcome when it does — but they will conflict textually.
Whichever lands second must preserve the
successsettle on the bound-PTY arm oftrackedPromise.then. Losing it silently reopens the 31spendingwindow for every fresh-spawnrecovery, and no test outside
pty-connection-spawn-left-pane-unbound.test.tswill notice.Verification after the live run
pnpm tcclean (run alone).oxlint src tests configclean.pnpm run check:code-quality:changed: 0 new findings across 45 changed files.runtime-Electron, Zustand selector fan-out.
are
cross-version-wiretests that CI runs in a dedicated full-history job which iscross-version-wire=falseand skipped for this PR, and one is aremote-runtime-shared-control-connection.test.tstiming test whose file pair is byte-identical tomain, fails with this PR's changes stashed, and passed in CI.max-linesdisable. The recovery suite's inline harness is extracted toterminal-recovery-ledger-test-store.ts(the fake store, driven by the real store actions) andterminal-recovery-ledger-test-driver.ts(the request/settle cycle), so the new fallback suitereuses it rather than copying it. The split is forced as well as tidy: the
@/storemock factoryimports the store module, so a back-edge to the module under test deadlocks the factory.