Repository navigation
fix(terminal): stop the active-terminal repair loop from tripping React #185 - #11950
Conversation
setActiveTab always reallocated activeTabIdByWorktree, even when the tab was already active for that worktree. Terminal's active-terminal repair effect depends on that map, so when the repair cannot converge activeTabId -- which happens when an earlier-scanned worktree reuses the tab id -- the effect re-triggers itself every commit until React throws #185. Crash cluster A: 12 reports, boundary terminal.workbench, 1.4.162/1.4.163. Co-authored-by: Orca <[email protected]>
…rktrees Prefer the active worktree when resolving a terminal tab's owner. First-match ownership left activeTabId permanently unconvergeable under a duplicated tab id, so the active-terminal repair effect re-triggered itself into React #185. Breadcrumb the duplicate-ownership state (once per tab id) so a crash bundle can prove or kill the production origin of the precondition. Co-authored-by: Orca <[email protected]>
Its renderer guard is once-per-tab-id, so the stale worktree map it exists to diagnose duplicates every tab id at once and could evict the whole 30-entry ring. Also drops two keyed re-reads of tabsByWorktree that would throw for a prototype-named worktree id, and pins the activeTabIdByWorktree guard with a test that fails without it. Co-authored-by: Orca <[email protected]>
…gence flag Name-only coalescing keeps only the newest payload, so a resolvedToActiveWorktree false sample — the one value saying the activation still could not converge — was erased by any later benign true in the same 30s window. Keys on the flag instead, mirroring the WebGL name:kind branch; two keys still bound the burst. Also: the previous coalescing commit had no test at all (removing the name from both sets broke zero of 2701 tests), the resolver's activeWorktreeId truthiness check was a hole rather than a guard for a '' active id, and the resolver test file failed oxfmt --check. Co-authored-by: Orca <[email protected]>
The two earlier commits contradicted each other. Splitting the coalesce key existed so a `false` verdict could not be erased by a later benign `true` — but the renderer guard was keyed on the tab id alone, so for any one id only the first verdict was ever emitted. A duplicated id that first resolves benignly, then stops converging when the user switches worktrees, dropped the `false` sample at the source. That sample is the whole reason the breadcrumb exists: it is the only value saying the activation could not converge activeTabId. Key the guard on id plus verdict. At most two crumbs per tab id, and the main process still folds each verdict into its own ring entry, so the flood bound is unchanged.
…the guard Three comments said `false` is the verdict that matters because it is the only one showing the activation could not converge. That is backwards. The repair effect activates a tab drawn from tabsByWorktree[active], so the React #185 path can only ever emit `true`; `false` is what a deliberate jump-to-agent into a background worktree emits from a fully converged state. A reader of the next bundle would have discarded the exact sample the breadcrumb exists to capture. The mechanism was right, only its stated reason was wrong: the real justification for keying on the verdict is symmetric, since coalescing keeps only the newest payload and either verdict would erase the other. The suite also did not pin the "at most 2 per tab id" bound - a guard keyed on `${tabId}:${activeWorktreeId}` passed all 11 tests while emitting once per worktree, the storm the guard exists to prevent. Adds a count-pinning test that kills it. Caps the never-pruned guard set at 256 distinct verdict keys (~85KB), mirroring MAX_COALESCE_KEYS. Measured 330 B/entry; a realistic thousand duplicated tab ids is ~0.6MB, negligible but unbounded in principle.
Round 6 corrected my own round-5 comment. I had written that `true` is the repair-loop signature and `false` covers a deliberate background activation. The repair effect can emit `false` too: its closure holds the worktree from its render while the guard runs against live state, so a worktree switch landing in between reattributes the tab. The verdict hints at the caller; it does not prove it, and neither value should be discarded. Comment-only. Also take the free scan win the perf review measured: Object.entries allocates a pair array per worktree on a path that runs per tab activation. Own keys are safe to index by, so Object.keys plus an indexed read is behaviour-identical (16.1us -> 5.0us at 170 worktrees x 10 tabs).
Greptile SummaryFixes the active-terminal repair loop that was causing React error #185 (
Confidence Score: 4/5Safe to merge for the React #185 crash fix; a secondary defect in setRuntimePaneTitle/clearRuntimePaneTitle remains unaddressed under the duplicate-tab-id condition. The primary crash path is thoroughly fixed and reproduction-backed. One defect was identified: the PR description claims Round 7 added an isTabInActiveWorktree disjunct to setRuntimePaneTitle and clearRuntimePaneTitle to prevent spurious sortEpoch bumps under the duplicate-tab-id state, but neither function was modified from the base branch and the helper function does not exist in the codebase. Under the exact precondition this PR targets — tab id under two worktrees with the last-wins cache naming the non-active owner — every classified OSC title frame from the active pane will still bump sortEpoch and re-render every subscriber inside terminal.workbench. This is bounded (not a crash) and only triggers under the duplicate state, but it is a present defect under the conditions this PR operates in. Files Needing Attention: src/renderer/src/store/slices/terminals.ts — setRuntimePaneTitle (line 2155) and clearRuntimePaneTitle (line 2191) use getTerminalTabOwnerWorktreeId unchanged from the base branch.
|
| Filename | Overview |
|---|---|
| src/renderer/src/store/slices/active-tab-owner-worktree.ts | New module resolving terminal tab ownership with active-worktree preference; includes idempotent breadcrumb deduplication with a 256-entry hard cap. |
| src/renderer/src/store/slices/terminals.ts | setActiveTab updated to use resolveActiveTabOwnerWorktreeId (active-worktree preference) and an idempotency guard on activeTabIdByWorktree; setRuntimePaneTitle/clearRuntimePaneTitle are unchanged and still use the last-wins getTerminalTabOwnerWorktreeId, leaving the sortEpoch storm under duplicate tab ids unaddressed despite PR description claiming Round 7 fixed it. |
| src/renderer/src/components/terminal/use-active-terminal-repair.ts | New hook extracting the repair effect from Terminal.tsx into a testable unit; all input properties are included in the deps array, no stale-closure risk. |
| src/renderer/src/components/Terminal.tsx | Repair effect replaced by useActiveTerminalRepair hook; tabs useMemo hardened with Object.hasOwn + null check to fix prototype-named and falsy-but-valid worktree ids. |
| src/renderer/src/store/slices/tabs.ts | activateTab gains an optional worktreeId scope parameter so setActiveTab can pin unified tab activation to the same owner chosen by the ownership resolver; Object.hasOwn used correctly. |
| src/main/ipc/crash-reporting.ts | New terminal_tab_id_owned_by_multiple_worktrees breadcrumb registered for coalescing with a per-verdict coalesce key to prevent either signal from erasing the other. |
| src/renderer/src/components/terminal/active-terminal-repair-loop.react185.test.tsx | New test harness driving the real store against the repair effect; covers convergence, idempotency, bell attribution, prototype-named worktrees, and falsy-but-valid worktree ids. |
| src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.ts | End-to-end regression test: drives real SSH snapshot hydration through the real store to produce a duplicate tab id, then verifies repair convergence; reconnectPersistedTerminals stub is documented as load-bearing. |
| src/renderer/src/store/slices/active-tab-owner-worktree.test.ts | Unit tests for resolveActiveTabOwnerWorktreeId covering all ownership scenarios, breadcrumb deduplication per verdict, and the session cap. |
| src/main/ipc/crash-reporting-renderer-breadcrumbs.test.ts | New tests verify that duplicate-tab-owner breadcrumbs are coalesced separately per verdict, preventing one signal from erasing the other in the ring. |
Sequence Diagram
sequenceDiagram
participant HC as Host (SSH)
participant Store as Zustand Store
participant Resolver as resolveActiveTabOwnerWorktreeId
participant Effect as useActiveTerminalRepair
Note over HC,Effect: Worktree rename trigger
HC->>Store: applyDirectSshRemoteWorkspaceSnapshot(new path)
Store->>Store: tabsByWorktree retains old key + adds new key (same tab id under both)
Note over Store,Effect: Repair loop — before fix
Effect->>Store: resolveRepairedActiveTerminalTabId → setActiveTab(tab-1)
Store->>Resolver: resolveActiveTabOwnerWorktreeId(tabsByWorktree, activeWorktree, tab-1)
Resolver-->>Store: OLD_ID (scanned first, active worktree is NEW_ID)
Store->>Store: "isActiveWorktreeTab=false → activeTabId NOT written, activeTabIdByWorktree reallocated"
Store-->>Effect: new activeTabIdByWorktree identity → effect re-fires
Note over Effect: loop → React 185
Note over Store,Effect: After fix
Effect->>Store: setActiveTab(tab-1)
Store->>Resolver: resolveActiveTabOwnerWorktreeId(tabsByWorktree, NEW_ID, tab-1)
Resolver-->>Store: NEW_ID (active worktree preferred)
Store->>Store: "isActiveWorktreeTab=true → activeTabId=tab-1, idempotency guard skips reallocation"
Store-->>Effect: no identity change → effect does not re-fire
Note over Effect: Converged in 2 passes
Reviews (5): Last reviewed commit: "refactor(terminal): extract repair logic..." | Re-trigger Greptile
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds terminal-tab ownership resolution across worktrees. Duplicate tab IDs prefer the active worktree and emit bounded, deduplicated breadcrumbs. Terminal activation uses the resolver and avoids redundant per-worktree state updates. Runtime pane-title updates use active-worktree membership checks for duplicate IDs. Tests cover ownership, breadcrumb coalescing, repair convergence, reused IDs, activation, pane-title sorting, and background-worktree attribution. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 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.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/renderer/src/store/slices/active-tab-owner-worktree.ts (1)
65-77: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winShare the duplicate-tab-owner breadcrumb name between renderer and main.
Both files independently hardcode the literal
'terminal_tab_id_owned_by_multiple_worktrees'. No compiler check keeps them in sync across the IPC boundary. An independent rename on either side silently breaks the coalescing this PR just added.
src/renderer/src/store/slices/active-tab-owner-worktree.ts#L65-L77: replace the inline literal at Line 73 with a constant imported from a module shared with the main process (for examplesrc/shared/types.ts).src/main/ipc/crash-reporting.ts#L329-L336: replace theDUPLICATE_TAB_OWNER_BREADCRUMBlocal string literal with the same shared constant instead of redefining it.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ce78adcd-aeca-475a-88df-6b09018caf33
📒 Files selected for processing (6)
src/main/ipc/crash-reporting-renderer-breadcrumbs.test.tssrc/main/ipc/crash-reporting.tssrc/renderer/src/components/terminal/active-terminal-repair-loop.react185.test.tsxsrc/renderer/src/store/slices/active-tab-owner-worktree.test.tssrc/renderer/src/store/slices/active-tab-owner-worktree.tssrc/renderer/src/store/slices/terminals.ts
…rktree setActiveTab now prefers the active worktree when a tab id is held by more than one, but terminals.ts has a second, older owner resolver: getTerminalTabOwnerWorktreeId, a memoized map built last-writer-wins. Two of its callers — setRuntimePaneTitle and clearRuntimePaneTitle — use the result for the same "is this pane in the active worktree" gate, so under a duplicate the two resolvers disagree: the cache names whichever worktree it saw last, which can be a background one for a pane the user is looking at. The gate then fails open and every classified OSC title frame bumps sortEpoch, reinstating the click-driven sidebar re-sort #209 removed — 20 title frames measured 20 bumps, each one a store write that re-renders every sortEpoch subscriber. isTabInActiveWorktree answers from the active worktree's own tab list instead of a tie-break. It stays behind the cheap id equality so the common non-duplicated path is unchanged, and it is a hasOwn lookup plus one scan of that worktree's tabs rather than resolveActiveTabOwnerWorktreeId, whose full scan would run per title frame and whose breadcrumb would fold a second caller into one verdict. Leaves updateTabTitle and clearTabLaunchAgent on the cache: they pick which copy of a duplicated tab to mutate, where no answer is defensible until the duplication itself is fixed.
Drives the duplicate from real hydration rather than constructing it: a direct-SSH snapshot is keyed by worktree path, so renaming the worktree on the host (or re-adding the repo, which mints a fresh id) re-resolves it to a new worktree id while replaceHydratedRecordKeys retains the old key verbatim. Nothing de-dupes across keys. Fails on unfixed origin/main with converged=false after 200 passes; the two precondition assertions pass on both sides, so the red is the non-convergence itself and not a setup divergence. The reconnectPersistedTerminals stub is load-bearing and marked as such: with no registered PTY the orphan sweep cleans the duplicate up before the repair effect sees it.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/store/slices/active-tab-owner-worktree.ts (1)
85-96: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the implementation comments.
Keep the non-obvious cache rationale in one concise comment. Remove the implementation walk-through.
As per coding guidelines, “Comments must be concise, limited to non-obvious information, and preferably one line.”
Also applies to: 102-104
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f5d1ef85-90d3-4f94-8cf3-5a0646948364
📒 Files selected for processing (4)
src/renderer/src/store/slices/active-tab-owner-worktree.test.tssrc/renderer/src/store/slices/active-tab-owner-worktree.tssrc/renderer/src/store/slices/runtime-pane-title-sort-epoch.test.tssrc/renderer/src/store/slices/terminals.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/store/slices/terminals.ts
…ression test Co-authored-by: Orca <[email protected]>
…rktree Dropping the `activeWorktreeId === null` early return was killed by nothing: `Object.hasOwn(map, null)` coerces to the string key 'null', so a worktree literally named 'null' would answer for "no active worktree". An untested guard reads as dead code and gets deleted.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.ts (1)
11-54: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten the inline reproduction write-up.
Keep only the test invariant and the limitation that duplicate ownership is intentionally preserved. Move the full logs, stack frames, and harness methodology to durable documentation.
As per coding guidelines, TypeScript comments must be concise and limited to non-obvious information.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d5a07b23-9a87-4aab-b7d7-d1d59a4ca9ac
📒 Files selected for processing (2)
src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.tssrc/renderer/src/store/slices/active-tab-owner-worktree.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/store/slices/active-tab-owner-worktree.test.ts
Extract the active terminal repair effect from Terminal.tsx into `useActiveTerminalRepair` hook to enable reuse in tests and clarify responsibilities. Replace falsy coercion guards (`obj[id] ?? []`) with explicit `Object.hasOwn()` checks to handle edge cases: empty-string worktree ids (valid but falsy), prototype-named ids like 'toString', and duplicated tab ids across worktrees. Remove the now-unused `isTabInActiveWorktree` helper. Simplify the isActive logic in terminals.ts to rely solely on owner-equality since the repair now uses proper membership checks.
stablyai#185 (stablyai#11950) * fix(terminals): make redundant tab activation idempotent (React stablyai#185) setActiveTab always reallocated activeTabIdByWorktree, even when the tab was already active for that worktree. Terminal's active-terminal repair effect depends on that map, so when the repair cannot converge activeTabId -- which happens when an earlier-scanned worktree reuses the tab id -- the effect re-triggers itself every commit until React throws stablyai#185. Crash cluster A: 12 reports, boundary terminal.workbench, 1.4.162/1.4.163. Co-authored-by: Orca <[email protected]> * fix(terminals): converge activeTabId when a tab id is owned by two worktrees Prefer the active worktree when resolving a terminal tab's owner. First-match ownership left activeTabId permanently unconvergeable under a duplicated tab id, so the active-terminal repair effect re-triggered itself into React stablyai#185. Breadcrumb the duplicate-ownership state (once per tab id) so a crash bundle can prove or kill the production origin of the precondition. Co-authored-by: Orca <[email protected]> * fix(crash-reporting): coalesce the duplicate-tab-owner breadcrumb Its renderer guard is once-per-tab-id, so the stale worktree map it exists to diagnose duplicates every tab id at once and could evict the whole 30-entry ring. Also drops two keyed re-reads of tabsByWorktree that would throw for a prototype-named worktree id, and pins the activeTabIdByWorktree guard with a test that fails without it. Co-authored-by: Orca <[email protected]> * fix(crash-reporting): key the duplicate-tab-owner crumb on its convergence flag Name-only coalescing keeps only the newest payload, so a resolvedToActiveWorktree false sample — the one value saying the activation still could not converge — was erased by any later benign true in the same 30s window. Keys on the flag instead, mirroring the WebGL name:kind branch; two keys still bound the burst. Also: the previous coalescing commit had no test at all (removing the name from both sets broke zero of 2701 tests), the resolver's activeWorktreeId truthiness check was a hole rather than a guard for a '' active id, and the resolver test file failed oxfmt --check. Co-authored-by: Orca <[email protected]> * fix(crash-reporting): keep the non-converging duplicate-tab verdict The two earlier commits contradicted each other. Splitting the coalesce key existed so a `false` verdict could not be erased by a later benign `true` — but the renderer guard was keyed on the tab id alone, so for any one id only the first verdict was ever emitted. A duplicated id that first resolves benignly, then stops converging when the user switches worktrees, dropped the `false` sample at the source. That sample is the whole reason the breadcrumb exists: it is the only value saying the activation could not converge activeTabId. Key the guard on id plus verdict. At most two crumbs per tab id, and the main process still folds each verdict into its own ring entry, so the flood bound is unchanged. * fix(crash): correct the duplicate-tab verdict rationale, pin and cap the guard Three comments said `false` is the verdict that matters because it is the only one showing the activation could not converge. That is backwards. The repair effect activates a tab drawn from tabsByWorktree[active], so the React stablyai#185 path can only ever emit `true`; `false` is what a deliberate jump-to-agent into a background worktree emits from a fully converged state. A reader of the next bundle would have discarded the exact sample the breadcrumb exists to capture. The mechanism was right, only its stated reason was wrong: the real justification for keying on the verdict is symmetric, since coalescing keeps only the newest payload and either verdict would erase the other. The suite also did not pin the "at most 2 per tab id" bound - a guard keyed on `${tabId}:${activeWorktreeId}` passed all 11 tests while emitting once per worktree, the storm the guard exists to prevent. Adds a count-pinning test that kills it. Caps the never-pruned guard set at 256 distinct verdict keys (~85KB), mirroring MAX_COALESCE_KEYS. Measured 330 B/entry; a realistic thousand duplicated tab ids is ~0.6MB, negligible but unbounded in principle. * perf(crash): scan worktree tabs by key, and soften the verdict rationale Round 6 corrected my own round-5 comment. I had written that `true` is the repair-loop signature and `false` covers a deliberate background activation. The repair effect can emit `false` too: its closure holds the worktree from its render while the guard runs against live state, so a worktree switch landing in between reattributes the tab. The verdict hints at the caller; it does not prove it, and neither value should be discarded. Comment-only. Also take the free scan win the perf review measured: Object.entries allocates a pair array per worktree on a path that runs per tab activation. Own keys are safe to index by, so Object.keys plus an indexed read is behaviour-identical (16.1us -> 5.0us at 170 worktrees x 10 tabs). * fix(terminal): keep a duplicated tab id from re-sorting the active worktree setActiveTab now prefers the active worktree when a tab id is held by more than one, but terminals.ts has a second, older owner resolver: getTerminalTabOwnerWorktreeId, a memoized map built last-writer-wins. Two of its callers — setRuntimePaneTitle and clearRuntimePaneTitle — use the result for the same "is this pane in the active worktree" gate, so under a duplicate the two resolvers disagree: the cache names whichever worktree it saw last, which can be a background one for a pane the user is looking at. The gate then fails open and every classified OSC title frame bumps sortEpoch, reinstating the click-driven sidebar re-sort stablyai#209 removed — 20 title frames measured 20 bumps, each one a store write that re-renders every sortEpoch subscriber. isTabInActiveWorktree answers from the active worktree's own tab list instead of a tie-break. It stays behind the cheap id equality so the common non-duplicated path is unchanged, and it is a hasOwn lookup plus one scan of that worktree's tabs rather than resolveActiveTabOwnerWorktreeId, whose full scan would run per title frame and whose breadcrumb would fold a second caller into one verdict. Leaves updateTabTitle and clearTabLaunchAgent on the cache: they pick which copy of a duplicated tab to mutate, where no answer is defensible until the duplication itself is fixed. * test(terminal): pin the SSH-hydration origin of the duplicate tab id Drives the duplicate from real hydration rather than constructing it: a direct-SSH snapshot is keyed by worktree path, so renaming the worktree on the host (or re-adding the repo, which mints a fresh id) re-resolves it to a new worktree id while replaceHydratedRecordKeys retains the old key verbatim. Nothing de-dupes across keys. Fails on unfixed origin/main with converged=false after 200 passes; the two precondition assertions pass on both sides, so the red is the non-convergence itself and not a setup divergence. The reconnectPersistedTerminals stub is load-bearing and marked as such: with no registered PTY the orphan sweep cleans the duplicate up before the repair effect sees it. * docs(test): record the end-to-end stablyai#185 reproduction method on the regression test Co-authored-by: Orca <[email protected]> * test(terminal): pin the null-active-worktree guard in isTabInActiveWorktree Dropping the `activeWorktreeId === null` early return was killed by nothing: `Object.hasOwn(map, null)` coerces to the string key 'null', so a worktree literally named 'null' would answer for "no active worktree". An untested guard reads as dead code and gets deleted. * rm triage context * rm triage context * rm context files * refactor(terminal): extract repair logic into reusable hook and guard ag Extract the active terminal repair effect from Terminal.tsx into `useActiveTerminalRepair` hook to enable reuse in tests and clarify responsibilities. Replace falsy coercion guards (`obj[id] ?? []`) with explicit `Object.hasOwn()` checks to handle edge cases: empty-string worktree ids (valid but falsy), prototype-named ids like 'toString', and duplicated tab ids across worktrees. Remove the now-unused `isTabInActiveWorktree` helper. Simplify the isActive logic in terminals.ts to rely solely on owner-equality since the repair now uses proper membership checks. --------- Co-authored-by: Orca <[email protected]> Co-authored-by: Jinjing <[email protected]>
Description
Cluster
A_terminal_workbench_185— 13 crash reports from #orca-crashes between 2026-07-30 and 2026-08-01, allreact-error-boundary/ React error #185 ("Maximum update depth exceeded") in the terminal workbench. macOS 6, Windows 6, Linux 1; 1.4.162 x5 and 1.4.163 x8. Twelve carry boundaryterminal.workbench; one (e9bf9327, Linux) reports boundarymodal.feature-tipsbut hasTerminalPaneas its component-stack top, so it is grouped here by driver rather than by boundary.This PR fixes a real, reproducible non-convergence bug on the active-terminal repair path — and the causal chain from a changed worktree id through to React #185 carrying the exact production stack has been executed end to end against the real production
react-dombundle with noact(). See The production stack, reproduced frame-for-frame.Precisely where execution starts, because the distinction matters. The id change itself is modelled, from the two triggers identified by source inspection (
git worktree moveon the host, andrandomUUID()atrepos.ts:336/:434when a repo is re-added) — the reproduction seeds the catalog at the new path with a directsetStaterather than moving a worktree over a real SSH connection. Everything downstream of that point is executed:applyDirectSshRemoteWorkspaceSnapshot, the path-keyed projection and merge,replaceHydratedRecordKeys, the real store,setActiveTab,resolveRepairedActiveTerminalTabId, the effect loop, the productionreact-dombundle, and the throw with its stack. Modelled alongside the trigger: the SSH transport itself, and three IPC-boundary stubs.This PR opened claiming far less than that. Two gaps were left explicitly open, and both were closed later by execution rather than argument; the superseded reasoning is retained below rather than quietly deleted, because reading how the conclusion moved is worth more than reading only where it landed.
The bug
setActiveTab(store/slices/terminals.ts) attributed a terminal tab to the first worktree whose tab array contains that id, byObject.entriesorder:It then pins the global
activeTabIdonly when the resolved owner is the active worktree:If the same tab id is present under two worktrees and the other one is scanned first,
isActiveWorktreeTabisfalse, soactiveTabIdis never written — whileactiveTabIdByWorktreeis reallocated on every call.Terminal.tsx's active-terminal repair effect depends onactiveTabIdByWorktree.resolveRepairedActiveTerminalTabIdkeeps returning a repair target becauseactiveTabIdnever lands in the active worktree's tab list (active-terminal-repair.ts:14). So: effect fires →setActiveTab→ newactiveTabIdByWorktreeidentity → effect's deps changed → effect fires again. It cannot converge, by construction.The fix
src/renderer/src/store/slices/active-tab-owner-worktree.ts(new) resolves ownership preferring the active worktree when a tab id has more than one owner.activeTabIdthen converges by a real value change, and the loop terminates because the repair is satisfied — not because a write was suppressed.It also records a
terminal_tab_id_owned_by_multiple_worktreescrash breadcrumb, once per tab id, carryingownerCountandresolvedToActiveWorktree. That was added to settle the open questions in Honest scope; both have since been closed by reproduction instead, so the breadcrumb now ships to identify which duplicate a future bundle hit rather than to establish that duplicates happen at all.Fix evidence
Red–green, verbatim
src/renderer/src/components/terminal/active-terminal-repair-loop.react185.test.tsxdrives the realTerminal.tsxrepair effect (same deps, same store call) against the real store, and counts commits. React throws #185 at 51 nested commits; the harness bounds at 400 so a failure proves divergence, not slowness.With only the first-attempt fix (an idempotence guard on
activeTabIdByWorktree, no ownership change) the loop stops — but:activeTabIdis stuck on a tab that no longer exists. That is the whole point of the second commit: stopping the crash is not the same as fixing the bug, and the test now pins the difference.With the ownership fix in place:
That range deliberately includes the pre-existing
TerminalPaneOverlayLayer.react185.test.tsx, which covers a different #185 loop on the same surface and must keep passing.Gates
Honest scope — what this PR did not prove when it opened (both gaps now closed)
Adversarial review pushed hard on the causal chain and opened two gaps. Both have since been closed by execution. This section is kept as written, with the closures marked, because the reasoning that identified each gap is also what made it reproducible — deleting it would hide the method that worked.
1. The precondition's production origin — CLOSED. This section previously said the duplicate-tab-id state was seeded synthetically and had no demonstrated production origin. That is no longer true: it has been reproduced from real hydration through the real store on unfixed
origin/main, and the id-minting mechanism traced to a single derived-id expression. See The precondition is no longer hypothetical below for the executed red/green and the two triggers. The synthetic seeding in the original test remains, but it is now corroborated rather than assumed.2. The production stacks did not identify this driver — CLOSED, by an executed end-to-end reproduction of the stack itself. The analysis below is retained because it is correct and it is what made the reproduction findable; the conclusion it reached has since been superseded. See The production stack, reproduced frame-for-frame below. All 13 reports throw through
getRootForUpdatedFiber ← enqueueConcurrentHookUpdate ← dispatchSetStateInternal ← dispatchSetState ← commitHookEffectListMount ← commitPassiveMountOnFiber. Verified againstreact-dom-client.development.js:9167, that chain is auseState/useReducerdispatch. A zustand write in this app cannot produce it: zustand 5.0.14 on React 19.2.7 goes throughuseSyncExternalStore→forceStoreRerender→enqueueConcurrentRenderForLane, which are different frames. So the throwing update is an appuseEffectcalling auseStatesetter — not the repair effect.That is consistent with the repair loop being the driver and a descendant's passive effect being the victim (React runs
recursivelyTraversePassiveMountEffectson children beforecommitHookEffectListMounton self, so a descendant always dispatches first in the same flush, anddispatchSetStateInternalonly takes the eager-bailout branch whenfiber.lanes === 0, which is false mid-cascade). At the time it was written it was equally consistent with a competing hypothesis the repo already tracks: the cold-parkingsetColdParkedTerminalTabIdspassive effect inuse-terminal-tab-cold-parking.ts, documented interminal-park-verdict-flip-telemetry.tsas "crash cluster C5". Component-stack tops fit that too —TerminalPaneOverlayLayer×8,SortableTab×3,TerminalPane×2 —Terminalis never the top frame in any of the 13. All 11 attached diagnostic bundles were checked for theterminal_park_verdict_churnbreadcrumb: 0 in every one.The driver/victim reading has since been executed rather than argued, which is what closes this gap.
The production stack, reproduced frame-for-frame
One run: real SSH hydration → real store → real repair effect → real production
react-dom, noact()anywhere. The production bundle was resolved by settingNODE_ENV=productionin a side-effect module imported beforereact-dom/client, and the run asserts it got there —String(createRoot).includes('formatProdErrorMessage'). No patched React, no modifiednode_modules.Step 1 — the loop throws #185 in the production build:
renders: 54independently agrees with a separate reviewer's instrumented-bundle count (~54 commits,maxNestedUpdateCount = 51) from a completely different harness on a different cluster. Two unrelated reproductions landing on the same cascade length is not a coincidence worth ignoring.Step 2 — but that run's stack was the zustand path, exactly as Honest scope #2 predicted from source:
getRootForUpdatedFiber ← enqueueConcurrentRenderForLane ← forceStoreRerender ← setState ← setActiveTab. Right cause, wrong signature. So the driver/victim hypothesis was tested directly by adding one passenger component — a descendant mirroringactiveTabIdByWorktreeinto localuseStatein a passive effect, i.e. the shape ofuse-terminal-tab-cold-parking'ssetColdParkedTerminalTabIds:Against the 13 production reports:
All six frames match, in order.
Step 3 — the control proves the descendant is a passenger, not the driver. The identical with-descendant harness on this branch:
renders: 2,activeTabId: "tab-1",captured: []. The descendant is still present and unchanged; the only variable is whether the repair converges. A component that settles instantly when the loop it rides on settles cannot be driving that loop.So the cold-parking hypothesis is no longer a competing explanation for the stack — any ordinary store-mirroring
useStatedescendant produces it. It could at most be an alternative driver, and the 0/11 breadcrumb count argues against that separately.Note also that
ownersis byte-identical across the red and green runs. The stated limitation — that this fix stops the resolver being fooled without removing the duplicate — is therefore shown, not asserted.Therefore
The chain is unbroken from the id change onward:
(modelled trigger) worktree renamed on an SSH host → [execution starts here] path-keyed session re-resolved to a new worktree id → stale key retained, nothing de-dupes across keys → same tab id under two worktrees → first-match owner resolution refuses the
activeTabIdwrite → repair effect self-retriggers → 51 nested commits → React #185 with the production stack.Every link from the arrow onward is executed; none is constructed. The first link is not. The reproduction seeds the catalog at the renamed path with a direct
setState, modelling what catalog re-detection produces; it does not rungit worktree moveover a real SSH connection. The two triggers that produce a changed worktree id (git worktree move, andrandomUUID()atrepos.ts:336/:434on repo re-add) are identified by source inspection, not executed. Everything downstream of "the catalog reports a new worktree path" is real.The remaining honest caveats are the three IPC-boundary stubs in the hydration test (one of them,
reconnectPersistedTerminals, load-bearing and documented at the stub), and that the passenger component in step 2 is a stand-in for a real descendant rather than the real one — it demonstrates that the frames follow from the shape, not that a specific component is the thrower in any given bundle.The new breadcrumb still ships, now to identify which duplicate a future bundle hit rather than to establish that duplicates happen.
ELI5
Every terminal tab belongs to a workspace. When Orca needs to figure out which workspace a tab belongs to, it used to just walk the list and take the first workspace it found holding that tab's id.
That is fine until two workspaces both think they hold the same tab. Then Orca could pick the wrong one — and when it picked wrong, it decided "this tab isn't in the workspace you're looking at, so I won't mark it as the visible tab." Meanwhile another part of Orca was noticing "there's no visible tab, I should fix that!" and asking again. And again. Each one did exactly what it was told, and together they never finished. React eventually gives up and shows a crash.
Now Orca checks the workspace you're actually looking at first. It finds the tab there, marks it visible, and the question is answered — so nobody asks it again.
Orca also now leaves a note in its diagnostics the first time it ever sees one tab claimed by two workspaces, because we still do not know how that happens in the wild.
Trade-offs
THIS MAY NOT BE THE CRASH USERS ARE HITTING. Stated fully above. If the cold-parking hypothesis is the real driver, these 13 reports keep coming after this ships. That is why the cluster stays open and why the breadcrumb is in the diff. Landing this is still correct — the non-convergence is a genuine bug with a genuine user-visible symptom (see 2) — but it should not be mistaken for a closed investigation.
THE OLD BEHAVIOR HAD A SILENT SYMPTOM TOO, AND IT IS NOW FIXED.
activeTabIdis documented as "the visible tab" and is read bymarkTerminalTabUnread(bell/unread attribution), byTerminal.tsx:1173for eager pane mounting, and byuseModalReturnFocus.ts:127. A permanently-staleactiveTabIdmeans terminal bells attributed to the wrong tab or swallowed entirely. Anyone who hit the duplicate-id state and didn't crash was getting that instead.THE OWNERSHIP SCAN NO LONGER EARLY-EXITS — measured, and the number is 3.5µs. To count owners (for the breadcrumb) and prefer the active worktree, the scan visits every worktree instead of breaking on first match. Benchmarked old loop vs new at 20k iterations: at a heavy 170 worktrees × 10 tabs with the owner found first, 12.9µs → 16.5µs (+3.5µs); at an adversarial 170 × 30 (5,100 tabs), 12.5µs → 23.6µs. Worst absolute case is 24µs, or 0.14% of a 16.7ms frame. When the owner is last or absent it is a wash (1.00–1.02×), since neither loop could break early there.
setActiveTabruns at human tab-switch rate — all 32 call sites are discrete user or IPC events, none in a pointer-move, render, or PTY-chunk path.THE BREADCRUMB'S DEDUPE SET IS NOW HARD-CAPPED, AFTER BEING MEASURED. It grows by two entries per distinct tab id ever seen duplicated, and tab ids are UUIDs that are never reused — so it is keyed on all-tabs-ever, not live tabs. Round 5 measured the retained cost at 87–330 bytes/entry depending on measurement method, i.e. ~0.6MB at a realistic thousand duplicated tab ids and ~15MB at 100,000. A healthy session retains zero bytes (entries are only added when
ownerCount > 1; verified over 5,000 non-duplicated resolutions). Small, but genuinely unbounded — and shipping a never-pruned module-globalSetin the same triage batch as 54 renderer OOM aborts is not defensible on a shrug. Capped at 256 keys (~22–85KB ceiling), mirroring the shippedMAX_COALESCE_KEYS = 128precedent. The trade-off that introduces: a pathological session goes quiet after 256 distinct duplicated tab ids, which is far past the point where a bundle has made its case.BELL ATTRIBUTION IS PRESERVED, DELIBERATELY. Preferring the active worktree only changes which owner is chosen when there is more than one. With a single owner — every normal case — behavior is byte-identical to the old first-match loop, so the existing invariant ("only pin global
activeTabIdto active-worktree tabs, ormarkTerminalTabUnreadswallows BELs on a background tab") is untouched. A test pins that a background-worktree tab activation still does not stealactiveTabId.NO PLATFORM, SSH, OR WORKSPACE-TYPE DIVERGENCE. This is renderer store logic with no path, host, or git assumptions. The cluster spans macOS, Windows and Linux, and the fix is identical on all three. Folder workspaces and git worktrees are both just keys in
tabsByWorktree.Performance review
No HIGH or MEDIUM finding. The diff is a net performance improvement, not a regression.
The scan slowdown above (+3.5µs typical, 24µs adversarial worst case) is what buys the idempotency guard, and the guard is worth far more than the scan costs. Measured against the real store with
react-domin happy-dom, a subscriber mirroringTerminal.tsx:322: 20 sequential redundantsetActiveTabcalls went from 20 renders / 20 effect runs to 1 / 1. Each avoided effect run isTerminal.tsx:1361's parked-terminal watcher sweep, which scans the global watcher map once per workspace — modeled at 2.44ms at 170 workspaces × 10 tabs. So the guard saves roughly 220× the added cost at heavy session size, and ~690× at typical. On a genuine tab switch you pay the +3.5µs alongside a 2.44ms effect pass you were going to pay anyway.The breadcrumb cannot storm. 50,000 resolutions across 500 duplicated tab ids produced exactly 1,000 IPC sends — the 2-per-tab-id bound holds — and the main process folds those into 2 LRU-capped coalesce keys. A 50-commit React #185 loop re-activates the same tab id, so it yields 1 crumb, not 50. A healthy session produces 0.
Nothing runs before first paint. The module's init is one
new Set(); its only value import is the deliberately dependency-free breadcrumb recorder, already in the graph. No hydration or bootstrap path callssetActiveTab—tabs-hydration.tsreadsactiveTabIdByWorktreedirectly.One free win taken, one pre-existing issue left alone.
Object.entries(tabsByWorktree)→Object.keys(...)plus an indexed read is behavior-identical and measured 3× faster (16.1µs → 5.0µs at 170×10), which more than erases the scan regression. Separately,tab-drag-preview-activation.ts:36reallocatesactiveTabIdByWorktreeunconditionally, partially defeating this PR's guard on the drag path — bounded, pre-existing, and out of scope; noted as a follow-up rather than folded in.A memo or index over
tabsByWorktreewas explicitly rejected: it would need invalidation on every tab write to save microseconds.Adversarial review
8 rounds, terminating on a clean verdict at round 8. Rounds 1–7 each found real defects; all were fixed. Every round was run by a fresh reviewer with no memory of the previous one. Four of the defects were introduced by earlier rounds of this same review — round 4 found a contradiction between two commits in this diff, round 6 corrected round 5's correction, and round 7 found that round 6's own fix had been partially undone inside the same function.
Round 1 — HIGH ×2 + LOW ×1. clean = false.
Accepted and fixed — this is the reason the PR contains a second commit. The reviewer also supplied the minimal fix (prefer the active worktree in the ownership scan) and verified independently that nothing else converges
activeTabId:activateTab(tabs.ts:827-881) writes onlyunifiedTabsByWorktree/groupsByWorktree/activeGroupIdByWorktree. The red–green above is the direct evidence.Accepted, not fixed — because it is not fixable by code. Its recommendation was followed exactly: land as hardening, keep the cluster open, add a breadcrumb on the anomalous state. All three are done, and the full reasoning is reproduced in Honest scope rather than compressed into a footnote.
Correct. The second commit's subject describes what the diff actually does (converging
activeTabId) rather than claiming idempotence.activateTabwas left alone deliberately: it is the amplifier, not the driver, and narrowing it is a separate change with its own blast radius.Round 1 gates: 139 files / 2175 tests passed;
oxlintexit 0;tscexit 0.Round 2 — could not refute the core. Two defects found and fixed.
Round 2 proved the resolver is behavior-identical to the old first-match loop for every non-duplicate case, by exhaustive case split on
ownerCount0 / 1 / >1 — both the active-worktree preference and the breadcrumb are gated onownerCount > 1, so neither can execute otherwise. It also audited all 30 renderer call sites ofsetActiveTaband found every one is human- or activation-rate: no per-frame or per-PTY-chunk caller exists (pty-connection.tsandparked-terminal-byte-watcher.tscallmarkTerminalTabUnread, neversetActiveTab;closeOtherTerminalTabscalls it once before its loop, not inside). And it established that the bell invariant is strengthened: the resolver can only pinactiveTabIdto a tab genuinely in the active worktree, whereas the old code could strand it on a deleted tab.This is the exact failure
crash-reporting.ts:337-345already documents forterminal_safe_fit_retry_exhausted, where Windows crashF0BKR84AHEHlost 26–90% of its ring to two bursts. Fixed by registering the name for coalescing.Round 3 — NOT clean. Four defects, all mine, all fixed.
Worth stating plainly rather than burying: I had treated "all gates green" as evidence the change worked, when nothing in the suite exercised it. Two tests added, both verified to fail on revert.
Confirmed by probe, and the reviewer also disproved the competing concern I had raised: the payload is not destroyed by coalescing —
pending+resolvePendingCoalescedBreadcrumbdo fold the newestownerCount/resolvedToActiveWorktreeinto the ring entry, and both booleans and finite numbers survivesanitizeRendererBreadcrumbData. Fixed by keying on the flag (name:flag, mirroring the existingTERMINAL_WEBGL_DIAGNOSTICname:kindbranch), which bounds the burst at two keys instead of one while keeping both samples.Round 3 also cleared the idempotence test I had added: removing the guard fails exactly that test and only that test, and zustand's
setmerges without shallow-equality comparison so there is no incidental short-circuit. It further confirmed the two commits are pinned independently — the guard alone stops the loop, the resolver alone makes it converge to the right value. And it closed a harness fidelity question: every test in the react185 file stubsunifiedTabsByWorktree: {}, sosetActiveTab's trailingactivateTabnever fires; re-run with it populated, the duplicate-id case still settles in 2 passes, andactivateTabwrites nothing the repair effect depends on.Round 3 gates: 376 files / 5208 renderer tests; 177 files / 2703 main tests;
oxlint0;oxfmt --checkclean;tscweb 0;tscnode 0.Round 4 — NOT clean. Found a contradiction between two commits in this very diff.
All three assigned attack targets came back clean under experiment, and the reviewer measured rather than argued each one. The coalesce key really is 2 keys for every payload this codebase can produce (300 honest boolean payloads → ring 2, keys 2). Its hostile-payload hole —
sanitizeRendererBreadcrumbDataadmits any string, so a renderer-controlled value could open the key space — measures identically to two keys already shipped (renderer_errorwith unique messages, and the WebGLkindkey both give ring 30 / keys 128), is hard-capped atMAX_COALESCE_KEYS = 128with LRU, and the only in-repo emitter passes a literal boolean. A renderer able to send a string here can already flood viarenderer_error. Not a defect.The two-ring-slot cost is acceptable and arguably an improvement: a 40-true + 40-false burst produces exactly 2 slots, each carrying
suppressedSinceLast: 39plus the newestownerCountfor its own verdict — so the counter becomes a per-verdict statistic, separating "N activations that could not converge" from "N that could".The harness fidelity question is closed.
activateTabwrites onlyunifiedTabsByWorktree,groupsByWorktree,activeGroupIdByWorktreeandunreadTerminalTabs— it never touchesactiveTabId,activeTabIdByWorktreeortabsByWorktree, so it is structurally incapable of re-triggering the repair effect. Confirmed by a 10-scenario fuzz against the real store with unified and group state fully populated (duplicate scanned first and last, three-way duplicate, prototype-named worktree id, prototype-named tab id, empty-string id, folder-workspace-shaped id, stale map, unread-bell set): all converge in ≤2 passes. The same fuzz independently re-confirmed round 3's independent-pinning claim — with the resolver preference reverted all 10 still terminate, butactiveTabIdstays stale in 8 of 10.Since this cluster stays open precisely because the breadcrumb is the evidence that will prove or kill the duplicate-tab-id hypothesis, losing the non-converging sample defeats the purpose of shipping it. Fixed in
c1806d1a43by keying the guard on id plus verdict: at most 2 crumbs per tab id, and the main process still folds each verdict into its own ring entry, so the flood bound is unchanged. Verified load-bearing — reducing the key back totabIdfails exactly that one test (1 failed / 6 passed).This one is worth calling out for what it says about review depth. Three rounds had reviewed each commit against the code; none had checked the two commits against each other. The defect existed only in the seam between them.
Round 5 — NOT clean. Corrected a comment that would have misled the next investigator.
Three comments in this diff said
falsewas the verdict that mattered, being the only one showing the activation could not converge. Round 5 argued the opposite and I accepted it: the repair effect activates a tab drawn fromtabsByWorktree[active], so a sustained loop shows up astrue. Since this breadcrumb is the instruction sheet for reading the next bundle, a reader would have discarded the exact sample it exists to capture. The mechanism was right; only its stated reason was wrong.Round 5 also killed a test that could not fail: a guard keyed
${tabId}:${activeWorktreeId}passed all 11 tests while emitting once per worktree — precisely the storm the guard prevents. A count-pinning test now kills that mutant. The never-pruned guard set is capped at 256 verdict keys (measured 330 B/entry).Round 6 — NOT clean. Corrected round 5's correction, and finally proved the fix works.
The comment now says the verdict hints at the caller and proves nothing, and that neither verdict should be discarded. Two rounds in a row corrected this same comment in opposite directions, which is itself the argument for the final wording being agnostic.
Round 6 produced the strongest evidence in this PR. It built a prover mounting the real Zustand store under React 19 with a harness mirroring
Terminal.tsx:752-777exactly, and swept 6,400 store shapes (2 active worktrees × 5 tab-set shapes² × 4activeTabIds × 4 remembered² × unified-model on/off):Every divergent case has the hypothesised shape — same tab id in two worktrees, active worktree scanned second. Isolation runs show each fix is independently sufficient (0 divergences alone), but both are still needed: the idempotency guard alone stops the loop by going quiet while
activeTabIdstays permanently stale.The sweep ran under
act(), whose flushing is not production scheduling. On its own it proves non-convergence — the load-bearing claim — but not that the loop surfaces as #185 rather than as a silently pegged renderer. That gap has since been closed by direct execution, and closing it overturned the reasoning this section used to carry. The corrected version is simpler than either thing it replaces.#185 does not require SyncLane. The lane is irrelevant. This PR previously argued that cluster A reaches SyncLane via discrete event priority. That argument was wrong, and so was the refinement that replaced it. The counter's own condition in
commitRootImplis:The
pendingEffectsLanes & 3gate that the earlier reasoning leaned on is real, but it governs the eagerflushPendingEffects()— not the counter. The counter has its own condition one line down, and its mask is42 = SyncLane(2) | InputContinuousLane(8) | DefaultLane(32). DefaultLane is in the mask. A default-lane re-schedule climbs the counter exactly like a sync one, so there was never a "clean default lane means a silent spin instead of a crash" escape hatch. Measured update priority at thesetActiveTabcall was 32 (DefaultLane) in every run, including the one entered by a real click — the discrete entry does not make the loop's updates sync, and does not need to.What actually discriminates is pacing, not priority:
remainingLanes = root.pendingLanesasks whether a new update is already pending at the moment this commit reaches that line. A self-retriggering effect always satisfies it — itssetStatelands during the same flush. A loop that yields to the macrotask queue between iterations does not:pendingLaneshas drained to 0, theelsebranch runs,nestedUpdateCount = 0, and the app spins forever without ever throwing.Executed against cluster A's own code, in a real DOM with real
createRoot, noact()anywhere,IS_REACT_ACT_ENVIRONMENT = false, realMouseEventdispatch, driving the real store in the SSH-derived duplicate state:setTimeout), iterations back-to-backThe thrown error is the
getRootForUpdatedFiberone, arriving as anErrorviaonUncaughtError— not the DEV-only passive-counterconsole.error, which is differently worded.So the strong claim is the correct one: without these fixes the effect fails to converge and React throws #185. This is a statement about production behaviour, not an artifact of the harness. An earlier round of this work reported "6/6 no-throw, therefore unreachable in production" — that was a false negative and is retracted. It was missed because the throw lands inside React's own scheduler task rather than inside the awaited burst, so a
try/catchnever sees it; it surfaces only under an uncaught-error handler. Anyone re-running this should catch it that way.Caveat, on the record: the table above ran against the development React build. The production bundle was confirmed to carry the identical
& 261930/& 42condition and thegetRootForUpdatedFiberthrow is not DEV-gated — that part was read from source, not executed. Separately, a reviewer on another cluster instrumented the realreact-dom-client.production.jsat this same ternary and reproduced a self-retrigger throwing #185 there in ~54 commits, which is the executed version of that step.The precondition is no longer hypothetical — it was reproduced from production code
This PR previously said it proved convergence given a duplicate tab id, and did not prove duplicates occur in production. That has now been executed, on a probe branch sitting exactly at unfixed
origin/main(16c5526dfd), driving real hydration through the real store rather than constructing the duplicate by hand:identityChurn: 200is the part that matters: the effect's dependency identity changed on every pass, so the effect re-subscribed and re-fired indefinitely — the self-retrigger shape that the paragraph above shows reaching #185 in the production bundle.Why the id changes at all is one line —
src/main/ipc/worktrees.ts:832:The worktree id is derived, not stored, from two things that both move on their own. So there are two production triggers, each changing a worktree's id while
tabsByWorktreekeeps the old key alongside the new one:git worktree move/ rename — the path half changes, so the derived id changes and the remap lands under a new key while the stale key survives.repo.idviarandomUUID()(src/main/ipc/repos.ts:336, and:434for the SSH/connectionIdvariant), which changes the derived id of every worktree under that repo at once.Trigger 2 is the more dangerous of the two precisely because it is bulk: one re-add re-keys every worktree in the repo, so the duplicate is not a rare single-tab coincidence.
That reproduction is now a committed regression test, not a one-off probe:
src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.ts. It drives a real direct-SSH snapshot apply through the real store. Verbatim on unfixedorigin/main:What makes that red stronger than a bare failure: the two precondition assertions immediately above it —
— pass on both sides. Unfixed
mainreaches the identical duplicated state with the identical armed repair; the only thing that differs is whether the repair terminates. The red is the non-convergence itself, not a setup divergence. The test also asserts the precondition is produced rather than removed, so it cannot go vacuously green if hydration ever stops creating the duplicate.Honest limits on the reproduction. Three store actions are stubbed at the IPC boundary, and one of them —
reconnectPersistedTerminals— is load-bearing: with a live PTY the orphan sweep cleans the duplicate up and the bug evaporates, so the stub is what holds the window open rather than an artifact being papered over. The "repair cycle" counter is the harness's own loop, not React's scheduler. What is not stubbed is the store logic under test, which is why this counts as a production-path reproduction rather than a construction.This is a two-link chain, not one end-to-end run: link 1 (above) is non-convergence from production store code; link 2 is #185 from a self-retrigger in the production React bundle. Each is separately executed. A single run joining them has not been done, and is called out here rather than glossed.
A limitation this fix does not remove. The
ownersmap is unchanged under the fix — the duplicate is still there, the resolver simply stops being fooled by it. StaletabsByWorktreekeys still survive a worktree-id change, and first-match owner resolution can still mis-resolve them at other call sites (see "A second blast radius" below). Filed as a follow-up rather than widening this PR, deliberately: the loop is the crash, the stale key is the hygiene problem behind it, and fixing them in one diff would make neither reviewable.Round 6's mutation audit came back empty for the first time in six rounds — 14 mutants, all killed, all 13 tests demonstrably failable. The four tests no mutant initially killed got purpose-built ones (
ownerCount>1→>0; fallback toactiveWorktreeId; verdict pinnedtrue;activeTabIdnever written) and all four went red. Given this branch has now shipped two tests that could not fail, that audit mattered more than a clean result usually does.A further candidate origin — plausible, not executed
Separate from the two executed triggers above, there is a second route to a duplicated tab id that is SSH-specific, which would explain why
createTab's collision minting never sees it:Scoped hydration remaps remote worktree ids by path, then
replaceHydratedRecordKeysretains local entries for every key outsidereplaceWorkspaceKeys. ButmergeDirectSshRemoteWorkspaceSessionde-dupes tab ids only within the replaced keys —currentTabsByIdis built fromreplaceWorktreeIdsalone. Nothing de-dupes a tab id present both under a replaced key and a non-replaced one. Reinforcing it:terminals.ts:991setsactiveTabIdfrom the hydrated session, which can name a tab absent fromtabsByWorktree[activeWorktreeId]— exactly the repair trigger.Labelled PLAUSIBLE, not executed — read from the call chain plus the verified absence of a cross-key de-dupe. It is the first hypothesis to test when the new breadcrumb fires, and it suggests checking whether cluster-A bundles correlate with direct-SSH sessions.
A second blast radius — found in round 3, reproduced and fixed in round 7
Round 3 surfaced something neither earlier round could see, because each only reviewed its own increment: a sibling resolver already existed.
getTerminalTabOwnerWorktreeId(terminals.ts:314) is a memoized last-wins resolver; the newresolveActiveTabOwnerWorktreeIdis first-wins-with-active-preference. Under the same duplicate precondition they disagree, and the sibling is used atterminals.ts:2141and:2176to decideownerWorktreeId === s.activeWorktreeId— i.e. whether to bumpsortEpoch. If the active worktree is not the last owner, an active-worktree pane's title-classification change re-sorts the sidebar when it should not.Round 3 recorded this as PLAUSIBLE-not-reproduced and deliberately left it out of the diff. Round 7 reproduced it and fixed it, which is the clearest argument in this PR for why the review loop kept going after it stopped finding crashes.
Executed, with
activeWorktreeId = 'wt-active'andtabsByWorktree = {'wt-active':[t1], 'wt-other':[t1]}— active scanned first, so last-writer-wins nameswt-other:That last line is the one that promotes this from tidiness to a real defect: a user on the active worktree watching an agent pane gets a sidebar re-sort on every classified OSC title frame — reinstating exactly the click-driven re-sort the comment on that line says PR #209 removed. Each bump is a store write that re-renders every
sortEpochsubscriber, inside theterminal.workbenchboundary.The fix adds
isTabInActiveWorktreeto the same new module — anObject.hasOwnguard plus one.some()over the active worktree's list — used as a second disjunct at both call sites, cheap equality first so the non-duplicated path is unchanged. These two callers deliberately do not route throughresolveActiveTabOwnerWorktreeId: that would put a full O(worktrees × tabs) scan on every title frame and emit the duplicate breadcrumb from a second caller, folding two distinct call sites into one verdict and muddying the signal this PR is collecting. That reasoning is in the code, not only here.Four mutations, each producing exactly its intended failure and each restored green.
Still on the last-writer-wins cache, deliberately:
updateTabTitle(terminals.ts:1957) andclearTabLaunchAgent(:2107) use the owner id to pick which worktree's tab array to mutate. Under a duplicated id they mutate the last-scanned copy and leave the active worktree's stale — a visible pane's title that never updates, alaunchAgentthat never clears. Not fixed here, because with a genuinely duplicated id both copies legitimately claim the tab and there is no defensible "correct" one to pick; guessing would be worse than leaving it. Neither feeds an active-worktree comparison or a render loop. These go into the follow-up together with the stale-key cleanup, since all three are consumers of one root defect rather than three bugs.Round 8 — clean. Loop terminated.
Round 8 attacked round 7's fix on the one axis that could have made it harmful: an added disjunct into a suppression gate can only ever remove a
sortEpochbump, so the question was whether it removes one it shouldn't.Answered by exhaustive enumeration rather than argument — 3 worktrees × {absent, present-without-tab, present-with-tab} = 27 maps, crossed with 5 active-worktree values = 135 states, each evaluated before and after the disjunct:
All 8 suppressions are exactly "tab id duplicated across >1 worktree AND the active worktree is one of the owners". Because that proof ran against a model of the owner resolver, the same space was then re-run through the real store with real
setRuntimePaneTitlecalls:49 bumped, 55 no-bump, 0 model mismatchesacross 104 cases. The proof holds against the shipped path, not a reconstruction of it.Two further mutations probed what round 7's four had not reached:
activeWorktreeId === nullguard fromisTabInActiveWorktree: 37 tests passed, nothing went red. A real hole.Object.hasOwn(map, null)coerces to the string key'null', so a worktree keyed'null'would answer for "no active worktree". Contrived to trigger — but the guard was load-bearing by intent and pinned by nothing, which is how guards get deleted as dead code later. Closed by one test (bf184ac400); re-running the mutation against it reds exactly that test and nothing else.ownerWorktreeId === s.activeWorktreeId ||short-circuit at both call sites: 2193 passed, all green. Confirms it is pure performance with no hidden behavioural dependency — claimed in round 7, demonstrated in round 8.A follow-up pass on key handling found that three of eleven property-descriptor shapes disagree across the four key-presence oracles in play (
Object.entriesin the sibling cache,Object.keysin the owner resolver,Object.hasOwnin the new guard, and the plain index at the render site). None produces a new under-bump: for a non-enumerable own key the new guard agrees with what the render path shows the user while both siblings do not; an inherited key is an over-bump identical to pre-fix behaviour; and the one shape that could under-bump is unreachable because the owner resolver throws first. Reachability was closed by execution — every production writer oftabsByWorktreerun against a__proto__key with no pollution on any, and nodefineProperty/setPrototypeOfanywhere on renderer state records.Residual, stated rather than buried: within a duplicate, a genuinely-background pane sharing the id is also suppressed.
setRuntimePaneTitle(tabId, paneId, title)takes no worktree argument, so the API cannot distinguish which pane emitted the title — the same "no defensible correct copy" situation as theupdateTabTitle/clearTabLaunchAgentcase above, and it resolves when the duplication itself is fixed, not here.Postscript — six more of these landed while the PR was open
Between 09:31 and 14:39 UTC on 2026-08-01, after the triage scan that produced this PR had already closed, six further reports arrived on app version 1.4.163 carrying
boundary_id: terminal.workbenchand the identical six-frame stack this PR reproduces:1051d66f-0283-44aa-b195-03557a1d8ac21828176e-6344-40f3-b665-fc670a0cf032ff40fed8-660f-42f1-8247-ff650f369ccf94b7fa09-f3c1-4664-bb29-e60bf87f67ffcedc3d1b-50cf-409f-8261-12f5787acb411bdb9c23-c0a8-44d3-8de7-07b977293f9dTwo things worth drawing out. This is live on the current release, not a historical signature — 1.4.163 is the version these landed on. And five of the six are the same user inside five hours, which is the shape you would expect from a loop that re-arms on a particular workspace state rather than from a rare race: the machine that hits it once hits it again. The last of them landed 17 minutes after the fifth, while this paragraph was being written.
This is corroboration of frequency and currency only. It adds no new diagnostic information — the stacks are frame-for-frame what the reproduction already produces, all six entering through
TerminalPaneOverlayLayer$1— and it does not independently confirm the causal chain, whose limits are stated plainly above and are unchanged by these six.Made with Orca 🐋