Skip to content

fix(terminal): stop the active-terminal repair loop from tripping React #185 - #11950

Merged
AmethystLiang merged 15 commits into
mainfrom
fix/crash-a-active-terminal-repair-loop
Aug 1, 2026
Merged

AmethystLiang merged 15 commits into
mainfrom
fix/crash-a-active-terminal-repair-loop

Conversation

@nwparker

@nwparker nwparker commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

Cluster A_terminal_workbench_185 — 13 crash reports from #orca-crashes between 2026-07-30 and 2026-08-01, all react-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 boundary terminal.workbench; one (e9bf9327, Linux) reports boundary modal.feature-tips but has TerminalPane as 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-dom bundle with no act(). 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 move on the host, and randomUUID() at repos.ts:336/:434 when a repo is re-added) — the reproduction seeds the catalog at the new path with a direct setState rather 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 production react-dom bundle, 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, by Object.entries order:

for (const [wId, tabs] of Object.entries(s.tabsByWorktree)) {
  if (tabs.some((t) => t.id === tabId)) { tabOwnerWorktreeId = wId; break }
}

It then pins the global activeTabId only when the resolved owner is the active worktree:

activeTabId: isActiveWorktreeTab ? tabId : s.activeTabId

If the same tab id is present under two worktrees and the other one is scanned first, isActiveWorktreeTab is false, so activeTabId is never written — while activeTabIdByWorktree is reallocated on every call.

Terminal.tsx's active-terminal repair effect depends on activeTabIdByWorktree. resolveRepairedActiveTerminalTabId keeps returning a repair target because activeTabId never lands in the active worktree's tab list (active-terminal-repair.ts:14). So: effect fires → setActiveTab → new activeTabIdByWorktree identity → 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. activeTabId then 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_worktrees crash breadcrumb, once per tab id, carrying ownerCount and resolvedToActiveWorktree. 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.tsx drives the real Terminal.tsx repair 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:

 × settles when another worktree reuses the tab id and is scanned first
AssertionError: expected 'stale-tab' to be 't1' // Object.is equality
      Tests  1 failed | 2 passed (3)

activeTabId is 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:

$ npx vitest run -c config/vitest.config.ts \
    src/renderer/src/components/terminal/active-terminal-repair-loop.react185.test.tsx \
    src/renderer/src/store/ src/renderer/src/components/terminal-pane/

 Test Files  363 passed (363)
      Tests  5097 passed (5097)

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

$ npx oxlint <every changed/added file>                        exit 0
$ npx tsc --noEmit -p config/tsconfig.tc.web.json              exit 0

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 against react-dom-client.development.js:9167, that chain is a useState/useReducer dispatch. A zustand write in this app cannot produce it: zustand 5.0.14 on React 19.2.7 goes through useSyncExternalStore → forceStoreRerender → enqueueConcurrentRenderForLane, which are different frames. So the throwing update is an app useEffect calling a useState setter — 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 recursivelyTraversePassiveMountEffects on children before commitHookEffectListMount on self, so a descendant always dispatches first in the same flush, and dispatchSetStateInternal only takes the eager-bailout branch when fiber.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-parking setColdParkedTerminalTabIds passive effect in use-terminal-tab-cold-parking.ts, documented in terminal-park-verdict-flip-telemetry.ts as "crash cluster C5". Component-stack tops fit that too — TerminalPaneOverlayLayer ×8, SortableTab ×3, TerminalPane ×2 — Terminal is never the top frame in any of the 13. All 11 attached diagnostic bundles were checked for the terminal_park_verdict_churn breadcrumb: 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, no act() anywhere. The production bundle was resolved by setting NODE_ENV=production in a side-effect module imported before react-dom/client, and the run asserts it got there — String(createRoot).includes('formatProdErrorMessage'). No patched React, no modified node_modules.

Step 1 — the loop throws #185 in the production build:

