Skip to content

fix(terminal): move the recovery ledger onto the tab row and gate it on observed outcome - #20025

Merged
nwparker merged 5 commits into
mainfrom
fix/terminal-recovery-row-ledger
Sep 11, 2026
Merged

nwparker merged 5 commits into
mainfrom
fix/terminal-recovery-row-ledger

Conversation

@nwparker

@nwparker nwparker commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1234 $\color{#cf222e}{\Huge{\mathbf{−}}}$​131 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1103
Prod 27 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​760 $\color{#cf222e}{\Huge{\mathbf{−}}}$​169 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​591

Its base #19745 has since been squash-merged as 7d367b2aa, so this now targets main directly. 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: getTab reads unifiedTabsByWorktree, remountTerminalTabForRecovery reads and mutates tabsByWorktree, 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 was unregister'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; recoverUnverifiableDirectSshReattach re-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) on TerminalTab, stripped on persist exactly like pendingActivationSpawn (buildSanitizedTabsByWorktree, and the transient-keys set in session-write-subscriber.ts so ledger churn does not rewrite the durable session). remountTerminalTabForRecovery now takes a request, runs admission inside its set(), and writes generation + 1 and the ledger in one object. Both module Maps and the unregister cleanup block are deleted. activeTerminalRecoveryInstanceIds and pendingRetryByTabId stay 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 — a tab.generation move (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. viewMode is mirrored to the row, persisted, and read from both indices. viewMode was 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. patchTerminalTabPinned is generalized to patchTerminalTabRow(tabsByWorktree, tabId, patch) and now serves setTabViewMode, toggleTabViewMode, pinTab and unpinTab. terminalTabSchema now declares viewMode so the row survives the load boundary. The chat-ownership guard keeps reading both indices — see below. Checked the host-echo reconcile: terminal-build.ts already does existing ? 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:

  • The only writers of tab.recovery are the single set() in createRemountTerminalTabForRecovery and settleTerminalTabRecovery.
  • The only reader is locateTerminalTab(...).tab.
  • No path drops the field while keeping the row.
  • Nothing exists outside the row to garbage-collect, so there is no release path to get wrong.

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, now TerminalPaneRecoveryOutcome in shared), the 31s DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS bound, the tabGeneration keying, and — the one that matters — the existing settle entry point. session.settleDirectSshPaneRetryAttempt is renamed settlePaneAttachAttempt and 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,156
  • direct-ssh-retry-status.ts:58 (the existing 31s timer)
  • unbound-pane-spawn-recovery.ts:22
  • direct-ssh-reattach-recovery.ts:9

success settles at reattach-result-handler.ts, placed after the no-PTY-id and session-expired branches rather than at the authoritativeReattachGeneration bump — at the bump it would have marked the storm's own failure path as a success and reopened the loop.

recoverUnverifiableDirectSshReattach now settles before re-requesting, matching the shape unbound-pane-spawn-recovery.ts already used. That ordering is the fix: settling after would ask for a repeat while the ledger still read pending.

Declined: generalizing directSshPaneRetryByTabId itself

The brief asked me to generalize that ledger rather than add a second one. I didn't, deliberately.

It is authority-scoped. DirectSshAuthority threads through pruneObsoleteAuthorityState, directSshAuthoritiesEqual, liveBindingMatches and isCurrentDirectSshAuthority across 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: directSshPaneRetryByTabId is 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 pending as an observed failure

readTerminalRecoveryOutcome reports a pending ledger older than the 31s settlement bound as timed-out, but admission deliberately checks the recorded ledger.outcome, not the derived one, when applying the settled-failure refusal. Only an explicit failed / timed-out settle 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 pending counted as an observed failure, a pane kind with no settle path would leave its tab's recovery wedged permanently — refusing that reason until something bumped tab.generation or 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 declared viewMode. Zod strips undeclared keys, so the terminal row lost viewMode on every session load while the unified tab schema kept it — it declares viewMode explicitly "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 read undefined, 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:

  1. terminalTabSchema now declares viewMode: 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.
  2. The || stays. The schema cannot retroactively add viewMode to 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 loads undefined on 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 stays undefined rather 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.ts and now cover: row says chat, unified says chat with the row blank (the upgrade transition), row says chat with getTab blind, both agree on terminal, and — the case a same-process test cannot reach — a real persist/parse round trip through parseWorkspaceSession, with getTab deliberately blind so only the reloaded row can refuse.

Original-storm reproduction

I extracted terminal-pane-recovery.ts at 7af0f109537^ (pre-#19745) into a scratch module and drove the reported cycle: 200 iterations at the observed 10ms median gap, getTab blind, 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:

variant result
200 cycles at the observed 10ms gap 1 remount
10 cycles at 20s gaps 1 remount
unified index blind (getTab → null) 1 remount
ledger state after the storm 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.

production change reverted failing test(s)
viewMode removed from terminalTabSchema 3 schema round-trip tests + still refuses a chat-owned tab after a real persist/parse round trip
chat guard re-narrowed to the row alone refuses a chat-owned tab whose row lost viewMode across a restart
unsettled refusal refuses a second request while the last remount has reported nothing
settled-failure refusal refuses 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 through
re-add the disposal budget release, in the original b5cfc6ca shape stays capped for a tab the unified index cannot see
supersession > → !== does not reopen a settled failure when a host rebuild drops generation
terminal-build.ts ledger carry deleted carries the client-local ledger across a host snapshot rebuild
remote-workspace-session-merge.ts ledger carry deleted survives a reconnect the host snapshot knows nothing about
the only success settle deleted reports success once the attach payload is authoritative
success settle moved back to the authoritativeReattachGeneration bump does not report success for a reattach that returned no PTY id, does not report success for an expired session
viewMode row patch both patches the row in the same write tests
persist stripping sanitizes terminal tabs…, ignores recovery-ledger-only changes
settle-after-request ordering remounts over the preserved PTY when no retry lease exists

The last four rows of that table were the review's other two findings: both remote ledger-carry guards and the only success settle 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 success settle's placement is covered too, not just its presence: moving it back to the authoritativeReattachGeneration bump 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.ts and remote-workspace-session-merge.ts reconstruct rows from host snapshots. Without carrying recovery, 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 pattern pendingActivationSpawn already established in remote-workspace-session-merge.ts.

terminal-build emits no generation at 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 absent generation as "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

  • Full renderer + shared suite: 38,327 passed, 123 skipped, 0 failures (4,362 files).
  • pnpm tc clean (run alone — concurrent typechecks OOM this machine).
  • oxlint clean. pnpm run check:code-quality:changed: 0 new findings across 37 files. pnpm format applied.
  • No max-lines disable, twice. pty-connection-terminal-input-gating.test.ts went 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.ts then went over while adding the guard coverage — resolved by splitting the surface-ownership tests into terminal-pane-surface-ownership.test.ts, which is a real seam (who owns the surface vs. the budget/outcome gate), not a size dodge.
  • Perf: captureTerminalPaneRecoveryGeneration scans tabsByWorktree, and an existing ratchet test caught it firing on the pane-connect path. connect-pane-pty now 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 sshd container and a
real Electron renderer driven over CDP (electron-headless, ORCA_BACKGROUND_LAUNCH=1, no
window activation).

ssh-docker-transport-drop-recovery.spec.ts — 6/6 in 4.6m

This 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 / exited distinction the ledger's outcome gate now encodes.

case fault injected result
recovers a live pane after the transport dies under it killed per-connection sshd forks pass (27.4s)
stays bounded when a disconnected shell floods its pty transport drop + output flood pass (45.2s)
replaces the pane only when the host proves the session is gone SIGKILLed relay pass (26.2s)
keeps one reattachable lease per pane across repeated relay restarts repeated relay SIGKILL pass (44.0s)
keeps the session while a frozen host goes silent frozen host pass (52.4s)
accepts input again after a frozen host resumes frozen host, then resumed pass (52.6s)

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 one
back-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 to
that 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-recovery 1/1,
terminal-wedged-write-pipeline-recovery 2/2, terminal-stuck-occlusion-recovery 1/1.

spawn-left-pane-unbound — correcting the earlier assessment

The "Declined: treating an aged-out pending as an observed failure" section above rests on there
being 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. settleSpawnThatLeftPaneUnbound calls
settlePaneAttachAttempt(attempt, 'failed') unconditionally, before requesting the remount, so a
spawn that keeps failing is refused as settled-failure after one remount. Only success had no
report: the remount for this reason heals by spawning, not reattaching, so it never reaches
handleReattachResult — the only place success was settled. A pane that healed therefore sat
pending for the full 31s bound, blocking the tab's next recovery for any other reason.

It now reports. fresh-spawn-start.ts already branches on whether the spawn bound a PTY; the
success arm settles success there — the exact dual of the failure report, at the same observation
point, 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:spawn throw in main is converted to
undefined by the renderer transport (ipc-pty-connect.ts:165-209), so a missing cwd, a bad shell
binary, or No PTY provider for connection (SSH target offline or dropped mid-spawn) all land here —
as do a paired-runtime terminal.create giving up after its retry deadline and the inert transport
used 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.ts drives a pane that reports nothing, ever, and
pins the exact fallback:

t outcome
0 admitted — no ledger yet
16s declined unsettled (past the cooldown, inside the 31s bound)
31s pending ages out, falls through, cooldown elapsed → admitted
62s admitted
93s / 124s / 200s / 299s declined window-cap, with the terminal_pane_recovery_window_cap breadcrumb
301s the first attempt leaves the window → admitted

Three remounts per rolling five minutes, each breadcrumbed. A stuck-but-not-capped pane reopens
on all three real triggers: the user's Retry, a success settle (PTY rebind), and an
authority-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 — otherwise
anything that bumps generation each cycle would lift the ceiling along with it, which is the
storm's own shape. Only an external lifecycle remount (host hydration, which writes no ledger) sits
above 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: remountTerminalTabForRecovery changed from
returning boolean to returning an admission result and gained a request argument, and the
verification sweep covered the renderer and shared suites but not tests/e2e/, where two callers
live.

  • tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts:420 — three assertions of
    toHaveBeenCalledWith('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

  • Paired web / mirrored client was never exercised live. F20025-3 stands: because
    buildMirroredTerminalTabs emits no generation, supersession-by-generation effectively cannot
    fire on that topology, so a settled failure stays closed for its reason until the user presses
    Retry. It is degraded, not regressed — generation was never mirrored there before this PR
    either — 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 is
    the one thing I would want before calling the remote path proven.
  • WSL was not exercised. No Windows or WSL host was available. Three pieces of evidence short of
    a run: the repo's own path router (pr-e2e-source-routing.mjs --wsl-source) returns false for
    this diff; CI's real WSL terminal job was skipped on both runs for that reason; and the whole
    pty-connection/ tree contains no WSL branch — two wslAvailable diagnostic fields and a comment.
    WSL panes are local panes over the same connectPanePty session and inherit the same settle
    points. That is a structural argument, not a test.
  • Folder workspaces are exercised through the real store, not a running app: a describe.each
    drives a repo worktree, a folder:-keyed workspace and FLOATING_TERMINAL_WORKTREE_ID through
    admit → pending-blocks → settle-failed → refuse → user-reopen, plus close-drops-the-ledger.
    Restricting locateTerminalTab to ::-shaped keys fails exactly the folder and floating cases and
    leaves the worktree case passing.

Conflict warning: #19318

#19318 (fix(terminal): bound a pane's wait on a spawn that never settles) is open against main
and touches the same code: it rewrites unbound-pane-spawn-recovery.ts from 40 to 119 lines and
edits the same fresh-spawn-start.ts block this PR adds the success settle to. The two are
complementary — that PR bounds a pty:spawn invoke that never resolves at all, this one reports the
outcome when it does — but they will conflict textually.

Whichever lands second must preserve the success settle on the bound-PTY arm of
trackedPromise.then.
Losing it silently reopens the 31s pending window for every fresh-spawn
recovery, and no test outside pty-connection-spawn-left-pane-unbound.test.ts will notice.

Verification after the live run

  • pnpm tc clean (run alone). oxlint src tests config clean.
  • pnpm run check:code-quality:changed: 0 new findings across 45 changed files.
  • Static-analysis ratchets all pass: reliability-gate manifest (120 gates), max-lines, ts-nocheck,
    runtime-Electron, Zustand selector fan-out.
  • Targeted suite over the change area: 449 files / 4,305 tests, 0 failures.
  • Full change-area sweep: 1,873 files / 18,172 tests. Three failures, each shown unrelated — two
    are cross-version-wire tests that CI runs in a dedicated full-history job which is
    cross-version-wire=false and skipped for this PR, and one is a
    remote-runtime-shared-control-connection.test.ts timing test whose file pair is byte-identical to
    main, fails with this PR's changes stashed, and passed in CI.
  • No max-lines disable. The recovery suite's inline harness is extracted to
    terminal-recovery-ledger-test-store.ts (the fake store, driven by the real store actions) and
    terminal-recovery-ledger-test-driver.ts (the request/settle cycle), so the new fallback suite
    reuses it rather than copying it. The split is forced as well as tidy: the @/store mock factory
    imports the store module, so a back-edge to the module under test deadlocks the factory.

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

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 — remountTerminalTabForRecovery now writes the generation bump and the ledger in one set(); the disposal-release unregister block and both module Maps are deleted.
  • Outcome-gated admission — admitTerminalRecoveryRemount refuses an unsettled re-request and a settled-failure with 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 — settleDirectSshPaneRetryAttempt is renamed settlePaneAttachAttempt and settles both ledgers from one call, so the five existing failure points and the success path all settle recovery.
  • viewMode mirrored to the row — the OR'd chat-ownership guard collapses to a row-only read; patchTerminalTabRow generalizes the pin helper and serves all four toggles.
  • Host-rebuild preservation — terminal-build.ts and remote-workspace-session-merge.ts preserve recovery, 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 when session.connectionId is set); the session-expired branch leaves the ledger pending to age out. Worth tightening the wording so a reader doesn't expect a settle that doesn't happen.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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 } : {})

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.

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.

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

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 viewMode on the terminal row — terminalTabSchema now declares viewMode, so the row survives the persist/parse boundary instead of reading undefined after a restart.
  • Re-read both indices for chat ownership — the guard in requestTerminalPaneRecovery reverts to row || unifiedTab, so a pre-existing session with viewMode only on the unified tab still refuses to remount a hidden chat surface.
  • Pinned the only success settle — reattach-success-settle.test.ts asserts 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 the client-local recovery ledger block.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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 })

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.

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.
@nwparker
nwparker force-pushed the fix/terminal-recovery-row-ledger branch from 19f4927 to 61f0a10 Compare September 11, 2026 06:55
@nwparker
nwparker changed the base branch from fix/terminal-recovery-remount-storm to main September 11, 2026 06:55
@greptile-apps

