Repository navigation
perf(renderer): index four projections that rescanned their inputs per keystroke - #18747
Conversation
There was a problem hiding this comment.
ℹ️ No critical issues — one misplaced doc comment inline; the refactor itself looks sound.
Reviewed changes
- Board search index split —
buildWorkspaceBoardPaletteDocumentsextracted and memoized on[worktrees, repoMap]inuse-workspace-kanban-search.ts, so keystrokes rerunsearchWorktreeDocumentsover an already-built index instead of rebuilding every worktree's normalized fields. - Tab-group projection indexes —
openFileById,browserTabById, andgroupTabByIdmaps replace per-tab.findscans inuseTabGroupItemProjections.ts, alongside the pre-existingterminalTabById. - Source-control tree path accumulation —
source-control-tree.tsaccumulates the ancestor path down the walk instead ofsegments.slice(0, i + 1).join('/')per segment. - Sidebar header boundary indexes —
worktree-header-section-boundaries.tsreplaces per-headerfindIndex/indexOfwith first-winsMapindexes built once per call. - Benchmark — new
config/scripts/renderer-quadratic-scan-benchmark.mjswith abench:renderer-quadratic-scansscript, asserting baseline/indexed equality before timing.
I traced each change against its pre-change shape: the board path is byte-for-byte equivalent (searchWorktrees already decomposed into buildWorktreePaletteDocuments + searchWorktreeDocuments with the same evidencePolicy: 'board'), the accumulated ancestor path produces identical strings, the successor indexes preserve findIndex/indexOf first-wins semantics (including the last-element → undefined case), and the tab maps are keyed exactly as the .find calls were. Existing tests cover matchWorkspaceBoardWorktrees and buildSourceControlTree; the equivalence claims hold.
ℹ️ Nitpicks
- The PR description states "
Mapconstruction is first-wins" as a blanket claim. That is only true of the sidebar boundary indexes (!has()guards). The three tab maps (openFileById,browserTabById,groupTabById) usenew Map(list.map((item) => [item.id, item])), which is last-wins on duplicate keys. It is safe here becauseOpenFile.idis documented as unique ("use filePath as unique key") and the pre-existingterminalTabByIdalready used the same shape, but the description overstates the invariant.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between aa9b868fe3a141991b8162d0fe8daa8b19da897a and 63e3b1a. 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review. 📝 WalkthroughWalkthroughThe change optimizes renderer projections by replacing repeated linear scans with memoized palette documents and lookup maps. Source-control tree construction now accumulates ancestor paths incrementally. Sidebar boundary calculations precompute header and successor indexes. A benchmark script compares baseline and indexed implementations, validates equivalent results, and reports timing data. An npm script runs the benchmark. Merge Risk: 🔵 Low · up to Renderer lookup and traversal optimizations improve performance, but the benchmark output has an unlabeled speedup column that can make reported results harder to interpret. This is a bounded documentation/reporting issue and does not block runtime use. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed and covers the change, motivation, testing, benchmarks, trade-offs, and checklist. However, it marks the mandatory Linked Issue section as N/A, although the template requires an issue link. Full details: Docstring CoverageExplanation Docstring coverage is 31.58% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 19 functions across 7 files. (1 skipped: 1 unsupported.)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
config/scripts/renderer-quadratic-scan-benchmark.mjs (1)
3-4: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy liftBenchmark production projections or label these as microbenchmarks.
Line 4 claims that every scenario drives a production export. The tab and sidebar timings run local implementations. The source-control timing runs
ancestorPathsBeforeandancestorPathsAfter; it only checks thatbuildSourceControlTreereturns a nonempty result. A production regression can therefore leave this script passing and still print a speedup.Extract benchmarkable production projection functions, or rename these rows and remove the production-equivalence claim.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 48821d9a-d298-4038-90de-de5e66b5cb98
📒 Files selected for processing (7)
config/scripts/renderer-quadratic-scan-benchmark.mjspackage.jsonsrc/renderer/src/components/right-sidebar/source-control-tree.tssrc/renderer/src/components/sidebar/use-workspace-kanban-search.tssrc/renderer/src/components/sidebar/workspace-kanban-search.tssrc/renderer/src/components/sidebar/worktree-header-section-boundaries.tssrc/renderer/src/components/tab-group/useTabGroupItemProjections.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
78576c2 to
0e2ddac
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Restored the
matchWorkspaceBoardWorktreesdoc contract — the "returnsnullwhen no filtering is active" JSDoc is back on the match function, andbuildWorkspaceBoardPaletteDocumentscarries its own; the duplicated board-policy note is folded into one comment. - Scoped the sidebar successor index per bucket —
indexBucketSuccessorsnow returnsMap<bucketKey, Map<id, successor>>, fixing a real bug the initial refactor introduced: an id sitting in more than one bucket could resolve a successor from the wrong bucket (the caller resolves viarepoHeaderBucketByRepoId, not bucket iteration order). - Added a focused boundaries test —
worktree-header-section-boundaries.test.tspins the per-bucket successor case, the no-successor fallback, and duplicate-header first-wins, all againstestimateRenderRowSizegeometry. - Reworked the benchmark into honest microbenchmarks — a shared
compare(label, scale, before, after)gate asserts baseline and indexed shapes agree before timing,envInt/repeatclean up the setup, and the misleading "drives a production export" claim is gone. The source-control scenario is now purely synthetic (nobuildSourceControlTreeimport); its production equivalence is covered by existing unit tests.
I verified the per-bucket fix against the pre-PR bucketIds.indexOf(id) + 1 semantics and the flat-map failure mode it corrects; the new tests' 28 / 32 / 116 geometry constants match estimateRenderRowSize, and the generic indexHeaderRenderRows keyOf filters reproduce the old findIndex first-wins behavior exactly for both repo and project-group headers.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
0e2ddac to
7a3bf90
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Benchmark now drives the production exports — scenarios 1, 3 and 4 time the real
matchWorkspaceBoardWorktrees/buildWorkspaceBoardPaletteDocuments,buildSourceControlTree, andgetRepoHeaderSectionEndByRepoIdagainst a hand-written reproduction of the pre-change loop, so a production regression now trips theJSON.stringifyequality gate instead of passing silently. Scenario 2 stays modelled on both sides and is now labelledmodelledin a newdrivescolumn. - Added a
.tsx/.jsonload hook — an esbuildtransformSyncstrips the transitively imported sidebar row-model icons, reusing the repo's established--experimental-transform-types+registerHooksbootstrap.
I diffed both inline reproductions against the pre-change sources (segments.slice(0, i + 1).join('/') and the per-header findIndex/indexOf loop) and against the current production functions: the equality gates compare array/object shapes (never a Map), so JSON.stringify is a faithful equivalence check, and repeat now returns its last result so the gate can serialize it.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
7a3bf90 to
aa9b868
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: c5e8b67f-fbe2-4551-a949-02c2c24d54be
📥 Commits
Reviewing files that changed from the base of the PR and between 0e2ddacf13c9b23c2a24d166e0f5cccda440242b and aa9b868fe3a141991b8162d0fe8daa8b19da897a.
📒 Files selected for processing (2)
config/scripts/renderer-quadratic-scan-benchmark.mjspackage.json
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
| // ------------------------------------------------- | ||
|
|
||
| console.log('Renderer quadratic-scan removals\n') | ||
| console.log('| projection | drives | scale | before | after | |') |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Label the speedup column.
Line 358 renders a blank sixth column. Line 362 emits the speedup value in that column. Add a speedup header so the Markdown report is self-describing.
Proposed fix
-console.log('| projection | drives | scale | before | after | |')
+console.log('| projection | drives | scale | before | after | speedup |')📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| console.log('| projection | drives | scale | before | after | |') | |
| console.log('| projection | drives | scale | before | after | speedup |') |
…r keystroke
Four renderer projections scanned a collection inside a loop over another collection, each on a
path that reruns per keystroke or per store write. All four now build the index once per stable
input, which is what the surrounding code already does for its other lookups.
`workspace-kanban-search.ts` called `searchWorktrees`, the convenience wrapper that builds the
palette document index inline. The board's filter hook memoized the whole call on the query, so
every character re-normalized and re-segmented every indexed field of every worktree — and did
it again on every agent-status tick while a query was active, since those churn board
identities. `buildWorkspaceBoardPaletteDocuments` splits out, memoized on
`[worktrees, repoMap]`; only the match reruns per keystroke. This is the shape
`worktree-jump-palette-document-index.ts` already provides for Cmd-J.
`useTabGroupItemProjections` resolved each editor tab against `state.openFiles` — the global
list across every worktree — and each `tabOrder` entry against the group's tabs, with a `.find`
per element. Both are now `Map` lookups, alongside the `terminalTabById` index the same file
already built. The memo key `groupTabs` gets a new identity on any unified-tab write, so this
ran on title, label and colour changes.
`buildSourceControlTree` rebuilt every ancestor path with `segments.slice(0, i + 1).join('/')`
per segment, making tree construction O(files x depth^2) in characters copied — on the path the
Source Control file filter rebuilds per keystroke. The path now accumulates.
`worktree-header-section-boundaries.ts` ran a full `findIndex` over the render rows for every
header row, plus an `indexOf` over the bucket ordering, in two `useMemo`s keyed on `renderRows`
— so it recomputed on every sidebar row-model change, not just during a drag. One indexing pass
each, first-match-wins to match `findIndex`/`indexOf`. The successor index is keyed per bucket
because a repo or group id can appear in more than one bucket ordering; a flat id-keyed map would
pick whichever bucket was iterated first. `worktree-header-section-boundaries.test.ts` pins that
and the first-wins duplicate-header case.
Measured by `pnpm bench:renderer-quadratic-scans`. Three scenarios time the production export
against a reproduction of the pre-change function; the tab-group scenario is modelled on both
sides because the projection lives inside a React hook. Each asserts before/after agree first.
| projection | drives | scale | before | after | |
| --- | --- | --- | --- | --- | --- |
| workspace board filter (per keystroke burst) | production | 300 worktrees x 12 keystrokes | 15.4 ms | 4.4 ms | 3.5x |
| tab-group projections (per unified-tab write) | modelled | 60 tabs x 120 open files | 1.23 ms | 0.34 ms | 3.6x |
| source-control tree build (per filter keystroke) | production | 5000 changed files | 6.2 ms | 3.9 ms | 1.6x |
| sidebar header boundaries (per row-model rebuild) | production | 80 repos x 600 rows | 2.0 ms | 0.8 ms | 2.6x |
The tree and sidebar wins are smaller than the scans they remove because the rest of each
function (tree finalize/sort, per-row size estimation) is linear and now dominates.
4,537 existing sidebar, tab-group and right-sidebar tests pass unmodified.
aa9b868 to
63e3b1a
Compare
…r keystroke (stablyai#18747) Four renderer projections scanned a collection inside a loop over another collection, each on a path that reruns per keystroke or per store write. All four now build the index once per stable input, which is what the surrounding code already does for its other lookups. `workspace-kanban-search.ts` called `searchWorktrees`, the convenience wrapper that builds the palette document index inline. The board's filter hook memoized the whole call on the query, so every character re-normalized and re-segmented every indexed field of every worktree — and did it again on every agent-status tick while a query was active, since those churn board identities. `buildWorkspaceBoardPaletteDocuments` splits out, memoized on `[worktrees, repoMap]`; only the match reruns per keystroke. This is the shape `worktree-jump-palette-document-index.ts` already provides for Cmd-J. `useTabGroupItemProjections` resolved each editor tab against `state.openFiles` — the global list across every worktree — and each `tabOrder` entry against the group's tabs, with a `.find` per element. Both are now `Map` lookups, alongside the `terminalTabById` index the same file already built. The memo key `groupTabs` gets a new identity on any unified-tab write, so this ran on title, label and colour changes. `buildSourceControlTree` rebuilt every ancestor path with `segments.slice(0, i + 1).join('/')` per segment, making tree construction O(files x depth^2) in characters copied — on the path the Source Control file filter rebuilds per keystroke. The path now accumulates. `worktree-header-section-boundaries.ts` ran a full `findIndex` over the render rows for every header row, plus an `indexOf` over the bucket ordering, in two `useMemo`s keyed on `renderRows` — so it recomputed on every sidebar row-model change, not just during a drag. One indexing pass each, first-match-wins to match `findIndex`/`indexOf`. The successor index is keyed per bucket because a repo or group id can appear in more than one bucket ordering; a flat id-keyed map would pick whichever bucket was iterated first. `worktree-header-section-boundaries.test.ts` pins that and the first-wins duplicate-header case. Measured by `pnpm bench:renderer-quadratic-scans`. Three scenarios time the production export against a reproduction of the pre-change function; the tab-group scenario is modelled on both sides because the projection lives inside a React hook. Each asserts before/after agree first. | projection | drives | scale | before | after | | | --- | --- | --- | --- | --- | --- | | workspace board filter (per keystroke burst) | production | 300 worktrees x 12 keystrokes | 15.4 ms | 4.4 ms | 3.5x | | tab-group projections (per unified-tab write) | modelled | 60 tabs x 120 open files | 1.23 ms | 0.34 ms | 3.6x | | source-control tree build (per filter keystroke) | production | 5000 changed files | 6.2 ms | 3.9 ms | 1.6x | | sidebar header boundaries (per row-model rebuild) | production | 80 repos x 600 rows | 2.0 ms | 0.8 ms | 2.6x | The tree and sidebar wins are smaller than the scans they remove because the rest of each function (tree finalize/sort, per-row size estimation) is linear and now dominates. 4,537 existing sidebar, tab-group and right-sidebar tests pass unmodified.

ELI5
Four places in the UI were looking things up the slow way: for each item in one list, scan the whole of another list. That's fine for five items and terrible for five hundred — and all four sit on paths that rerun on every keystroke or every time any tab or agent status changes.
The fix in every case is the same and boring: build a lookup table once, then look things up in it. Same results, same order, same everything — just without re-reading the phone book for every name.
Concretely:
What Changed
sidebar/workspace-kanban-search.ts+use-workspace-kanban-search.tsuseMemobuildWorkspaceBoardPaletteDocumentssplit out, memoized on[worktrees, repoMap]tab-group/useTabGroupItemProjections.ts.findoverstate.openFilesper editor tab;.findovergroupTabspertabOrderentryopenFileById/browserTabById/groupTabByIdmaps, alongside theterminalTabByIdthis file already builtright-sidebar/source-control-tree.tssegments.slice(0, i + 1).join('/')per segment → O(files × depth²) chars copiedsidebar/worktree-header-section-boundaries.tsfindIndexover render rows per header +indexOfper bucketfindIndex/indexOf; successors indexed per bucket since an id can sit in more than one bucket orderingsidebar/worktree-header-section-boundaries.test.tsThe board change mirrors the shape
worktree-jump-palette-document-index.tsalready provides for Cmd-J — the board caller was simply skipping the memoized entry point.Why
All four projections are O(n·m) on paths that rerun per keystroke or per store write, so they scale with the user's data in exactly the place that produces input lag. Indexing once per stable input is what each surrounding file already does for its other lookups.
Linked Issue
N/A — found during a renderer performance audit; no tracking issue.
Visual Proof
N/A — no visual or interaction change. The benchmark asserts each indexed shape returns the same result as the scan it replaces.
Measurements
pnpm bench:renderer-quadratic-scans(new, checked in). Three of the four scenarios import and time the production export against a hand-written reproduction of the pre-change function. The tab-group scenario is modelled on both sides — the projection lives inside theuseTabGroupItemProjectionsReact hook and cannot be imported without a renderer — so its row measures a reproduction of the change, not the change. Every scenario asserts before/after produce the same result before timing.The tree and sidebar wins are smaller than the scans they remove: the rest of each function (tree finalize/sort, per-row size estimation) is linear and now dominates. Earlier revisions of this PR reported 18.1x and 2.3x for those two rows from proxies that timed only the removed loop; those numbers were a model, not the function.
Negative user-facing trade-offs
None identified. Each change replaces a linear scan with an index built from the same input:
Mapconstruction is first-wins and I kept it that way explicitly, matchingfindIndex/indexOfsemantics. The benchmark asserts the production function's output equals the pre-change reproduction before timing, and the new boundaries test pins the duplicate-header and multi-bucket cases.slice().join('/').evidencePolicy: 'board'documents (Improve cmd j search keyword match #15170 — a card may only be hidden by text printed on it). Moving the build out did not change which fields are indexed.matchWorkspaceBoardWorktreeskeepsdocumentsoptional and falls back to building them, so no existing caller (including its tests) changes behaviour.Testing
pnpm tc✅npx vitest run src/renderer/src/components/{sidebar,tab-group,right-sidebar}— 4541 passed (4537 existing unmodified + 4 new) ✅pnpm run check:code-quality:changed✅pnpm bench:renderer-quadratic-scans✅ (macOS; pure TypeScript projections, no platform-dependent behaviour)I manually tested these changes locally
Automated tests added/updated, or explained why not below
Agent skill upstream boundary
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)