E2E driver-only  {"bundleIsProduction":true,
                  "owners":["repoA::/srv/proj/wt","repoA::/srv/proj/wt-renamed"],
                  "renders":54,"activeTabId":null,
                  "captured":[{"source":"window","message":"Minified React error #185; ..."}]}

renders: 54 independently 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 mirroring activeTabIdByWorktree into local useState in a passive effect, i.e. the shape of use-terminal-tab-cold-parking's setColdParkedTerminalTabIds:

E2E with-descendant  {..."renders":54,"activeTabId":null,"captured":[{"source":"window",
  "message":"Minified React error #185; ...",
  "frames":["getRootForUpdatedFiber","enqueueConcurrentHookUpdate","dispatchSetStateInternal",
            "dispatchSetState","commitHookEffectListMount","commitPassiveMountOnFiber",
            "recursivelyTraversePassiveMountEffects","commitPassiveMountOnFiber"]}]}

Against the 13 production reports:

getRootForUpdatedFiber ← enqueueConcurrentHookUpdate ← dispatchSetStateInternal
  ← dispatchSetState ← commitHookEffectListMount ← commitPassiveMountOnFiber

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 useState descendant produces it. It could at most be an alternative driver, and the 0/11 breadcrumb count argues against that separately.

Note also that owners is 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 activeTabId write → 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 run git worktree move over a real SSH connection. The two triggers that produce a changed worktree id (git worktree move, and randomUUID() at repos.ts:336/:434 on 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

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

  2. THE OLD BEHAVIOR HAD A SILENT SYMPTOM TOO, AND IT IS NOW FIXED. activeTabId is documented as "the visible tab" and is read by markTerminalTabUnread (bell/unread attribution), by Terminal.tsx:1173 for eager pane mounting, and by useModalReturnFocus.ts:127. A permanently-stale activeTabId means 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.

  3. 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. setActiveTab runs 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.

  4. 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-global Set in the same triage batch as 54 renderer OOM aborts is not defensible on a shrug. Capped at 256 keys (~22–85KB ceiling), mirroring the shipped MAX_COALESCE_KEYS = 128 precedent. 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.

  5. 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 activeTabId to active-worktree tabs, or markTerminalTabUnread swallows BELs on a background tab") is untouched. A test pins that a background-worktree tab activation still does not steal activeTabId.

  6. 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-dom in happy-dom, a subscriber mirroring Terminal.tsx:322: 20 sequential redundant setActiveTab calls went from 20 renders / 20 effect runs to 1 / 1. Each avoided effect run is Terminal.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 calls setActiveTab — tabs-hydration.ts reads activeTabIdByWorktree directly.

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:36 reallocates activeTabIdByWorktree unconditionally, 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 tabsByWorktree was 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.

HIGH-1 — terminals.ts:1908-1934. "The fix stops the loop by refusing to write, not by fixing the misattribution. When the precondition holds, isActiveWorktreeTab is still false, so activeTabId NEVER converges … The crash is traded for a permanently wrong global activeTabId: bells/unread swallowed or misattributed, mount-eagerness targeting the wrong tab. A real loud-to-silent trade."

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 only unifiedTabsByWorktree/groupsByWorktree/activeGroupIdByWorktree. The red–green above is the direct evidence.

HIGH-2 — causal chain unproven at both ends. Precondition has no demonstrated production origin; production stacks are provably not the zustand path; a competing documented hypothesis (cluster C5 cold-parking) is still open.

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.

LOW-3. The original commit subject claimed "make redundant tab activation idempotent", but activateTab still unconditionally reallocates unifiedTabsByWorktree and groupsByWorktree on every call, so setActiveTab is not idempotent. The loop broke only because the repair effect's dep array happens to omit those maps.

Correct. The second commit's subject describes what the diff actually does (converging activeTabId) rather than claiming idempotence. activateTab was 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; oxlint exit 0; tsc exit 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 ownerCount 0 / 1 / >1 — both the active-worktree preference and the breadcrumb are gated on ownerCount > 1, so neither can execute otherwise. It also audited all 30 renderer call sites of setActiveTab and found every one is human- or activation-rate: no per-frame or per-PTY-chunk caller exists (pty-connection.ts and parked-terminal-byte-watcher.ts call markTerminalTabUnread, never setActiveTab; closeOtherTerminalTabs calls it once before its loop, not inside). And it established that the bell invariant is strengthened: the resolver can only pin activeTabId to a tab genuinely in the active worktree, whereas the old code could strand it on a deleted tab.

MEDIUM — the new breadcrumb was not registered for coalescing. Its renderer-side guard is once-per-tab-id, not once-per-session. The hypothesized cause is a stale worktree map — but a stale whole tabsByWorktree entry duplicates every tab id in that worktree at once, so N distinct ids each take a full slot in the 30-entry ring. A 40-tab user hitting the bug would lose the entire ring in the very crash being diagnosed — the diagnostic destroying its own evidence.

This is the exact failure crash-reporting.ts:337-345 already documents for terminal_safe_fit_retry_exhausted, where Windows crash F0BKR84AHEH lost 26–90% of its ring to two bursts. Fixed by registering the name for coalescing.

LOW — two prototype-unsafe keyed reads. tabsByWorktree[activeWorktreeId]?.some(...) resolves inherited members, so an activeWorktreeId of toString/constructor/valueOf returns the inherited function — truthy, so ?. does not short-circuit — and .some is undefined. Fixed by tracking ownership inside the existing loop, which also removes two redundant re-scans.

Round 3 — NOT clean. Four defects, all mine, all fixed.

MEDIUM — the round-2 coalescing fix was entirely untested. Deleting the breadcrumb name from both sets and running the main gate gave 177 files / 2701 tests passed, zero failures. The whole commit could be reverted silently. Every other member of NAME_ONLY_COALESCED_BREADCRUMB_NAMES has a dedicated coalesceKey assertion in crash-reporting-renderer-breadcrumbs.test.ts; this one had none.

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.

MEDIUM — name-only coalescing masks the one field the breadcrumb exists for. Coalescing is last-writer-wins on the payload. resolvedToActiveWorktree: false is the only value that says the activation still could not converge activeTabId — and it is silently overwritten by any later benign true inside the 30s window. suppressedSinceLast records the count, not the mix.

Confirmed by probe, and the reviewer also disproved the competing concern I had raised: the payload is not destroyed by coalescing — pending + resolvePendingCoalescedBreadcrumb do fold the newest ownerCount/resolvedToActiveWorktree into the ring entry, and both booleans and finite numbers survive sanitizeRendererBreadcrumbData. Fixed by keying on the flag (name:flag, mirroring the existing TERMINAL_WEBGL_DIAGNOSTIC name:kind branch), which bounds the burst at two keys instead of one while keeping both samples.

LOW — the activeWorktreeId truthiness check was a hole, not a guard. If activeWorktreeId is '' and '' is a key owning the tab, ownership is detected but the truthiness test fails, so the function falls back to firstOwnerId — reintroducing precisely the non-convergence this commit exists to remove, via the guard meant to protect it. Fixed by tracking activeOwnerId: string | null instead of a boolean. Theoretical today (no non-test code assigns ''), but the fix removes the question rather than relying on that.

LOW — the resolver test file failed oxfmt --check at HEAD. The branch would have failed a CI format gate. Neither round 1 nor round 2 ran oxfmt. My miss: I ran it on the files touched by the second commit and never on the file added by the first.

Round 3 also cleared the idempotence test I had added: removing the guard fails exactly that test and only that test, and zustand's set merges 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 stubs unifiedTabsByWorktree: {}, so setActiveTab's trailing activateTab never fires; re-run with it populated, the duplicate-id case still settles in 2 passes, and activateTab writes nothing the repair effect depends on.

Round 3 gates: 376 files / 5208 renderer tests; 177 files / 2703 main tests; oxlint 0; oxfmt --check clean; tsc web 0; tsc node 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 — sanitizeRendererBreadcrumbData admits any string, so a renderer-controlled value could open the key space — measures identically to two keys already shipped (renderer_error with unique messages, and the WebGL kind key both give ring 30 / keys 128), is hard-capped at MAX_COALESCE_KEYS = 128 with LRU, and the only in-repo emitter passes a literal boolean. A renderer able to send a string here can already flood via renderer_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: 39 plus the newest ownerCount for 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. activateTab writes only unifiedTabsByWorktree, groupsByWorktree, activeGroupIdByWorktree and unreadTerminalTabs — it never touches activeTabId, activeTabIdByWorktree or tabsByWorktree, 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, but activeTabId stays stale in 8 of 10.

LOW — commits 46e7da1816 and a1e953fdcd contradict each other. a1e953fdcd exists entirely to stop a false verdict being erased by a later benign true. But the renderer guard from 46e7da1816 is keyed on the tab id alone, so for any one id only the first verdict is ever emitted. A duplicated id that first resolves benignly and then stops converging when the user switches worktrees drops the false sample at the source — it never reaches the coalescer the other commit was written to protect.

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 c1806d1a43 by 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 to tabId fails 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 false was 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 from tabsByWorktree[active], so a sustained loop shows up as true. 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.

MEDIUM. Round 5 overshot in the opposite direction. The repair effect can emit false: its closure holds the worktree from its render while the resolver reads s.activeWorktreeId live inside set(), so a worktree switch landing between commit and passive flush reattributes the tab. Reproduced, not argued — emitted {ownerCount: 2, resolvedToActiveWorktree: false} from the repair effect, failing expected [false] to deeply equal [true]. Not contrived: useIpcEvents, WorktreeJumpPalette and worktree-activation all call setActiveWorktree, and async IPC before the passive flush triggers it without needing sibling ordering.

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-777 exactly, and swept 6,400 store shapes (2 active worktrees × 5 tab-set shapes² × 4 activeTabIds × 4 remembered² × unified-model on/off):

RED  (both fixes reverted):  960 / 6400 diverge — the effect re-fires without
     reaching a fixed point.  In-harness it throws #185, stack:
     getRootForUpdatedFiber ← enqueueConcurrentRenderForLane ← forceStoreRerender
     ← zustand setState ← setActiveTab (terminals.ts:1907) ← the useEffect
GREEN (both applied):          0 / 6400, all settle in ≤6 passes

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 activeTabId stays 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 commitRootImpl is:

0 !== (pendingEffectsLanes & 3) && flushPendingEffects();
ensureRootIsScheduled(root);
remainingLanes = root.pendingLanes;
0 !== (lanes & 261930) && 0 !== (remainingLanes & 42)
  ? root === rootWithNestedUpdates ? nestedUpdateCount++ : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root))
  : (nestedUpdateCount = 0);