greptile-apps Bot commented Sep 11, 2026

Copy link
Copy Markdown

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

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The 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 7fb75

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 expecte… Reformat the description using all template headings. Add an explicit Fixes #<issue> reference, provide before/after visual proof or write N/A with a reason, complete the AI Disclosure and Agent skill upstream boundary sections, address…
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 55 functions across 46 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: moving the recovery ledger onto terminal-tab rows and gating recovery on observed outcomes.
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.
Full details: Description check

Explanation

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 Fixes #... linked issue, visual proof or N/A, the AI Disclosure section, the Agent skill upstream boundary checkbox, the Notes section, and the checklist.

Resolution

Reformat the description using all template headings. Add an explicit Fixes #&lt;issue&gt; reference, provide before/after visual proof or write N/A with a reason, complete the AI Disclosure and Agent skill upstream boundary sections, address the Notes items, and complete the Testing and Checklist checkboxes.

  • Fix all pre-merge checks with AI
✨ 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.

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

ℹ️ 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 success settle — fresh-spawn-start.ts now settles success on the bound-PTY arm of trackedPromise.then, the dual of settleSpawnThatLeftPaneUnbound's failed settle, closing the last observation-gate hole for spawn-left-pane-unbound.
  • Remote projection strips recovery — tabToRemote and the RemoteWorkspaceTerminalTab type now omit recovery, 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 new terminal-pane-recovery-unsettled-fallback.test.ts pins the aged-out-pending softening, and terminal-tab-recovery-remount.test.ts gained a describe.each over repo worktree, folder workspace, and floating bucket.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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. */

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.

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.

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

