Repository navigation
fix(editor): stop Close All / Close Others freezing the renderer on large tab sets - #12404
Conversation
`openFile` honored a recently-closed snapshot's `reopenId` whenever no open file currently held that id, without checking whether the same (path, mode, owner) was already open under a different id. Editor ids are not symmetrical across worktrees: the first worktree to open an absolute path gets the bare path as its id, and any other owner of the same path gets a namespaced `editor:<wt>:<runtime>:<path>` id. So a snapshot captured under one shape could be restored while the live tab carried the other. When that happened `openFile` took the `existing` branch and mapped over `openFiles` looking for the stale id, matching nothing — no OpenFile was created or updated — yet it still set `activeFileId`, the per-worktree active id, the tab bar order and a unified tab entity to that stale id. The user got a tab rendering nothing and a dangling active editor. Resolve the id from the already-open file whenever one exists, so capture and restore agree on canonicalization. This is a no-op for the non-reopen path, where `resolveEditorFileIdForOwner` already returns `existing.id` via the identical predicate.
closeAllFiles resolved a reopen position for every closing tab by calling getRecentlyClosedTabPosition, which itself rescanned the worktree's tab-bar order and group membership with a nested find per entry. That made the whole bulk close O(N^3) in open editor tabs, and because it runs inside a synchronous zustand set() the renderer is blocked for the entire duration: measured against the real store, 500 tabs took 1.2s and 1000 tabs took 13.0s of frozen UI. Sessions that accumulate tabs — long SSH/relay work, a mirrored host republishing open files, a folder workspace opened wide — hit this on a single menu click. Hoist the per-tab rescans into one precomputed index. The new createRecentlyClosedTabPositionIndex builds tab-bar, unified-tab, and group lookups in a single linear pass over the worktree's state, then answers each position query in O(1); getRecentlyClosedTabPosition now delegates to it so single-tab callers keep identical behavior. Positions, reopen order, and the tab-bar/group indices recorded by #12236 are unchanged — first-occurrence wins everywhere, matching the indexOf/find scans this replaces. Position derivation moves to its own module so recently-closed-tabs.ts stays under the max-lines limit without a suppression; existing importers are unaffected via re-export. Same measurement after the change: 500 tabs 44ms, 1000 tabs 142ms, and the instrumented scan count drops from 503,000,500 to 4,000 at N=1000.
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThe change adds indexed recently closed tab position utilities for tab-bar and grouped-tab ordering. 🚥 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 |
…l-quadratic #12399 and #12404 both append a test to the tail of the same describe block in editor.test.ts ('createEditorSlice recently closed editor tabs'), so git saw one conflicting hunk spanning both new `it` bodies plus their shared closing brace. editor.ts auto-merged cleanly — the two source changes touch `openFile`'s id resolution and `closeAllFiles`'s position capture, far apart. Resolution is purely additive: keep both tests as sibling `it` blocks. No assertion, helper, or source line was altered. Both PRs' helpers (`ownedEditorFileId`, `withCountedEntityIdReads`) merged without conflict. Verified each fix is still live and independently guarded by reverting one source hunk at a time: - revert `const id = existing ? existing.id : ...` -> only 'reactivates the live tab when a stale reopen id targets an already-open file' fails - revert `positionIndex.positionFor(f.id)` back to the per-tab `getRecentlyClosedTabPosition` scan -> only 'captures close-all snapshot positions without rescanning tab state per closed tab' fails (25920 reads vs the 13440 ceiling) Restored: editor.test.ts 193/193 green.
|
Resolved the #12399 / #12404 merge conflict by merging What conflicted: both PRs append a new test to the tail of the same describe block ( Resolution is purely additive: both tests kept as sibling Verified both fixes are still live and independently guarded by reverting one source hunk at a time and confirming only the matching test goes red:
Restored, then:
GitHub now reports this PR as |
# Conflicts: # src/renderer/src/store/slices/editor.test.ts
…arge tab sets (stablyai#12404) * fix(editor): stop Cmd/Ctrl+Shift+T reopening a phantom editor tab `openFile` honored a recently-closed snapshot's `reopenId` whenever no open file currently held that id, without checking whether the same (path, mode, owner) was already open under a different id. Editor ids are not symmetrical across worktrees: the first worktree to open an absolute path gets the bare path as its id, and any other owner of the same path gets a namespaced `editor:<wt>:<runtime>:<path>` id. So a snapshot captured under one shape could be restored while the live tab carried the other. When that happened `openFile` took the `existing` branch and mapped over `openFiles` looking for the stale id, matching nothing — no OpenFile was created or updated — yet it still set `activeFileId`, the per-worktree active id, the tab bar order and a unified tab entity to that stale id. The user got a tab rendering nothing and a dangling active editor. Resolve the id from the already-open file whenever one exists, so capture and restore agree on canonicalization. This is a no-op for the non-reopen path, where `resolveEditorFileIdForOwner` already returns `existing.id` via the identical predicate. * fix(editor): make Close All linear instead of cubic in tab count closeAllFiles resolved a reopen position for every closing tab by calling getRecentlyClosedTabPosition, which itself rescanned the worktree's tab-bar order and group membership with a nested find per entry. That made the whole bulk close O(N^3) in open editor tabs, and because it runs inside a synchronous zustand set() the renderer is blocked for the entire duration: measured against the real store, 500 tabs took 1.2s and 1000 tabs took 13.0s of frozen UI. Sessions that accumulate tabs — long SSH/relay work, a mirrored host republishing open files, a folder workspace opened wide — hit this on a single menu click. Hoist the per-tab rescans into one precomputed index. The new createRecentlyClosedTabPositionIndex builds tab-bar, unified-tab, and group lookups in a single linear pass over the worktree's state, then answers each position query in O(1); getRecentlyClosedTabPosition now delegates to it so single-tab callers keep identical behavior. Positions, reopen order, and the tab-bar/group indices recorded by stablyai#12236 are unchanged — first-occurrence wins everywhere, matching the indexOf/find scans this replaces. Position derivation moves to its own module so recently-closed-tabs.ts stays under the max-lines limit without a suppression; existing importers are unaffected via re-export. Same measurement after the change: 500 tabs 44ms, 1000 tabs 142ms, and the instrumented scan count drops from 503,000,500 to 4,000 at N=1000. --------- Co-authored-by: OrcaWin <[email protected]>
Defect
closeAllFiles(the store action behind editor Close All / bulk close) is roughly O(N^3) in the number of open editor tabs.Per closing tab it called
getRecentlyClosedTabPosition(s, worktreeId, f.id)to record the reopen position. That function was itself quadratic: it rebuiltgroupTabEntityIdsandtabBarGroupEntityIdsbymap-ing overgroup.tabOrder/tabBarOrderand doing a fullunifiedTabs.find(...)inside each iteration. One O(N^2) derivation, re-run once per closed tab.It runs inside a synchronous zustand
set(), so the renderer is blocked for the whole duration — the user sees the app hang, with no spinner and no way to cancel.Failure scenario
Open a workspace with a few hundred editor tabs — easy after a long session, a mirrored host republishing its open files over SSH/relay, or opening a wide folder workspace — then hit Close All. Measured against the real store (
createEditorTabsStore, realopenFile, real unified tabs/groups), not synthetic objects:At 1000 tabs the renderer was frozen for 13 seconds.
Fix
Hoist the per-tab rescans into a single precomputed index.
createRecentlyClosedTabPositionIndex(state, worktreeId)builds tab-bar order, unified-tab (byidand byentityId), and per-group order/membership lookups in one linear pass, then answers each position query in O(1).closeAllFilesbuilds that index once before the loop and callspositionIndex.positionFor(f.id).getRecentlyClosedTabPositionnow delegates to the index, so every single-tab caller (close file, preview replace, terminal close, browser close) keeps identical behavior.Behavior is preserved exactly: first-occurrence wins everywhere, matching the
indexOf/findscans it replaces; thegroupOrderMatchesTabBarguard, the earlyundefinedreturn, and the emitted{ tabBarIndex, groupId, groupIndex }shape are unchanged. Reopen order and the recorded tab positions from #12236 are untouched. Group index is scoped per group rather than globally, matching the originalgroup.tabOrder.indexOf(...).Position derivation moved into its own module (
recently-closed-tab-position.ts) sorecently-closed-tabs.tsstays under the oxlintmax-lineslimit without a suppression or ratchet bump; existing importers are unaffected via re-export.Verification
editor.test.ts:captures close-all snapshot positions without rescanning tab state per closed tab. It counts work rather than wall-clock time — unified tabs are wrapped so every read ofentityIdincrements a counter — and asserts that 4x the tabs costs at most 8x the scans.expected 275240 to be less than or equal to 41680), then restored it and watched it pass. The instrumented scan count for N=1000 goes from 503,000,500 to 4,000 (exactly 4N).{ tabBarIndex: 0, groupId, groupIndex: 0 }— that assertion passes both before and after, pinning behavior preservation.npx vitest run --config config/vitest.config.tsoneditor.test.ts,recently-closed-tabs.test.ts,tabs.test.ts,browser.test.ts,worktrees.test.ts,useIpcEvents.test.ts,terminal-pane-detach-agent-retention.test.ts,agent-status-drop-ipc.test.ts,worktree-removal-maps-leak.test.ts,useRetainedAgents.test.ts— 719 passing.npx tsc --noEmit -p config/tsconfig.tc.web.json— clean.npx oxlinton the changed files andnode config/scripts/check-max-lines-ratchet.mjs— clean, no new suppressions.Not in scope
A residual O(N^2) remains outside this path: the trailing
closeUnifiedTabloop rebuilds tab arrays once per tab, andnotifyHostOfMirroredEditorClosere-finds the file inopenFiles. Together they account for the remaining 142 ms at 1000 tabs. Fixing that means a bulk-close entry point in the tabs slice with its own activation/MRU semantics — a separate change.