The pendingEffectsLanes & 3 gate that the earlier reasoning leaned on is real, but it governs the eager flushPendingEffects() — not the counter. The counter has its own condition one line down, and its mask is 42 = 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 the setActiveTab call 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.pendingLanes asks whether a new update is already pending at the moment this commit reaches that line. A self-retriggering effect always satisfies it — its setState lands during the same flush. A loop that yields to the macrotask queue between iterations does not: pendingLanes has drained to 0, the else branch 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, no act() anywhere, IS_REACT_ACT_ENVIRONMENT = false, real MouseEvent dispatch, driving the real store in the SSH-derived duplicate state:

entry renders after entry #185
real discrete click 53 thrown
IPC-entered (setTimeout), iterations back-to-back 53 thrown
IPC-paced (a macrotask between every iteration) 229 and still climbing not thrown

The thrown error is the getRootForUpdatedFiber one, arriving as an Error via onUncaughtError — not the DEV-only passive-counter console.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/catch never 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 / & 42 condition and the getRootForUpdatedFiber throw is not DEV-gated — that part was read from source, not executed. Separately, a reviewer on another cluster instrumented the real react-dom-client.production.js at 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:

RED   (unfixed origin/main):  {"converged": false, "passes": 200, "identityChurn": 200}
GREEN (this branch):          {"converged": true,  "passes": 1}

