Repository navigation
perf(sidebar): stop re-allocating 423 workspace descriptors and 193 bucket projections per recompute - #18241
Conversation
…ucket projections per recompute Layers three identity memos onto the row cache #18222 landed, without changing what the four sidebar numbers say in any state. - The active-workspace descriptor list is memoized on the four slices `collectActiveDashboardWorkspaces(state, false)` actually reads. - Each worktree's bucket tally is memoized on its rows plus the acknowledgement map, so a ping that rebuilds one worktree no longer re-projects the board. - The `useShallow` selector becomes a module-level 14-identity gate, which allocates nothing on the unchanged path. - The counts object is reused by identity when all four totals hold.
📝 WalkthroughWalkthroughThe dashboard bucket count hook now uses an identity-preserving selector for tracked state slices. The bucket count builder memoizes active workspace descriptors and per-worktree tallies, prunes removed worktrees, and reuses unchanged count objects. New tests cover allocation behavior, selective recomputation, cache invalidation, staleness boundaries, mutation sequences, and equivalence with an unmemoized oracle. Merge Risk: ⚪ Minimal · up to The PR reuses existing dashboard data to reduce repeated in-memory allocations without changing displayed counts. One test subcase could exercise cache hits more precisely, but the relevant boundary remains covered and no actionable merge-blocking risk remains. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description provides detailed ELI5, rationale, implementation, measurements, scope, correctness, linked issue, and testing information. It omits some template headings and checklist items, including an explicit Visual Proof N/A statement, but the core information is complete. Full details: Linked Issues checkExplanation The PR satisfies the relevant objective for ✨ 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
A performance-only refactor that memoizes three allocation hot-spots in the sidebar's bucket-count path, leaving the computed numbers identical while cutting per-recompute allocations. Tests assert the memoized builder stays equivalent to an unmemoized reference walk, and all new/changed tests plus the pre-existing cache tests pass.
- Workspace descriptor memo —
selectActiveDashboardWorkspacesreuses the workspace list whilerepos/worktreesByRepo/folderWorkspaces/projectGroupsidentities hold. I tracedcollectActiveDashboardWorkspaces(state, false)and confirmed the metadata-free read set is exactly those four slices:resolveHostLabel,buildHostLabelLookup,isFolderRepo, andremoteHostKindare all gated behindincludeMapMetadata. - Per-worktree tally memo —
tallyWorktreeRowscaches each worktree's bucket tally keyed on itsrows+acknowledgedAgentsByPaneKeyidentities, matchingdashboardRowBucketProjection's read set (row +ack[panexistKey]), so an acknowledgement recount never rebuilds rows. Tally eviction runs againstseenWorktreeIdsbeforefinishWorktreeAgentRowsCachePass, so the map stays bounded. - Store-selector gate —
selectAgentBucketCountStatereplaces zustand'suseShallowwith a module-level 14-way===gate; since the slice set is unchanged from the old selector and it is a pure function of the singleton store, one gate correctly serves the singleAgentDashboardSidebarEntryconsumer. ThelastCountsidentity reuse can only suppress re-renders when all four totals are actually equal.
The equivalence matrix closes the NOW + STALE boundary the earlier #18141 matrix missed and asserts a non-vacuous working: 1 → working: 0 decay across a cache hit. I verified the memo keys against the store's immutable-update convention (worktrees/folder workspaces are replaced by identity, never mutated in place).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…/sidebar-bucket-count-alloc # Conflicts: # src/renderer/src/components/dashboard/useAgentBucketCounts.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/components/dashboard/build-dashboard-bucket-counts.equivalence.test.ts (1)
303-303: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueHoist
stateout of the clock loop so this test exercises cache hits.
baseState()allocates newrepos,worktreesByRepo,folderWorkspaces, andprojectGroupsobjects on each call. Because it runs inside theCLOCK_WALKloop, every step changes those slice identities and misses the workspace memo and the tally memo. This test therefore repeats cold-cache equivalence and never reaches theBASE + STALEcache hit that theCLOCK_WALKcomment describes.The boundary is still covered by the cumulative test and by the explicit boundary test, so this is a precision improvement only.
♻️ Proposed change to hold state identity across the clock walk
for (const mutation of MUTATIONS) { const cache = createDashboardBucketCountsCache() + const state = mutation.apply(baseState()) for (const step of CLOCK_WALK) { - const state = mutation.apply(baseState()) expect(
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 6c7c7bdc-eb46-43d2-9f62-3055a3c06108
📒 Files selected for processing (7)
src/renderer/src/components/dashboard/build-dashboard-bucket-counts.allocation.test.tssrc/renderer/src/components/dashboard/build-dashboard-bucket-counts.equivalence.test.tssrc/renderer/src/components/dashboard/build-dashboard-bucket-counts.tssrc/renderer/src/components/dashboard/dashboard-snapshot-workspaces.tssrc/renderer/src/components/dashboard/useAgentBucketCounts.gate.test.tssrc/renderer/src/components/dashboard/useAgentBucketCounts.test.tsxsrc/renderer/src/components/dashboard/useAgentBucketCounts.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
…ucket projections per recompute (stablyai#18241) Layers three identity memos onto the row cache stablyai#18222 landed, without changing what the four sidebar numbers say in any state. - The active-workspace descriptor list is memoized on the four slices `collectActiveDashboardWorkspaces(state, false)` actually reads. - Each worktree's bucket tally is memoized on its rows plus the acknowledgement map, so a ping that rebuilds one worktree no longer re-projects the board. - The `useShallow` selector becomes a module-level 14-identity gate, which allocates nothing on the unchanged path. - The counts object is reused by identity when all four totals hold.

Salvages the still-valid parts of #18141, rebuilt on the row-cache design #18222 landed. #18141 is closed as superseded; its count-cache design (a per-worktree
validUntilclock boundary) is not reintroduced — main's row cache wins.ELI5
The sidebar shows four numbers: how many agents are waiting on you, working, done, or idle. To get them, Orca walks every workspace you have open and sorts each agent into one of the four piles.
#18222 made the expensive middle step — rebuilding each workspace's agent list — reuse its previous answer when nothing about that workspace changed. But two cheaper steps around it were still redone from scratch on every single recompute:
repos,worktreesByRepo,folderWorkspaces,projectGroups), none of which change when an agent sends a status ping.This PR memoizes both, plus swaps the store subscription's
useShallowcomparison — which allocated two arrays, 28 tuples and twoMaps on every store write in the app just to conclude nothing moved — for a direct 14-way===. Finally, when the four numbers come out the same as last time, the same object is handed back, so nothing downstream re-renders.Zero change to what the numbers say.
Measurements
Baseline is current
main(c0e5b189aa0), not #18141's numbers, which measured against a pre-#18222 main and are invalid.Method: main's
buildDashboardBucketCountsvendored side-by-side with this branch's, both driven over the same fixture (10 repos / 423 worktrees / 193 with tabs / 386 tabs) for 100 calls through one warm cache. Deterministic operation counts, because wall-clock swung ~2x between runs on a loaded machine. Wall times are best-of-5 runs.Scenario A — ordinary agent status ping (
agentStatusEpochunchanged; dominant idle-app traffic)mainScenario B — retention-relevant change (
agentStatusEpochbumps)mainStore-subscription selector, 200k writes, best of 8, all 14 slices unchanged:
useShallowObject.entriescalls per writeMapallocations per writeWhat this does not fix, and what it would cost
Scenario B's
423 → 423row recomputes is untouched, and it is the bigger remaining prize.agentStatusEpochis a coarse invalidation token: main'sworktree-agent-rows-cachecompares it for equality and discards every worktree's rows when it moves. The epoch bumps on retention-relevant changes, migration changes, orphan eviction, and the freshness scheduler's stale-boundary tick — not rare.#18141 solved this with a per-worktree
validUntil: the minimum futureagentStatusEvidenceObservedAt(entry) + AGENT_STATUS_STALE_AFTER_MSover that worktree's entries, so a worktree with no entry near its freshness boundary survives an epoch bump. I traced the clock consumers to confirm the idea is still sound on today's pipeline — onlyworktree-agent-rows.ts:176and:221readnowin a way that can move a bucket; title-derived rows stampupdatedAt: nowbut carrystartedAt: 0, whichdashboardRowBucketProjectionshort-circuits.Assessment: feasible, but out of scope here.
worktree-agent-rows-cache.tshas three other consumers —build-dashboard-snapshot.ts,useDashboardPopoutBridge.ts,useLiveDashboardSnapshot.ts— so the token cannot simply be swapped. It would need:now >= computedAt && now <= validUntilin addition to (not instead of) the existing input-identity checks, since the epoch also signals non-clock changes;restoredUnconfirmedanddoneentries excluded from the boundary (they are never fresh / never decay), which errs toward extra rebuilds and never toward a stale count;now— the pop-out bridge in particular passes anowfrom a different tick source;Prize, from the table above: 423 → ~1 row-pipeline recomputes per call in Scenario B, and it would speed up the pop-out dashboard too, since it shares the cache. That is a real win but it is a redesign of code that landed after #18141 was written, so it belongs to whoever owns the dashboard cache rather than to a rebase.
Correctness
useShallow→ module gate. The gate compares the same 14 slice identitiesshallow()compared, and returns the previous object when they all hold. The returned object doubles as theDashboardSnapshotStatehanded to the builder, so the object is built once per real change instead of once per store write. The gate is module-level rather than per-hook because it is a pure function of the store state — one gate correctly serves every mounted consumer.main, since a wrong key here silently serves a stale workspace list. WithincludeMapMetadata: false,resolveHostLabelis unreachable (both call sites are gated), sobuildHostLabelLookupnever runs andsshTargetLabels/runtimeEnvironments/settingsare never read;isFolderRepoandremoteHostKindare short-circuited. What remains isrepos,worktreesByRepo,folderWorkspacesandprojectGroups— exactly the key. Graduate Agents activity view with filtering, persistence, and performance improvements #18222 did not change this, and the read set is now documented onDashboardWorkspaceStateso widening it flags the key.dashboardRowBucketProjectionreads only the row andacknowledgedAgentsByPaneKey[row.paneKey], so those two identities are the complete input. Keying on the ack slice rather than folding it into the row cache preserves main's property that an acknowledgement recounts without rebuilding any rows. Tallies are evicted in the same pass that evicts rows, so the map stays bounded.buildDashboardBucketCounts(state, now)) is unchanged, which is what makes it usable as the test oracle.Tests
build-dashboard-bucket-counts.equivalence.test.ts— an unmemoized reference walk composed from the same shared primitives, run against the memoized builder over 8 mutations x 5 clock steps, both independently and cumulatively through one shared cache.NOW,NOW + STALE + 1andNOW + STALE * 4but never exactlyNOW + STALE— the last instant an entry is fresh (now - observedAt <= STALE) and the only point where a cache hit, not a recompute, has to return a freshness verdict. That step is now in the matrix and has a dedicated case assertingworking: 1on a cache hit atNOW + STALEandworking: 0one millisecond later, so the case is not vacuous.build-dashboard-bucket-counts.allocation.test.ts— fails onmain: asserts 1 descriptor collection (400, not 2000) across 5 recomputes, 5 bucket projections instead of 2000, re-collection when each of the four keyed slices moves, and that an acknowledgement write still recounts every worktree without rebuilding a single row.useAgentBucketCounts.gate.test.ts— fails onmain: countsObject.entriescalls andMapconstructions across 2000 store writes for the gate (0 and 0) against an unwrappeduseShallowbaseline (4000 and 4000).agent-dashboard-performance-isolation.test.tsstill passes — no new eager import reaches the sidebar.Negative user-facing trade-offs
None.
agentStatusEpoch.resetAgentBucketCountStateForTestsexists for deterministic tests.Closes #18141.