Repository navigation
Conversation
Two independent costs on every repo catalog refresh, both in repos.ts.
1. mergeFetchedProjectCompatibilityForHost ran synchronously inside a zustand
set() and was O(projects x (setups + repos)): getProjectHostIds and
getExplicitProjectHostIds rescanned all setups and repos per project, and
mergePreviousProjectMetadata rebuilt a full repo key-set per project.
Precompute the indexes once and hand each helper only its own project's
slice, rather than reimplementing any ownership logic.
200 repos 7.7 ms -> 1.0 ms (7.8x)
600 repos 33.2 ms -> 1.2 ms (27.8x)
1200 repos 202.2 ms -> 8.3 ms (24.3x)
Verified against 4,002 differential cases (2 realistic + 4,000 randomized:
duplicate repo/project ids, dangling sourceRepoIds, empty repoId setups,
local/SSH/runtime mixes) comparing output element provenance and order, not
just deep structure.
2. Three slices lost their array identity on every refresh, defeating
identity-keyed memos and waking subscribers:
- projects / projectHostSetups: the merge always allocates (sourceRepoIds is
rebuilt per project, setups arrive freshly cloned over IPC), so reconcile
against `previous`. filterSetupsForPrunedRepoRows also had to stop copying
unconditionally, or the reconcile would compare against a throwaway.
- filterRepoIds: return the input when nothing was pruned. Six
identity-sensitive subscribers, including App.tsx at the root.
- folderWorkspacePathStatuses: keep the identity when already empty. Entries
self-invalidate on requestSnapshot drift and a 10s TTL, so the defensive
reset was never the correctness mechanism.
Co-authored-by: Orca <[email protected]>
…log types reconcileFetchedRepos already reused equal entries and the whole array when nothing moved; projects and projectHostSetups need the same treatment. Extract reconcileFetchedEntries with an identity-key callback and keep the repo function as a thin wrapper, rather than adding a near-duplicate module. The structural value compare matters here for the same reason it did for repos: Project.sourceRepoIds is a required array and ProjectHostSetup.hookSettings is two levels deep, so a reference compare would report every entry changed and the reconcile would never fire. Widen the arrays these now hand back to readonly, following the RepoSlice precedent: returning live store state behind a mutable type is the footgun that change called out. Local accumulators are annotated mutable and built from copies. No casts added. Co-authored-by: Orca <[email protected]>
Split the refresh-identity cases out of repos.test.ts into a dedicated file — repos.test.ts crossed the 800-line limit, and these are a distinct concern. Fixtures are production-shaped on purpose. A scalar-only repo reconciles even when the compare is broken, which is exactly how an earlier version of this work shipped green while being inert. Each identity assertion was verified to fail against a reverted source. Also completes the ProjectGroup and FolderWorkspace fixtures in useAgentDetectionTarget.test.ts so they satisfy their types at the declaration instead of being laundered through the surrounding state cast. Co-authored-by: Orca <[email protected]>
033d4ac to
121ded5
Compare
|
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: 📥 CommitsReviewing files that changed from the base of the PR and between 3713dd7 and 033d4ac26e8d2581ba4c9fcc90fc1a4fd95a4b99. 📒 Files selected for processing (15)
📝 WalkthroughWalkthroughThe change updates project, setup, and repository-filter collections to use readonly array types. Repository refresh logic now performs generic structural reconciliation and preserves unchanged object and array references. Project and setup catalogs use scoped host ownership indexes. Refresh paths conditionally prune filters and clear path-status caches. Tests cover identity preservation, catalog changes, filter pruning, and stale workspace status removal. UI persistence copies readonly filter arrays before serialization. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
⚔️ Resolve merge conflicts 💡
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 |
Superseded before review — closing shortlyThis branch was written against an older The conflict is with #13770 ("keep catalog array identity and path-status cache on no-op refetches"), which landed from a parallel session while this was in flight. Checking this branch against current
So the headline (the quadratic merge) and two identity fixes are still needed, but roughly a third of this branch is now duplicate work, and landing it as-is would entrench the duplication rather than fix it. Rather than resolve a conflict into a branch that would add a second structural-equality helper, this is being rebuilt on current
The benchmark numbers quoted here were measured against the older Worth noting for coordination: this is the second collision in this file today. #13744 and #13770 both landed structural-equality helpers within hours of each other from different sessions. |
Summary
Follow-up to #13744. Profiling the leftovers from that PR surfaced something much bigger than the identity work it was chasing: a quadratic merge running synchronously inside a zustand
set()on every repo catalog refresh.bb8ca450754aaareadonly033d4ac1. The quadratic merge — the headline
mergeFetchedProjectCompatibilityForHostruns synchronously inside a zustandset()on every repo refresh (fetchRepos,fetchRuntimeEnvironmentRepos,fetchReposForAllHosts). It was O(projects × (setups + repos)):getProjectHostIds/getExplicitProjectHostIdsrescanned all setups and repos, once per projectmergePreviousProjectMetadatarebuilt a full repo key-set (new Set(reposById.keys())) per project — a hidden quadratic termAt 1200 repos that is ~200 ms of main-thread work — roughly a dozen dropped frames — inside a store write.
The fix precomputes the indexes once and hands each helper only its own project's slice. No ownership logic was reimplemented; the existing helpers are called verbatim with pre-sliced inputs, so the results are provably identical rather than "hopefully equivalent".
Warm refresh (previous state already holds the catalog — the steady-state case):
Growth is now roughly linear rather than quadratic. Absolute numbers are noisy run-to-run (the 1200 baseline ranged 156–473 ms); the ratio was stable.
2. Three slices that lost array identity every refresh
Same class of bug #13744 fixed for
repos, in the slices next to it:projects/projectHostSetups— the merge always allocates (sourceRepoIdsis rebuilt per project; setups arrive freshly cloned over IPC), so these now reconcile againstprevious.filterSetupsForPrunedRepoRowsalso had to stop copying unconditionally — otherwise the reconcile compares against a throwaway copy and achieves nothing.filterRepoIds— returns the input when nothing was pruned. This one has the widest reach of the three: six identity-sensitive subscribers includingApp.tsxat the root.folderWorkspacePathStatuses— keeps identity when already empty, at all six catalog-fetch sites (useIpcEventsfiresfetchRepos+fetchProjectGroups+fetchFolderWorkspacestogether, so fixing only the repo sites would leave the sidebar churning).On that last one I checked whether the reset was load-bearing before touching it. It isn't: entries already self-invalidate via a
requestSnapshotcheck on read (repos.ts:1609) and write (:2377), plus a 10s TTL and a component-level force-refetch on membership change. Two things settled it —fetchRuntimeEnvironmentReposalready mutatesreposwithout clearing this cache (so it would be a live bug if the reset were required), and the only test asserting a clear covers a mutation site, using identity-agnostictoEqual({}).3.
readonlytypesFollowing the
RepoSlice['repos']precedent — returning live store state behind a mutable type is the footgun that PR called out.RepoSlice['projects'],['projectHostSetups'],UISlice['filterRepoIds'], andProjectHostSetupProjectionare nowreadonly. Local accumulators are annotated mutable and built from copies. Noascasts,as unknown as, or@ts-expect-erroradded.At the persisted-UI IPC boundary (
App.tsx) I copy rather than widen a shared main-process type — that call is debounced and serializes anyway.Honest accounting of the payoff
The identity half is not a CPU win. Measured: the projection WeakMap hit saves ~2 µs at 200 repos and ~0 at 1200, because the selector's expensive prologue (
normalizeHydratedProjectHostSetupProjection) is uncached and runs before any cache lookup. Reconciliation also makes the write path slightly slower.What it actually buys is render churn:
useProjectHostSetupProjectiongoes from "new object every refresh" to reference-stable, which stops ~24 component re-renders (mostly per-paneTerminalPane) plus thebuildRowssidebar-tree rebuild inWorktreeList, and two spurious effect re-runs (AiVaultPanelscope paths, native-chat skill rescan).The speedup in §1 is the real win here. I have also posted a correction on #13744, whose cache claims that profiling falsified.
Testing
Refresh-identity cases live in a new
repos-refresh-identity.test.ts(repos.test.tscrossed the 800-line limit, and these are a distinct concern — nomax-linesdisable added).Every identity assertion was verified to fail against a reverted source. Fixtures are production-shaped on purpose: a scalar-only repo reconciles even when the compare is broken, which is exactly how an earlier version of this work shipped green while being completely inert.
tscweb + node + cli — zero errorsResidual risk
getProjectHostSetupOwnerKey(threeJSON.stringifycalls per setup) and object spreads inmergeProjectCompatibilityProject— together ~40% of what's left. A non-JSON owner key is a cheap follow-up.projectHostSetupProjectionFromRepossetscreatedAt: repo.addedAt || now, so a repo withaddedAt === 0would get a drifting timestamp and never reconcile.addedAtis required and real repos have it, so this is no worse than today — but it is why a fixture missingaddedAtwould make the fix look broken.folderWorkspacePathStatusesreset entirely (rather than guarding it) is defensible on the evidence above and would close a window where the folder-path guard is briefly un-gated, but that is a real behavior change and deserves its own PR.Made with Orca 🐋