identityChurn: 200 is 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:

const worktreeId = `${repo.id}::${gitWorktree.path}`

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 tabsByWorktree keeps the old key alongside the new one:

  1. 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.
  2. Re-adding a repo — mints a fresh repo.id via randomUUID() (src/main/ipc/repos.ts:336, and :434 for the SSH/connectionId variant), 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 unfixed origin/main:

 × converges the active-terminal repair instead of re-running it forever
AssertionError: expected false to be true // Object.is equality
- Expected  + Received
- true      + false

What makes that red stronger than a bare failure: the two precondition assertions immediately above it —

expect(worktreeIdsOwningTab(store, 'tab-1')).toEqual([OLD_ID, NEW_ID])
expect(store.getState().activeTabId).toBeNull()

— pass on both sides. Unfixed main reaches 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 owners map is unchanged under the fix — the duplicate is still there, the resolver simply stops being fooled by it. Stale tabsByWorktree keys 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 to activeWorktreeId; verdict pinned true; activeTabId never 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 replaceHydratedRecordKeys retains local entries for every key outside replaceWorkspaceKeys. But mergeDirectSshRemoteWorkspaceSession de-dupes tab ids only within the replaced keys — currentTabsById is built from replaceWorktreeIds alone. Nothing de-dupes a tab id present both under a replaced key and a non-replaced one. Reinforcing it: terminals.ts:991 sets activeTabId from the hydrated session, which can name a tab absent from tabsByWorktree[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 new resolveActiveTabOwnerWorktreeId is first-wins-with-active-preference. Under the same duplicate precondition they disagree, and the sibling is used at terminals.ts:2141 and :2176 to decide ownerWorktreeId === s.activeWorktreeId — i.e. whether to bump sortEpoch. 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' and tabsByWorktree = {'wt-active':[t1], 'wt-other':[t1]} — active scanned first, so last-writer-wins names wt-other:

FAIL > setActiveTab and setRuntimePaneTitle disagree about who owns a duplicated tab id
       duplicated: setActiveTab->activeTabId=t1 (owner=wt-active)
                 ; setRuntimePaneTitle sortEpoch 0->1
PASS > control: without duplication the same title change does not bump sortEpoch
FAIL > storm: alternating classified titles bump sortEpoch once per frame when duplicated
       storm: sortEpoch after 20 title frames = 20

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 sortEpoch subscriber, inside the terminal.workbench boundary.

The fix adds isTabInActiveWorktree to the same new module — an Object.hasOwn guard 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 through resolveActiveTabOwnerWorktreeId: 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) and clearTabLaunchAgent (: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, a launchAgent that 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 sortEpoch bump, 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:

r8 exhaustive: 127 unchanged, 8 suppressed, 0 unjustified
r8 over-bumps: 0

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 setRuntimePaneTitle calls: 49 bumped, 55 no-bump, 0 model mismatches across 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:

  • Dropping the activeWorktreeId === null guard from isTabInActiveWorktree: 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.
  • Dropping the cheap 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.entries in the sibling cache, Object.keys in the owner resolver, Object.hasOwn in 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 of tabsByWorktree run against a __proto__ key with no pollution on any, and no defineProperty/setPrototypeOf anywhere 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 the updateTabTitle/clearTabLaunchAgent case 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.workbench and the identical six-frame stack this PR reproduces:

Report Time (UTC) Reporter OS
1051d66f-0283-44aa-b195-03557a1d8ac2 09:31:07 SeungGiJeong darwin 25.5.0
1828176e-6344-40f3-b665-fc670a0cf032 12:56:19 SeungGiJeong darwin 25.5.0
ff40fed8-660f-42f1-8247-ff650f369ccf 13:09:54 SeungGiJeong darwin 25.5.0
94b7fa09-f3c1-4664-bb29-e60bf87f67ff 13:36:28 Kooooojun darwin 27.0.0
cedc3d1b-50cf-409f-8261-12f5787acb41 14:22:44 SeungGiJeong darwin 25.5.0
1bdb9c23-c0a8-44d3-8de7-07b977293f9d 14:39:01 SeungGiJeong darwin 25.5.0

Two 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 🐋

nwparker and others added 7 commits August 1, 2026 04:26
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-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

Fixes the active-terminal repair loop that was causing React error #185 (Maximum update depth exceeded) across 13+ production crash reports. The root cause was setActiveTab using first-match ownership resolution: when the same tab id appeared under two worktrees (triggered by a worktree rename or repo re-add changing the derived id), the earlier-scanned worktree would win, isActiveWorktreeTab would be false, activeTabId would never converge, and the repair effect would re-fire indefinitely.

  • Core fix (active-tab-owner-worktree.ts, terminals.ts): setActiveTab now uses resolveActiveTabOwnerWorktreeId, which prefers the active worktree when a tab id has multiple owners, ensuring activeTabId actually converges. An idempotency guard prevents activeTabIdByWorktree from allocating a new object on redundant activations, so the repair effect cannot retrigger itself even in the fallback path.
  • Unified tab scoping (tabs.ts): activateTab gains an optional worktreeId parameter so setActiveTab can bind unified tab activation to the same owner the ownership resolver chose, preventing a duplicated entity id from activating the wrong worktree's group.
  • Diagnostics (crash-reporting.ts, active-tab-owner-worktree.ts): A terminal_tab_id_owned_by_multiple_worktrees breadcrumb is emitted at most twice per tab id (once per verdict), with per-verdict coalesce keys and a 256-entry session cap.

Confidence Score: 4/5

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

Important Files Changed

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
Loading

Reviews (5): Last reviewed commit: "refactor(terminal): extract repair logic..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

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

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed and relevant, but it omits explicit Screenshots, Security Audit, and Testing checklist sections required by the template. Add the required headings, state “No visual change,” report each testing gate, and summarize security risks reviewed with any follow-up.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the terminal repair-loop fix and its React #185 outcome.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 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.

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

🧹 Nitpick comments (1)
src/renderer/src/store/slices/active-tab-owner-worktree.ts (1)

65-77: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Share 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 example src/shared/types.ts).
  • src/main/ipc/crash-reporting.ts#L329-L336: replace the DUPLICATE_TAB_OWNER_BREADCRUMB local 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

