Repository navigation
perf(editor,source-control): batch closed-tab model sweeps, drop 40 store subscriptions - #18144
Conversation
…tore subscriptions Closing N diff tabs scanned the global Monaco model registry 2N times and rendered both URI forms for every retained model on each scan. The Source Control panel opened 42 store subscriptions from one hook, 40 of which watched action identities that are fixed at store construction and can never change.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (8)
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe change batches closed-editor tab cleanup across Monaco models and editor caches. It adds multi-owner cache sweeping, multi-prefix model disposal, and a centralized closed-tab disposal API. The cleanup hook now processes all closed tabs in one call. Tests cover disposal parity, cache behavior, registry scans, and no-op cases. The source-control actions hook now subscribes only to generation-record maps and memoizes store action references. New tests verify subscriptions, identity stability, live references, and updates. Merge Risk: ⚪ Minimal · up to The PR reduces editor cleanup work and source-control subscriptions while preserving model disposal and panel behavior; no actionable merge-blocking risk remains after normal checks and review. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed and explains the change, rationale, performance measurements, trade-offs, and verification results. The required Linked Issue is still empty, and the template sections for Visual Proof, Testing checkboxes, Review, Notes, and Checklist are not explicitly completed.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Batched Monaco model disposal —
useClosedEditorTabCleanupnow collects the full removal batch intodisposeClosedEditorTabs, running onegetModels()scan (disposeUnattachedMonacoModelsByPathPrefixes) and one pass per cache instead of one scan/prefix per closed diff tab. Prefix matching was rewritten as a colon-boundary probe against aSet(isOwnedByPathPrefix), provably equivalent to the olduri === prefix || uri.startsWith(prefix + ':')predicate with decoded/encoded short-circuiting preserved. - Cache sweep helpers —
closed-editor-tab-cache-sweep.tsgainsdeletePaneScopedCacheEntries(a::-boundary probe replacing per-ownerstartsWith), andsweepClosedPdfViewPositionsnow takes an array. Per-mode disposal parity (edit / markdown-preview / diff / no-op cases) is preserved. - Source Control store subscriptions —
useSourceControlStoreActionsdrops 40 subscriptions by reading the stable action references throughuseAppStore.getState()inside auseMemokeyed on the two record maps, leaving onlypullRequestGenerationRecordsandcommitMessageGenerationRecordssubscribed.
Verification
I traced the prefix predicate and ::-probe equivalence (including colon-adjacent sibling ids and the bounds optimization), confirmed the decoded/encoded toString forms are still checked identically, and confirmed no remaining production callers rely on the old single-path signatures. The parity and subscriber-count tests are meaningful (exact counters, > 0 disposed-set guard, listenerCount() - baseline delta) and would fail on a regression.
The one load-bearing invariant — that store actions are never reassigned inside a set() payload — is documented, statically checked by the author, and covered by the never reassigns a store action test. If a future slice ever makes one of these actions stateful, the memo would silently serve stale references, but that risk is deliberately accepted and guarded; no change needed now.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
… dead export (#18240) Readiness-review follow-ups to #18144. The parity test in closed-editor-tab-disposal.test.ts cannot see prefix bleed: buildScenario closes tab-0..tab-99, so tab-10 is in the closed batch too and the per-tab oracle disposes its models via tab-10's own prefix. Batched and oracle agree and the assertion passes even with a bleeding predicate. Verified by mutation: replacing the boundary probe with a naive startsWith leaves all five of that file's tests green. Adds a test through the batched disposeClosedEditorTabs entry point with a still-OPEN tab-10 alongside a closed tab-1, which does fail under that mutation. Also records the `boundary + 1` advance in hasPaneScopeOwner as load-bearing for `:::` runs, with a test that fails under a `+ 2` "tidy-up", and removes disposeUnattachedMonacoModelsByPathPrefix, which #18144 left with zero production callers and a comment claiming it was kept for callers that do not exist. Finally, documents why title-derived rows carry `startedAt: 0`, which is the sole reason their `now` stamps cannot move a dashboard bucket.
…tore subscriptions (stablyai#18144) Closing N diff tabs scanned the global Monaco model registry 2N times and rendered both URI forms for every retained model on each scan. The Source Control panel opened 42 store subscriptions from one hook, 40 of which watched action identities that are fixed at store construction and can never change.
… dead export (stablyai#18240) Readiness-review follow-ups to stablyai#18144. The parity test in closed-editor-tab-disposal.test.ts cannot see prefix bleed: buildScenario closes tab-0..tab-99, so tab-10 is in the closed batch too and the per-tab oracle disposes its models via tab-10's own prefix. Batched and oracle agree and the assertion passes even with a bleeding predicate. Verified by mutation: replacing the boundary probe with a naive startsWith leaves all five of that file's tests green. Adds a test through the batched disposeClosedEditorTabs entry point with a still-OPEN tab-10 alongside a closed tab-1, which does fail under that mutation. Also records the `boundary + 1` advance in hasPaneScopeOwner as load-bearing for `:::` runs, with a test that fails under a `+ 2` "tidy-up", and removes disposeUnattachedMonacoModelsByPathPrefix, which stablyai#18144 left with zero production callers and a comment claiming it was kept for callers that do not exist. Finally, documents why title-derived rows carry `startedAt: 0`, which is the sole reason their `now` stamps cannot move a dashboard bucket.

ELI5
Two separate bits of bookkeeping were doing far more work than they needed to.
Closing tabs. Orca keeps a single global list of every document Monaco is holding on to. When you closed a diff tab, Orca walked that entire list looking for the two documents belonging to that one tab — and it built a fresh text copy of every document's identifier while it looked. Close a batch of tabs (a "close all", a worktree switch) and it re-walked the whole list once per closed tab. 100 tabs closed against 764 held documents meant 200 full walks and ~306,000 throwaway strings, all inside one synchronous React effect. Now it collects everything being closed and walks the list once.
The Source Control panel. One hook asked the app store to notify it 42 separate times about every single change anywhere in the app. 40 of those 42 were watching functions that are created once when the store is built and can never change, so those notifications could never do anything. Now the panel asks the store to notify it about the 2 things that actually vary, and reads the 40 fixed functions directly.
Same behaviour, same documents disposed, same panel.
Corrections to the reported issue
Two details in the report were wrong; verified against the code:
useAppStorecalls, not ~50 — 40 actions + 2 record maps. So it was ~40 removable subscribers, not 48.scrollTopCache/editorSelectionCachesweep was not a real hotspot. Every write into those maps goes throughsetWithLRU(src/renderer/src/lib/scroll-cache.ts), which caps them atCACHE_MAX_ENTRIES = 20. The per-tab walk was therefore over at most 20 keys, and batching it changesN x 20comparisons intoN x 20comparisons — identical work. I did the single-pass change anyway (it now probes::boundaries against aSet, so it really is O(cache) rather than O(tabs x cache)), but the measurable win there is zero and the honest justification is simplicity, not speed. The Monaco registry is the only unbounded collection in this path, and that is where all of the measured win comes from.The rest of the report checks out:
disposeUnattachedMonacoModelsByPathPrefixdid scan the whole registry and call bothuri.toString(true)anduri.toString()per model, twice per closed diff tab (original + modified prefix), with the cleanup effect processing every removal in one synchronous pass.Fix 1 — one registry scan per removal batch
useClosedEditorTabCleanupnow collects the whole removal batch and hands it to a newdisposeClosedEditorTabs()(closed-editor-tab-disposal.ts), which:disposeUnattachedMonacoModelsByPathPrefixes(monaco, allOwnedPrefixes)— onegetModels()scan;:boundaries against aSet, which is provably the same predicate asuri === prefix || uri.startsWith(prefix + ':')but costs O(segments) instead of O(prefixes) per model.The
isAttachedToEditor()guard, the exact-path edit-model dispose, and every cache key touched are unchanged.disposeUnattachedMonacoModelsByPathPrefixis kept as a one-element wrapper for its other callers.Taking the monaco namespace as an argument also means the logic is now unit-testable without importing
monaco-editor, which is why the sweep helper was split out in the first place.Fix 2 — 42 store subscriptions become 2
useSourceControlStoreActionsnow subscribes only topullRequestGenerationRecordsandcommitMessageGenerationRecords(the two entries that are state and carry re-render semantics), and reads the other 40 throughuseAppStore.getState()inside auseMemokeyed on those two maps.I verified the "actions are stable" premise rather than assuming it, two ways:
src/renderer/src/store— once in a slice contract type, once as a property of the object a slice creator returns. None appears inside aset()payload.pullRequestGenerationRecordsandcommitMessageGenerationRecordsare the only two that do, which is exactly why they stay subscribed.All 40 are genuine actions; none turned out to be a derived value.
Reference stability is preserved and is now stronger than the doc comment promised. Each action keeps the single identity it was created with (asserted against
getState()in a test). The returned object was previously a fresh literal on every render — the pre-fix hook fails the new stability test — and is now stable until one of the two subscribed maps changes.Measurements
Measured in this repo on this machine, at the reported real scale (382 open diff tabs → 764 retained models), closing 100 diff tabs. Pre-fix numbers come from running the original per-prefix loop against the identical fixture.
Fix 1 — closing 100 diff tabs, 764 retained models
getModels()registry scansuri.toString()callsThat 44 ms was one synchronous block inside a
useEffect— i.e. a dropped-frames hitch on "close all" / worktree switch. The 1,328 figure is764 + 564: the 200 matching models short-circuit after the decoded form, the rest render both.The regression test asserts the pre-fix shape costs
2Nscans and2N x M x 2toString calls, the new one costs exactly 1 scan and at most2Mcalls, and — separately — that both dispose the same set of model paths, with attached models and still-open tabs untouched in both.Fix 2 — Source Control store subscriptions
The 42 → 2 subscriber count is exact and comes from the existing
readStoreListenerCount()census; the pre-fix hook fails that assertion withexpected 42 to be 2.Caveat on the third row, stated plainly: it is a happy-dom + development-React microbenchmark and the absolute milliseconds are not production figures. The ratio (~2.5x, reproduced across runs) is the useful part, and the cost it removes is React's
useSyncExternalStorebookkeeping per subscription, not zustand'sSetiteration — I also measured 42 vs 2 vanillauseAppStore.subscribelisteners over 2,000 writes and the difference was below the noise floor of the store's own write path, so I am not claiming a zustand-notify win. I could not verify the reported app-wide totals (~1,200 subscribers / ~24,700 selector evaluations per second) from a test process; those come from the live instance.Negative user-facing trade-offs
None.
tab-1vstab-10), still-open tabs and plain file models. TheisAttachedToEditor()guard is untouched, so nothing can be disposed out from under a live editor. Deletes are order-independent and idempotent, so hoisting the sweeps out of the per-tab loop cannot change the outcome.Known gap, deliberately not addressed
There is still no eviction over retained Monaco models. At 382 open tabs the ceiling is one model per activated edit tab plus two per diff tab, released only on tab close (
MonacoEditor.tsxpasseskeepCurrentModel). Adding an LRU here would silently discard undo history and view state for evicted tabs — a product decision, not a perf patch. Left as a bounded-cache gap.Verification
pnpm tc— cleannpx oxlint <changed files>— cleannpx vitest run --config config/vitest.config.ts src/renderer/src/components/editor src/renderer/src/components/right-sidebar— 3,240 passed, 1 failedThe single failure is
right-sidebar/ai-vault-session-worktree-map.test.tsx > builds the map at scale without re-normalizing paths per session, a wall-clock-bounded perf assertion (expect(elapsedMs).toBeLessThan(150)). It fails identically on the base commitaa3ae6f56ecwith this branch checked out nowhere near it, and this change touches nothing it imports — it is a pre-existing flake on a loaded machine.