Skip to content

fix(terminal): stop the recovery budget erasing itself during a remount - #19745

Merged
nwparker merged 2 commits into
mainfrom
fix/terminal-recovery-remount-storm
Sep 11, 2026
Merged

nwparker merged 2 commits into
mainfrom
fix/terminal-recovery-remount-storm

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​125 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​124
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​70 $\color{#cf222e}{\Huge{\mathbf{−}}}$​39 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​31

What

A terminal pane could remount itself in an unbounded loop until the renderer died. Report b5cfc6ca (Orca 1.4.198, Windows 10.0.26200) shows 8,878 remounts across 8 tabs — ~1,110 each — inside 122 seconds, every one with reason=reattach-unverifiable, against a documented cap of 3 per tab per 5 minutes.

Fix evidence

Straight from the user's diagnostic bundle (crash.exit_code: -2147483645):

remount breadcrumbs   : 8878   (all reason=reattach-unverifiable)
distinct tabs         : 8      (1110/1110/1110/1110/1110/1110/1109/1109)
window                : 2026-09-09T03:20:57.170Z -> 03:22:59.544Z  (122.4s)
median gap            : 10 ms
max-in-any-5-min/tab  : 1110   (MAX_RECOVERIES_PER_WINDOW = 3)

The storm exhausted bitmap allocation and Chromium aborted:

Check failure: SkBitmap.cpp:252: assertf(this->tryAllocPixels(info, rowBytes)):
ColorType:4 AlphaType:3 [w:512 h:512] rb:0

The test fails without this fix and passes with it — verified by reverting only the production predicate:

# production predicate reverted to getTab:
FAIL  terminal-pane-recovery.test.ts > unverifiable reattach remount storm (crash b5cfc6ca)
      > caps remounts when the remounted tab is invisible to getTab
AssertionError: expected 200 to be less than or equal to 3
Test Files  1 failed (1) | Tests  1 failed | 34 passed (35)

# with the fix:
Test Files  2 passed (2) | Tests  43 passed (43)

Full suites, real output:

command result
pnpm test src/renderer/src/components/terminal-pane/ 441 files, 4238 passed | 1 skipped
pnpm test src/renderer/src/store/slices/ 324 files, 3098 passed
pnpm tc clean
pnpm run check:code-quality:changed 0 new findings

ELI5

There is a safety rule: "a terminal tab may rebuild itself at most 3 times in 5 minutes." To enforce it, the code writes down a timestamp each time it rebuilds a tab.

The bug: rebuilding a tab tears down its old pane, and the teardown handler asks "does this tab still exist?" — if not, it throws away that tab's timestamps, since a closed tab needs no history.

But it asked the wrong list. Orca keeps two lists of tabs: terminal rows (tabsByWorktree) and UI tabs (unifiedTabsByWorktree). The rebuild works off the first; the existence check read the second. On the direct-SSH path those two lists drift apart, so the check answered "gone" for a tab that was very much alive — and erased the exact timestamp just written.

So every rebuild wiped its own evidence, the counter never reached 3, and the tab rebuilt forever at screen refresh speed until the renderer ran out of graphics memory and died.

The fix: ask the same list that governs rebuilding. The budget exists solely to throttle remountTerminalTabForRecovery, so its release condition must be the negation of that function's success condition.

Trade-offs

  • The reverse divergence now retains a spent budget instead of clearing it (row alive in tabsByWorktree, tab genuinely gone from the UI). Cost is nil: timestamps expire on their own after RECOVERY_WINDOW_MS, and a remount for such a tab would be legitimate anyway.
  • The underlying index divergence is untouched. tabsByWorktree and unifiedTabsByWorktree can still disagree, and that remains a live bug for anything else reading getTab about a terminal tab. Unifying them is a large change with many writers (ssh-target-cleanup, direct-ssh-terminal-workspace-scope, set-active-worktree, terminal-tab-owner-index, hydration) and is deliberately out of scope — the recovery budget does not need the indices consistent, it needs the right one.
  • No user-facing behaviour regression. Genuine tab closes still release the budget: closeTab removes the row from tabsByWorktree before the unified entry, so the new predicate goes false at least as early as the old one. Pinned by a new regression test.
  • The cap itself is unchanged at 3 per 5 minutes.

Adversarial review

1 loop to clean. The reviewer re-derived the mechanism independently rather than trusting the brief, confirmed unregister() is the only non-test writer that clears the budget, traced the real call chain (connect-pane-pty.ts:93 → session-reconcile-dispose.ts:203), and proved the regression test is genuine by temporarily reverting the predicate and watching it fail.

Two findings, both fixed in that loop:

  • (medium) No test proved a genuine tab close still releases the budget through the new index — the store test hand-mutated tabsByWorktree rather than exercising closeTab. Added real closeTab coverage.
  • (low) createHasTerminalTabForRecovery duplicated the traversal createRemountTerminalTabForRecovery performs, re-opening the exact drift class that caused this crash. Extracted a shared locateTerminalTabForRecovery so "same index" is enforced structurally, not by convention.

Reviewer also cleared the alternate storm paths: the viewMode === 'chat' guard fails open toward recovery (not a driver); a tab present in unified but absent from tabsByWorktree makes remount return false and emit remount_unavailable (never a loop); pending retries are filtered at fire time by isCurrentTerminalRecoveryRequest. No wire/RPC surface touched — renderer store state only.

Fixes the crash in report b5cfc6ca.

A recovery remount disposes the pane's xterm, and the disposal handler
released the tab's recovery budget whenever getTab said the tab was gone.
getTab reads unifiedTabsByWorktree while remountTerminalTabForRecovery
reads and mutates tabsByWorktree; on the direct-SSH path the two indices
diverge, so every successful remount deleted the timestamp it had just
written. The cap never engaged and the pane remounted at render speed.

Report b5cfc6ca (1.4.198, Windows): 8878 remounts across 8 tabs in 122s,
all reason=reattach-unverifiable, against a cap of 3 per tab per 5 min,
ending in a Skia bitmap allocation abort.

Gate the release on the same index that governs remounting, via a shared
locateTerminalTabForRecovery so the two cannot drift apart again.
@coderabbitai

coderabbitai Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 3df5d595-95a5-426d-9f9b-759b2b442202

📥 Commits

Reviewing files that changed from the base of the PR and between 7af0f10 and 4c9c21a.

📒 Files selected for processing (6)
  • src/renderer/src/components/terminal-pane/terminal-pane-recovery.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-recovery.ts
  • src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts
  • src/renderer/src/store/slices/terminal-tab-retirement.ts
  • src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts
  • src/renderer/src/store/terminals/terminal-tab-location.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

The change introduces a shared locateTerminalTab lookup for remount and presence checks. Terminal recovery now checks both unified and remount tab indexes for chat ownership and uses the remount index during unregister cleanup. Tests now model index drift, cover dropped chat tabs, validate presence checks, and require storm recovery to remount once.

Priority: ⬆️ High

Merge Risk: ⚪ Minimal · up to 4c9c2

Terminal recovery now uses consistent tab-index semantics, preventing the remount-loop regression while retaining genuine-close budget cleanup.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides strong technical context, rationale, trade-offs, regression evidence, and test results. However, it omits the required linked issue, visual proof or an explicit N/A explanatio… Add a valid issue reference after “Fixes #”. Add visual proof, or write N/A with a brief reason if there is no visual or interaction change. Complete or explicitly address the required Review, Agent skill upstream boundary, Notes, and Che…
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 8 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 and concisely describes the primary fix: preventing the recovery budget from being cleared during terminal remounts.
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 provides strong technical context, rationale, trade-offs, regression evidence, and test results. However, it omits the required linked issue, visual proof or an explicit N/A explanation, and several template sections and checklist confirmations.

Resolution

Add a valid issue reference after “Fixes #”. Add visual proof, or write N/A with a brief reason if there is no visual or interaction change. Complete or explicitly address the required Review, Agent skill upstream boundary, Notes, and Checklist sections, including the applicable testing and platform confirmations. Rename or expand sections as needed to match the repository template, especially “What Changed” and “Why”.`

  • 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 new issues found.

Reviewed changes

  • Release predicate corrected to the remount index — registerTerminalPaneRecoveryInstance's unregister() now releases the per-tab recovery budget via hasTerminalTabForRecovery (reads tabsByWorktree) instead of getTab (reads unifiedTabsByWorktree), the index-drift that erased the budget each remount had just consumed.
  • Structural index consistency — a shared locateTerminalTabForRecovery helper now backs both remountTerminalTabForRecovery and the new hasTerminalTabForRecovery, so the cap and its release cannot diverge again by convention drift.
  • Store-level predicate coverage — hasTerminalTabForRecovery is pinned for remountable tabs, tabs missing from the unified index, tabs absent from tabsByWorktree, and a genuine closeTab.
  • Storm regression test — a fake-timer reattachment storm (200 cycles at the observed 10ms median gap) asserts the remount count stays within the cap and demonstrably fails against the old predicate.

The fix is correct and scoped to renderer store state with no wire/RPC surface. getTab (tabs-focus-actions.ts:15) reads unifiedTabsByWorktree while remount mutates tabsByWorktree, confirming the reported drift; closeTab removes from tabsByWorktree inside its set() before reconciling the unified index (terminal-tab-close.ts), so a real close still releases the budget. The retained-budget case for reverse-diverged tabs self-expires via RECOVERY_WINDOW_MS as the PR documents — no cleanup regression.

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

… scan

Collapse the recovery lookup onto a single primitive, locateTerminalTab, and
express the already-exported isTerminalTabPresent in terms of it. The budget
release now calls isTerminalTabPresent directly, so the store drops the
hasTerminalTabForRecovery action added alongside it.

The native-chat ownership guard also consults tabsByWorktree: the unified tab
index owns viewMode, but it can transiently drop a row the remount index still
holds, and that hole used to read as "not chat-owned" and remount a chat-owned
tab.

Drops the storm control case that passed with and without the fix, and pins the
surviving drift case to the exact remount count the cooldown produces.

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

Reviewed changes

  • Consolidated to one tabsByWorktree scan — the previous hasTerminalTabForRecovery store method and its locateTerminalTabForRecovery helper were removed in favor of the pre-existing isTerminalTabPresent (terminal-tab-retirement.ts), which now delegates to a new shared locateTerminalTab in terminal-tab-location.ts. This eliminates the duplicate traversal the earlier review flagged as re-opening the drift class.
  • Structurally shared resolution — createRemountTerminalTabForRecovery, isTerminalTabPresent, and the native-chat guard all resolve a tab through the same locateTerminalTab, so the cap and its release cannot diverge again.
  • Chat guard hardened against index drift — requestTerminalPaneRecovery now checks both indices for viewMode === 'chat' (getTab and locateTerminalTab(...).tab.viewMode), so a unified-index hole can no longer read a chat-owned terminal tab as recoverable.
  • Tests tightened — the storm assertion is now exact (toBe(1), the 15s cooldown coalescing the whole 10ms-gap storm), a chat-guard drift test was added, and the redundant "visible to getTab" storm variant was removed since the predicate no longer consults getTab at all.

The refactor is behavior-preserving on the release path (verified against 7af0f10): isTerminalTabPresent reuses locateTerminalTab, which is semantically identical to its prior inline scan. The chat-guard's tabsByWorktree clause is a no-op on the local native path (viewMode is only patched on the unified tab there) and a genuine hardening on the paired/web-runtime path where TerminalTab.viewMode is host-tracked. Typecheck is clean and both affected test files pass (43 tests).

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

nwparker added a commit that referenced this pull request Sep 11, 2026
…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 merged commit 7d367b2 into main Sep 11, 2026
28 checks passed
nwparker added a commit that referenced this pull request Sep 11, 2026
…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 added a commit that referenced this pull request Sep 11, 2026
…on observed outcome (#20025)

* fix(terminal): move the recovery ledger onto the tab row and gate it 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.

* fix(terminal): persist the row's viewMode and keep both chat-ownership 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.

* fix(terminal): settle a fresh spawn's outcome and prove the ownership 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.

* fix(terminal): resolve the pane's tab row once for both epochs after 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.
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.

2 participants