📥 Commits

Reviewing files that changed from the base of the PR and between 16c5526 and ca86a4a.

📒 Files selected for processing (6)
  • src/main/ipc/crash-reporting-renderer-breadcrumbs.test.ts
  • src/main/ipc/crash-reporting.ts
  • src/renderer/src/components/terminal/active-terminal-repair-loop.react185.test.tsx
  • src/renderer/src/store/slices/active-tab-owner-worktree.test.ts
  • src/renderer/src/store/slices/active-tab-owner-worktree.ts
  • src/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.

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

🧹 Nitpick comments (1)
src/renderer/src/store/slices/active-tab-owner-worktree.ts (1)

85-96: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten 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

📥 Commits

Reviewing files that changed from the base of the PR and between ca86a4a and e2f9481.

📒 Files selected for processing (4)
  • src/renderer/src/store/slices/active-tab-owner-worktree.test.ts
  • src/renderer/src/store/slices/active-tab-owner-worktree.ts
  • src/renderer/src/store/slices/runtime-pane-title-sort-epoch.test.ts
  • src/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

nwparker and others added 2 commits August 1, 2026 07:05
…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.

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

🧹 Nitpick comments (1)
src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.ts (1)

11-54: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4ca0ed0 and bf184ac.

📒 Files selected for processing (2)
  • src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.ts
  • src/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.
@AmethystLiang
AmethystLiang merged commit 36cc849 into main Aug 1, 2026
43 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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]>
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