ℹ️ 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 on main) replaced the inline tab resolution with findTerminalTabForPane, which left the merged connectPanePty referencing a terminalTab that no longer existed (typecheck failure and a ReferenceError on every pane connect). The row is now resolved once and both tabGeneration and terminalRecoveryGeneration are read off it, matching the pre-merge behavior without a second tabsByWorktree scan.
  • TerminalTabRecord carries recovery — the findTerminalTabForPane record type gains recovery?: TerminalTab['recovery'] so the single resolved row can feed the recovery epoch.
  • captureTabRecoveryGeneration narrowed — the parameter is narrowed to Pick<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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

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

🧹 Nitpick comments (1)
tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts (1)

172-172: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert 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

📥 Commits

Reviewing files that changed from the base of the PR and between 94c2f96 and 7fb7529.

📒 Files selected for processing (46)
  • src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsx
  • src/renderer/src/components/terminal-pane/pty-connection-hidden-delivery-gate.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-spawn-left-pane-unbound.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.ts
  • src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts
  • src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-connect.ts
  • src/renderer/src/components/terminal-pane/pty-connection/direct-ssh-reattach-recovery.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/direct-ssh-reattach-recovery.ts
  • src/renderer/src/components/terminal-pane/pty-connection/direct-ssh-retry-status.ts
  • src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-success-settle.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/terminal-tab-id.ts
  • src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/unbound-pane-spawn-recovery.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-recovery-unsettled-fallback.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-recovery.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-recovery.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-surface-ownership.test.ts
  • src/renderer/src/components/terminal-pane/terminal-recovery-ledger-test-driver.ts
  • src/renderer/src/components/terminal-pane/terminal-recovery-ledger-test-store.ts
  • src/renderer/src/hooks/remote-workspace-session-merge-local-survival.test.ts
  • src/renderer/src/hooks/remote-workspace-session-merge.ts
  • src/renderer/src/lib/session-write-subscriber.test.ts
  • src/renderer/src/lib/session-write-subscriber.ts
  • src/renderer/src/lib/workspace-session-patch.test.ts
  • src/renderer/src/lib/workspace-session.ts
  • src/renderer/src/runtime/web-session-tabs-sync/mirrored-terminal-recovery-ledger.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync/terminal-build.ts
  • src/renderer/src/store/slices/tab-view-mode.test.ts
  • src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts
  • src/renderer/src/store/slices/tabs/tabs-label-actions.ts
  • src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts
  • src/renderer/src/store/terminals/terminal-tab-recovery-ledger.ts
  • src/shared/remote-workspace-session-projection.test.ts
  • src/shared/remote-workspace-session-projection.ts
  • src/shared/remote-workspace-types.ts
  • src/shared/terminal-tab-types.ts
  • src/shared/workspace-session-schema.ts
  • src/shared/workspace-session-terminal-schema.test.ts
  • tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts
  • tests/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')

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

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' }])

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.

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

Suggested change
setTerminalTabs([{ id: 'tab-1' }])
setTerminalTabs(terminalTabs().filter((tab) => tab.id !== 'tab-1'))
expect(captureTerminalPaneRecoveryGeneration('tab-1')).toBe(0)
setTerminalTabs([...terminalTabs(), { id: 'tab-1' }])

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