Repository navigation
perf(renderer): index the repo catalog compat merge and keep catalog identity - #13803
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (14)
🚧 Files skipped from review as they are similar to previous changes (14)
📝 WalkthroughWalkthroughRepository refresh reconciliation now preserves unchanged project, setup, and filter identities while updating changed, added, or removed rows. Generic structural comparison supports prototype-null records and caller-defined row identities. Repository merging uses indexed project and setup data. Filter cleanup avoids unnecessary allocations. Readonly array types now propagate through repository state, UI state, shared projections, and renderer components. Mergeability Score: ⚪ Minimal · up to This change indexes catalog compatibility merging and preserves array identity to reduce refresh-time work and unnecessary consumer updates; the supplied validation reports behavior parity and clean checks, so no actionable merge-blocking risk remains beyond normal review. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ 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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b9441c0c-e433-41d5-93a4-5059909ed6b5
📒 Files selected for processing (14)
src/renderer/src/App.tsxsrc/renderer/src/components/automations/AutomationEditorDialog.tsxsrc/renderer/src/components/automations/AutomationEditorDialogFooter.tsxsrc/renderer/src/components/right-sidebar/ai-vault-scope-paths.tssrc/renderer/src/components/sidebar/add-repo-skip-finalization.tssrc/renderer/src/components/sidebar/visible-worktrees.tssrc/renderer/src/lib/http-link-routing.tssrc/renderer/src/store/slices/repo-filter-selection.tssrc/renderer/src/store/slices/repo-identity-reconcile.tssrc/renderer/src/store/slices/repos-refresh-identity.test.tssrc/renderer/src/store/slices/repos.tssrc/renderer/src/store/slices/ui.tssrc/renderer/src/store/slices/worktrees.tssrc/shared/project-host-setup-projection.ts
mergeFetchedProjectCompatibilityForHost runs synchronously inside a zustand set() on every repo catalog refresh and was O(projects x (setups + repos)): getProjectHostIds / getExplicitProjectHostIds rescanned all setups and all repos once per project, and mergePreviousProjectMetadata rebuilt a full catalog repo key-set per project. Precompute the indexes once and hand each helper only its own project's slice. No ownership logic is reimplemented — the same resolvers run, just on pre-sliced inputs, memoized per project object. 200 repos 1.1 ms -> 0.2 ms (5.2x) 600 repos 11.2 ms -> 0.7 ms (15.3x) 1200 repos 43.0 ms -> 1.6 ms (26.6x) Verified against 4,000 randomized differential cases (duplicate repo ids, dangling sourceRepoIds, empty-repoId and orphan setups, dropped setups, local/SSH/runtime host mixes) comparing output element provenance and order against the previous implementation, not just deep structure. Each of the three index helpers was negative-controlled: breaking any one of them turns the differential red. Co-authored-by: Orca <[email protected]>
…tches Three fetch sites unconditionally reallocated filterRepoIds (`s.filterRepoIds.filter(...)`) on every repo catalog refresh, even when nothing was pruned. Six identity-sensitive subscribers select this array, including App.tsx at the root, so every refresh woke the whole tree. retainValidFilterRepoIds returns the input when every id is still valid; `.every` short-circuits so the common case allocates nothing at all. It lives in its own module rather than ui.ts: repos.ts does not import ui.ts and this codebase has a documented circular-slice-import hazard. The store type widens to `readonly string[]`, which takes three more declaration edits (visible-worktrees, add-repo-skip-finalization, the setter). PersistedUI.filterRepoIds deliberately stays `string[]`: main owns that array, and widening it would fail the ui-state schema-parity assertion unless the zod schema gained `.readonly()`, which Object.freeze()s every parsed `ui.set` payload arriving from a paired client. Copy at the App.tsx IPC boundary instead — one allocation per debounced 150ms persist, not per render. Co-authored-by: Orca <[email protected]>
…ches mergeFetchedProjectCompatibilityForHost always allocates — sourceRepoIds is rebuilt per project and fetched setups arrive freshly cloned over IPC — so `projects` and `projectHostSetups` lost both array and element identity on every catalog refresh. #13770's identity work covered only projectGroups and folderWorkspaces. Reconcile both at the merge's single return site (five callers) against `previous`, keyed on what each merge already dedups by: project.id, and getProjectHostSetupOwnerKey for setups. setup.id is deliberately not the setup key — the repo-derived fallback sets id = repo.id, so one repo on two hosts yields two setups sharing an id, and keying on it would splice the wrong host's routing metadata into a row. filterSetupsForPrunedRepoRows had to stop returning `[...setups]` unconditionally: three callers feed its result in as `previous`, so the throwaway copy defeated the reconcile even though element identity survived. Rather than add a third parallel deep-equality helper, generalize reconcileFetchedRepos (#13744) into reconcileCatalogRows and delete repos.ts's isPlainCatalogObject + areCatalogEntriesEqual (#13770). The two were the same algorithm modulo the null-prototype branch; the survivor takes the union of both prototype guards, which is strictly more permissive and so can only reconcile more, never mask a change. repos-catalog-merge-identity.test.ts and repo-identity-reconcile.test.ts stay green unmodified as the proof. Element-level reuse means a consumer mutating a Project or ProjectHostSetup in place would corrupt the previous render's object, so RepoSlice['projects'], ['projectHostSetups'] and ProjectHostSetupProjection widen to readonly. That is the safety mechanism, not polish — it caught two real in-place accumulators (ai-vault-scope-paths and the runtime-host purge in worktrees.ts), which now annotate mutable locals per the repo's readonly precedent. No casts added. Co-authored-by: Orca <[email protected]>
A dedicated file — repos.test.ts is already at the max-lines ceiling and these are a distinct concern. The fixture is production-shaped on purpose. A scalar-only repo reconciles even when the structural compare is broken, which is how an earlier version of this work shipped green while being completely inert; addedAt is pinned non-zero because project-host-setup-projection falls back to `repo.addedAt || now`, so a zero timestamp stamps Date.now() into every projection and nothing ever reconciles. Every mocked fetch returns a structuredClone so identity can never match by accident. Every identity assertion was verified red against reverted source: - drop reconcileCatalogRows from the merge return -> no-op-refetch identity and per-element reuse fail - filterSetupsForPrunedRepoRows back to `[...setups]` -> no-op-refetch identity fails - retainValidFilterRepoIds back to `.filter(...)` -> both filter-identity cases fail - areValuesEqual reduced to `a === b` -> all three reconcile cases fail - areValuesEqual forced to `true` -> all six change-propagation cases fail - setup key switched to setup.id -> the two-hosts-one-repo-id case fails Co-authored-by: Orca <[email protected]>
d681dfd to
6a6682f
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
projectHostSetupProjectionFromRepos used `repo.addedAt || now`, so a missing or zero addedAt stamped Date.now() into createdAt/updatedAt on every refresh. #13803's reconcile then treated the project as changed and never reused it. Use a finite check with a stable 0 fallback, and treat 0 as unknown in merge so a persisted createdAt is not wiped. Refresh-identity tests use production-shaped nested fixtures plus structuredClone and go red if the fallback is reverted. Co-authored-by: Orca <[email protected]>
* fix(store): keep project catalog identity when repo.addedAt is 0 projectHostSetupProjectionFromRepos used `repo.addedAt || now`, so a missing or zero addedAt stamped Date.now() into createdAt/updatedAt on every refresh. #13803's reconcile then treated the project as changed and never reused it. Use a finite check with a stable 0 fallback, and treat 0 as unknown in merge so a persisted createdAt is not wiped. Refresh-identity tests use production-shaped nested fixtures plus structuredClone and go red if the fallback is reverted. Co-authored-by: Orca <[email protected]> * type(shared): return readonly setups from getProjectHostSetupsForProject The helper already takes a readonly catalog and returns a filter subset. Mark the return readonly so callers cannot mutate a live setups array. Co-authored-by: Orca <[email protected]> * style: oxfmt projection files and drop stale addedAt comment oxfmt --check failed on the addedAt identity commit. Also stop claiming the projection still restamps Date.now() when addedAt is 0. Co-authored-by: Orca <[email protected]> * fix(store): treat createdAt 0 as unknown when merging sibling repos Repo order decided a project's createdAt: a zero-addedAt repo seeded the accumulator with 0, and the merge only treated the *incoming* addedAt as unknown, so min(0, 100) kept 0 when the unknown sibling came first. Share unknown-aware mergeCatalogCreatedAt/mergeCatalogUpdatedAt helpers and apply them on both sides of the projection merge and of the renderer's cross-host mergeProjectCompatibilityProject, which had the same 0-poisoning via Math.min(base.createdAt, overlay.createdAt). Co-authored-by: Orca <[email protected]> * test(store): pass a valid updateProject payload in createdAt merge case updateProject only accepts localWindowsRuntimePreference. The new unknown-vs-known createdAt test used displayName and failed typecheck. Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
…identity (stablyai#13803) * perf(renderer): index project host ownership on repo catalog refresh mergeFetchedProjectCompatibilityForHost runs synchronously inside a zustand set() on every repo catalog refresh and was O(projects x (setups + repos)): getProjectHostIds / getExplicitProjectHostIds rescanned all setups and all repos once per project, and mergePreviousProjectMetadata rebuilt a full catalog repo key-set per project. Precompute the indexes once and hand each helper only its own project's slice. No ownership logic is reimplemented — the same resolvers run, just on pre-sliced inputs, memoized per project object. 200 repos 1.1 ms -> 0.2 ms (5.2x) 600 repos 11.2 ms -> 0.7 ms (15.3x) 1200 repos 43.0 ms -> 1.6 ms (26.6x) Verified against 4,000 randomized differential cases (duplicate repo ids, dangling sourceRepoIds, empty-repoId and orphan setups, dropped setups, local/SSH/runtime host mixes) comparing output element provenance and order against the previous implementation, not just deep structure. Each of the three index helpers was negative-controlled: breaking any one of them turns the differential red. Co-authored-by: Orca <[email protected]> * perf(renderer): keep the repo filter array identity across no-op refetches Three fetch sites unconditionally reallocated filterRepoIds (`s.filterRepoIds.filter(...)`) on every repo catalog refresh, even when nothing was pruned. Six identity-sensitive subscribers select this array, including App.tsx at the root, so every refresh woke the whole tree. retainValidFilterRepoIds returns the input when every id is still valid; `.every` short-circuits so the common case allocates nothing at all. It lives in its own module rather than ui.ts: repos.ts does not import ui.ts and this codebase has a documented circular-slice-import hazard. The store type widens to `readonly string[]`, which takes three more declaration edits (visible-worktrees, add-repo-skip-finalization, the setter). PersistedUI.filterRepoIds deliberately stays `string[]`: main owns that array, and widening it would fail the ui-state schema-parity assertion unless the zod schema gained `.readonly()`, which Object.freeze()s every parsed `ui.set` payload arriving from a paired client. Copy at the App.tsx IPC boundary instead — one allocation per debounced 150ms persist, not per render. Co-authored-by: Orca <[email protected]> * perf(renderer): reconcile projects and host setups across no-op refetches mergeFetchedProjectCompatibilityForHost always allocates — sourceRepoIds is rebuilt per project and fetched setups arrive freshly cloned over IPC — so `projects` and `projectHostSetups` lost both array and element identity on every catalog refresh. stablyai#13770's identity work covered only projectGroups and folderWorkspaces. Reconcile both at the merge's single return site (five callers) against `previous`, keyed on what each merge already dedups by: project.id, and getProjectHostSetupOwnerKey for setups. setup.id is deliberately not the setup key — the repo-derived fallback sets id = repo.id, so one repo on two hosts yields two setups sharing an id, and keying on it would splice the wrong host's routing metadata into a row. filterSetupsForPrunedRepoRows had to stop returning `[...setups]` unconditionally: three callers feed its result in as `previous`, so the throwaway copy defeated the reconcile even though element identity survived. Rather than add a third parallel deep-equality helper, generalize reconcileFetchedRepos (stablyai#13744) into reconcileCatalogRows and delete repos.ts's isPlainCatalogObject + areCatalogEntriesEqual (stablyai#13770). The two were the same algorithm modulo the null-prototype branch; the survivor takes the union of both prototype guards, which is strictly more permissive and so can only reconcile more, never mask a change. repos-catalog-merge-identity.test.ts and repo-identity-reconcile.test.ts stay green unmodified as the proof. Element-level reuse means a consumer mutating a Project or ProjectHostSetup in place would corrupt the previous render's object, so RepoSlice['projects'], ['projectHostSetups'] and ProjectHostSetupProjection widen to readonly. That is the safety mechanism, not polish — it caught two real in-place accumulators (ai-vault-scope-paths and the runtime-host purge in worktrees.ts), which now annotate mutable locals per the repo's readonly precedent. No casts added. Co-authored-by: Orca <[email protected]> * test(renderer): cover repo catalog refresh identity A dedicated file — repos.test.ts is already at the max-lines ceiling and these are a distinct concern. The fixture is production-shaped on purpose. A scalar-only repo reconciles even when the structural compare is broken, which is how an earlier version of this work shipped green while being completely inert; addedAt is pinned non-zero because project-host-setup-projection falls back to `repo.addedAt || now`, so a zero timestamp stamps Date.now() into every projection and nothing ever reconciles. Every mocked fetch returns a structuredClone so identity can never match by accident. Every identity assertion was verified red against reverted source: - drop reconcileCatalogRows from the merge return -> no-op-refetch identity and per-element reuse fail - filterSetupsForPrunedRepoRows back to `[...setups]` -> no-op-refetch identity fails - retainValidFilterRepoIds back to `.filter(...)` -> both filter-identity cases fail - areValuesEqual reduced to `a === b` -> all three reconcile cases fail - areValuesEqual forced to `true` -> all six change-propagation cases fail - setup key switched to setup.id -> the two-hosts-one-repo-id case fails Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
* fix(store): keep project catalog identity when repo.addedAt is 0 projectHostSetupProjectionFromRepos used `repo.addedAt || now`, so a missing or zero addedAt stamped Date.now() into createdAt/updatedAt on every refresh. stablyai#13803's reconcile then treated the project as changed and never reused it. Use a finite check with a stable 0 fallback, and treat 0 as unknown in merge so a persisted createdAt is not wiped. Refresh-identity tests use production-shaped nested fixtures plus structuredClone and go red if the fallback is reverted. Co-authored-by: Orca <[email protected]> * type(shared): return readonly setups from getProjectHostSetupsForProject The helper already takes a readonly catalog and returns a filter subset. Mark the return readonly so callers cannot mutate a live setups array. Co-authored-by: Orca <[email protected]> * style: oxfmt projection files and drop stale addedAt comment oxfmt --check failed on the addedAt identity commit. Also stop claiming the projection still restamps Date.now() when addedAt is 0. Co-authored-by: Orca <[email protected]> * fix(store): treat createdAt 0 as unknown when merging sibling repos Repo order decided a project's createdAt: a zero-addedAt repo seeded the accumulator with 0, and the merge only treated the *incoming* addedAt as unknown, so min(0, 100) kept 0 when the unknown sibling came first. Share unknown-aware mergeCatalogCreatedAt/mergeCatalogUpdatedAt helpers and apply them on both sides of the projection merge and of the renderer's cross-host mergeProjectCompatibilityProject, which had the same 0-poisoning via Math.min(base.createdAt, overlay.createdAt). Co-authored-by: Orca <[email protected]> * test(store): pass a valid updateProject payload in createdAt merge case updateProject only accepts localWindowsRuntimePreference. The new unknown-vs-known createdAt test used displayName and failed typecheck. Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
Summary
mergeFetchedProjectCompatibilityForHostruns synchronously inside a zustandset()on every repo catalog refresh, and was O(projects × (setups + repos)). This indexes it, and stops three slices losing their array identity on the same path.Built on current
main(it supersedes #13788, which was written pre-#13770 and became conflicting).2c464a7c3a2da7filterRepoIdskeeps identity when nothing is pruned7ce561bprojects/projectHostSetups; delete the duplicate comparatord681dfd1. The quadratic merge
Three per-project rescans:
getProjectHostIds/getExplicitProjectHostIdsrescanned all setups and repos once per project, andmergePreviousProjectMetadatarebuilt a full repo key-set per project.Fixed by precomputing indexes once and handing the existing ownership helpers pre-sliced inputs. No ownership logic was reimplemented, so the results are provably identical rather than "hopefully equivalent".
2. Three slices losing identity
projects/projectHostSetups— the merge always allocates (sourceRepoIdsrebuilt per project; setups arrive freshly cloned over IPC), so these now reconcile againstprevious.filterSetupsForPrunedRepoRowsalso had to stop returning[...setups], or the reconcile compares against a throwaway.filterRepoIds— returns the input when nothing is pruned. Note[].filter(...)still allocates, so onmainthis churned even for users with no filter set.3. Deletes a duplicated comparator
#13744 and #13770 landed near-identical structural deep-equality helpers into this file hours apart, from parallel sessions. This generalizes
reconcileFetchedReposintoreconcileCatalogRows<T>and deletesrepos.ts'sisPlainCatalogObject+areCatalogEntriesEqual. No third comparator added;repos.tsshrinks. It also removes a pre-existingas (keyof Repo)[]cast.(A follow-up PR unifies the remaining copies — see below.)
Measured — branch tip, not the best commit
The per-commit number for
2c464a7in isolation is 5.2×/15.3×/26.6×, and two independent reviewers reproduced it. But that is not what shipping this branch gives you, because the reconcile in7ce561badds a structural walk back. Branch tip, medians of 40 rounds across 3 fresh node processes, steady-state no-op refresh:Crossover is around 50 repos; below that this is neutral-to-marginally-slower. The merge also runs once per host, so an all-hosts refresh pays the figure N times.
The consumer win
The strongest effect is one I had originally failed to cite.
project-host-setup-selector.tskeys a WeakMap chain on(repos, projects, projectHostSetups)array identity, andgetProjectHostSetupProjectionFromStateisObject.is-compared as a zustand selector. BecauseprojectsandprojectHostSetupswere reallocated every refresh, that cache missed 100% of the time and every consumer got a fresh projection object:WorktreeList,TerminalPane(one per pane),TabBarQuickCommandsButton,AiVaultPanel, pluscomputeRenderedSidebarWorktreeOrder. Verified stable across three identical fetches now.filterRepoIdshas six plain-identity subscribers:App.tsx:698,WorktreeList.tsx:5232,SidebarFilter.tsx:69,SidebarWorkspaceOptionsMenu.tsx:46,SidebarRepositoryFilterSection.tsx:42,use-visible-workspace-kanban-worktree-ids.ts:45.Known limitation — multi-host array identity
The array-identity half does not hold when refreshes alternate between different host scopes.
mergeProjectCompatibilityProjectsorders preserved-before-fetched (repos.ts:577-584), so refreshing host A and host B yield different orders and the reconcile correctly returns a new array. Element identity still holds; the WeakMap chain above keys on array identity, so multi-host users get the element benefit but not the projection benefit.This is pre-existing merge behaviour, not introduced here, and stabilizing that ordering is a separate change. Flagging it rather than letting the headline imply a win it does not deliver for the multi-host case.
Also note:
readonlycaught two array-level accumulators, but it does not prevent element-level mutation of a reusedProject/ProjectHostSetup.Verification
Adversarial review by four independent agents; no P0/P1 correctness findings.
mainacross 20,000 randomized catalogs (duplicate repo/project ids, danglingsourceRepoIds, empty-stringrepoIdsetups, local/SSH/runtime mixes,runtimeOwnerEnvironmentId,localWindowsRuntimePreferenceabsent/undefined/defined). Element provenance diverges only in the intended direction (reusing a previous object wheremainallocated), never toward over-preservation.areCatalogEntriesEqual.filterSetupsForPrunedRepoRows; revertingretainValidFilterRepoIds; reducing the compare toa === b; forcing it totrue; switching the setups key tosetup.id. Reducing to reference-equality turning the tests red is what proves the production-shaped fixture is load-bearing — a scalar-only fixture stays green while the feature is dead, which is exactly how an earlier version of this work shipped inert.tscweb + node + cli clean; oxlint, oxfmt, max-lines ratchet clean. Noascasts,as unknown as,@ts-expect-error, or lint disables added.Follow-ups (not in this PR)
mergeProjectHostSetupCompatibility+recordSshRepoReadoptionsstill spread fresh arrays intoset()without going through the compat merge. Only fires on SSH re-adoption; ~4 lines now thatfilterSetupsForPrunedRepoRowsreturns its input.addedAt === 0/absent silently never reconcile (projectHostSetupProjectionFromReposusesrepo.addedAt || now). Degraded-data only, but it turns the optimization off quietly rather than failing loudly.repos.tsis large and already carries a pre-existingmax-linessuppression.Made with Orca 🐋