Skip to content

fix(editor): stop Close All / Close Others freezing the renderer on large tab sets - #12404

Merged
OrcaWin merged 4 commits into
mainfrom
fix/editor-close-all-quadratic
Aug 4, 2026
Merged

OrcaWin merged 4 commits into
mainfrom
fix/editor-close-all-quadratic

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

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 rebuilt groupTabEntityIds and tabBarGroupEntityIds by map-ing over group.tabOrder / tabBarOrder and doing a full unifiedTabs.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, real openFile, real unified tabs/groups), not synthetic objects:

tabs before after
125 30 ms 7 ms
250 156 ms 14 ms
500 1.20 s 44 ms
1000 13.0 s 142 ms

At 1000 tabs the renderer was frozen for 13 seconds.

Fix

Hoist the per-tab rescans into a single precomputed index.

  • New createRecentlyClosedTabPositionIndex(state, worktreeId) builds tab-bar order, unified-tab (by id and by entityId), and per-group order/membership lookups in one linear pass, then answers each position query in O(1).
  • closeAllFiles builds that index once before the loop and calls positionIndex.positionFor(f.id).
  • getRecentlyClosedTabPosition now 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/find scans it replaces; the groupOrderMatchesTabBar guard, the early undefined return, 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 original group.tabOrder.indexOf(...).

Position derivation moved into its own module (recently-closed-tab-position.ts) so recently-closed-tabs.ts stays under the oxlint max-lines limit without a suppression or ratchet bump; existing importers are unaffected via re-export.

Verification

  • New test in 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 of entityId increments a counter — and asserts that 4x the tabs costs at most 8x the scans.
    • Reverted the source change and watched it fail (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).
    • The same test also asserts the recorded snapshot position is still { tabBarIndex: 0, groupId, groupIndex: 0 } — that assertion passes both before and after, pinning behavior preservation.
  • npx vitest run --config config/vitest.config.ts on editor.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 oxlint on the changed files and node 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 closeUnifiedTab loop rebuilds tab arrays once per tab, and notifyHostOfMirroredEditorClose re-finds the file in openFiles. 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.

OrcaWin added 2 commits August 3, 2026 22:31
`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.
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 58c1cc92-4c0a-4546-80f0-b14c8f8c84c4

📥 Commits

Reviewing files that changed from the base of the PR and between cdddec8 and 2b0892a.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-latched-pane-retention.test.ts
  • src/renderer/src/store/slices/editor.test.ts
  • src/renderer/src/store/slices/editor.ts

📝 Walkthrough

Walkthrough

The change adds indexed recently closed tab position utilities for tab-bar and grouped-tab ordering. closeAllFiles builds one position index and reuses it for all closed files. Tests cover bounded entityId reads and position preservation. A terminal test import is reformatted without runtime changes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the defect, fix, performance results, behavior preservation, tests, and out-of-scope work, but it omits several required template sections. Add the required Summary, Screenshots, Testing checklist, AI Review Report with cross-platform confirmation, Security Audit, and Notes sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the renderer-freeze fix for Close All and Close Others with large tab sets.
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.

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

OrcaWin commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Resolved the #12399 / #12404 merge conflict by merging origin/fix/editor-reopen-phantom-tab into this branch.

What conflicted: both PRs append a new test to the tail of the same describe block (createEditorSlice recently closed editor tabs) in src/renderer/src/store/slices/editor.test.ts. Because the two new it bodies were adjacent and shared a closing brace, git saw one conflicting hunk rather than two independent additions. editor.ts auto-merged cleanly — the two source changes are far apart (openFile id resolution vs. closeAllFiles position capture).

Resolution is purely additive: both tests kept as sibling it blocks. No assertion, helper, or source line altered. Both PRs' test helpers (ownedEditorFileId, withCountedEntityIdReads) merged without conflict.

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:

reverted hunk failing test
const id = existing ? existing.id : ... (#12399) reactivates the live tab when a stale reopen id targets an already-open file
positionIndex.positionFor(f.id) → per-tab getRecentlyClosedTabPosition (#12404) captures close-all snapshot positions without rescanning tab state per closed tab (25920 reads vs. the 13440 ceiling)

Restored, then:

  • npx vitest run --config config/vitest.config.ts src/renderer/src/store/slices/editor.test.ts → 193/193 passed
  • plus recently-closed-tabs.test.ts and tabs.test.ts → 296/296 passed
  • npx tsc --noEmit -p config/tsconfig.node.json clean; config/tsconfig.web.json clean apart from pre-existing TS6307 project-membership noise
  • npx oxfmt --check and npx oxlint clean on the touched files

GitHub now reports this PR as MERGEABLE. #12404 lands cleanly after #12399.

# Conflicts:
#	src/renderer/src/store/slices/editor.test.ts
@OrcaWin
OrcaWin merged commit e599d92 into main Aug 4, 2026
1 check passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant