Repository navigation
Conversation
…bar numbers The always-mounted agent bucket counts re-walked every active worktree, tab and pane on any of 14 store slices moving — and several of those move on ordinary agent traffic. Memoize each worktree's contribution on its own input identities, cache the active-workspace list, and replace the 14-key useShallow gate (which allocates two Object.entries arrays and two Maps per store write inside zustand's shallow) with an allocation-free identity check. Row buckets read the clock only through isExplicitAgentStatusFresh, so each cached contribution carries validUntil = min(evidenceObservedAt + AGENT_STATUS_STALE_AFTER_MS) over its entries — the same boundary the store's freshness scheduler bumps agentStatusEpoch on — and is reused only inside that interval. Counts and idle-decay timing are unchanged.
📝 WalkthroughWalkthroughThe change adds memoized dashboard bucket counting at the worktree level. It caches active workspace selection and per-worktree counts using state identities, tab inputs, acknowledgements, orchestration, and freshness boundaries. The dashboard builder aggregates cached worktree results. The hook caches selector inputs and reuses the previous counts object when totals remain unchanged. Tests cover scaling, state mutations, stale boundaries, cache resets, and equivalence with the previous implementation. Merge Risk: 🔵 Low · up to The PR adds renderer-side caching to avoid rebuilding dashboard agent counts, improving startup and sidebar performance. A bounded lifecycle issue may retain removed worktree data longer than intended, so it is mergeable with explicit owner awareness and follow-up to make cache cleanup track distinct worktree identities and guaranteed pass completion. 🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
Full details: Description checkExplanation The description is largely off-topic. It describes a diff-comment decorator fix, while this pull request changes dashboard bucket-count memoization and agent-count selector caching. It also omits or leaves incomplete several required template sections, including What Changed, Why, Linked Issue, Visual Proof, Review, Notes, and Checklist. Full details: Out of Scope Changes checkExplanation The listed file changes are focused on dashboard bucket-count memoization, active-workspace caching, and allocation-free selector updates. These changes match the stated sidebar and renderer performance objective. No unrelated file changes are listed.
✨ 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.
🧹 Nitpick comments (1)
src/renderer/src/components/dashboard/dashboard-worktree-bucket-counts.ts (1)
83-88: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename
liveEntriesThisPassto describe the touched-worktree count.The counter is incremented once per worktree that the pass touched, on both the cache-hit path and the rebuild path. It does not count live agent entries.
endWorktreeBucketCountPasscompares it againstcacheByWorktreeId.sizeto detect worktrees that disappeared, so the name works against the reader of that comparison.Also applies to: 215-215, 265-265
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 2538f40a-f91a-4a14-b21c-d91dd0b0c9e5
📒 Files selected for processing (5)
src/renderer/src/components/dashboard/build-dashboard-bucket-counts.test.tssrc/renderer/src/components/dashboard/build-dashboard-bucket-counts.tssrc/renderer/src/components/dashboard/dashboard-worktree-bucket-counts.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; 1 remains after this review.
There was a problem hiding this comment.
Important
The PR body does not describe this change. The ELI5, measurements, "corrections to the brief", and guard-test sections all describe a Markdown lazy-loading + emoji-catalog change (react-markdown / CommentMarkdown / WorktreeCardMeta / bundle chunks). The actual diff is a per-worktree memoization of the four sidebar bucket counts. Please replace the body before merge — as written it misleads reviewers and pollutes the commit history.
Reviewed changes
- Per-worktree bucket-count cache — the new
dashboard-worktree-bucket-counts.tsmemoizes each workspace'sattention/working/done/idlecontribution on its own input identities (tabs, live/migration/retained entry arrays, orchestration, acknowledgements, per-tab layout/title/pty values) plus avalidUntilfreshness boundary, so an agent ping re-walks only the owning worktree. - Active-workspace descriptor cache —
build-dashboard-bucket-counts.tsreuses the collected workspace descriptors untilrepos/worktreesByRepo/folderWorkspaces/projectGroupschange identity. - Stable selector identity —
useAgentBucketCounts.tsreplacesuseShallow+useMemowith a module-scoped gate andcountsEqual, keeping the returned object reference-equal across pings that leave totals unchanged. - Oracle + scaling tests — a byte-for-byte pre-memo port (
referenceBucketCounts) checked across a state matrix (cold + warm), and walk-count assertions via abuildWorktreeAgentRowsspy.
⚠️ PR description describes an unrelated change
Every section of the body except the title (ELI5, measurements table, "Corrections to the brief", "Guard tests", "Explicitly not attempted") concerns Markdown/emoji lazy-loading and has no counterpart in this diff. The diff's actual files are build-dashboard-bucket-counts.ts, dashboard-worktree-bucket-counts.ts, useAgentBucketCounts.ts and their tests. This looks like a stale body pasted from a sibling PR. Rewrite it to describe the bucket-count memoization (what it caches, why the input identities are safe, and what the guard tests actually assert), or reviewers and future archaeologists will misread what this commit does.
The memoization logic itself is sound: the cache keys are the exact identities buildWorktreeAgentRows + dashboardRowBucketProjection consume, the freshness boundary (evidenceObservedAt + STALE) matches isExplicitAgentStatusFresh's <= window exactly, and the endWorktreeBucketCountPass eviction correctly drops the map when a cached worktree leaves the active set. The referenceBucketCounts oracle gives real regression coverage rather than a self-referential snapshot.
ℹ️ Nitpicks
nextFreshnessBoundaryiterates all entries includingdoneentries, which never decay (shouldDecayonly fires forworking/blocked/waiting). A recently-finisheddoneentry therefore dragsvalidUntilearlier than the true first decay, causing an occasional no-op rebuild. Skipping non-decayable states would tighten the boundary.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Re-measured against current
|
| per call | main |
this branch |
|---|---|---|
| row-pipeline recomputes | 1.0 | 1.0 |
| bucket projections | 383 | 2 |
| workspace descriptors allocated | 423 | 0 |
| best-of-12 wall time | 0.50 ms | 0.08 ms |
Scenario B — retention-relevant change on one pane (agentStatusEpoch bumps)
| per call | main |
this branch |
|---|---|---|
| row-pipeline recomputes | 418.8 | 0.99 |
| bucket projections | 383 | 2 |
| workspace descriptors allocated | 423 | 0 |
| best-of-12 wall time | 1.16 ms | 0.11 ms |
(418.8 is "all 423, every call": over 100 calls the first was a cache hit and the other 99 recomputed all 423.)
Separately, the useShallow → module-gate change is worth ~1.2 µs per store write (0.0014 ms → 0.0002 ms best-of-8), which is real but small.
So main fixed the row pipeline for the ordinary-ping case only. It still allocates 423 workspace descriptors and runs 383 bucket projections on every call, and it throws away its entire cache on every epoch bump. This branch avoids all three. It is not redundant.
Why this is not a mechanical rebase
main's worktree-agent-rows-cache.ts has three other consumers — build-dashboard-snapshot.ts, useDashboardPopoutBridge.ts, useLiveDashboardSnapshot.ts — so it has to stay. This branch's dashboard-worktree-bucket-counts.ts is a replacement for it on the counts path, not a layer, which is why git rebase origin/main conflicts semantically in both build-dashboard-bucket-counts.ts and useAgentBucketCounts.ts.
Three ways forward, in increasing order of value and effort:
- Layer a counts memo on top of
selectWorktreeAgentRowsCached. Recovers the 423 descriptors and 381 of 383 projections; does not recover the epoch-bump win, becausemain's rows cache still invalidates wholesale ongeneration. - Same, plus hoist the
activeWorkspacesCachememo, which is independent of either cache design and is a clean standalone change. - Move this branch's per-worktree
validUntilfreshness boundary intoworktree-agent-rows-cache.ts, replacing the coarsegenerationtoken. This recovers everything and also speeds up the pop-out dashboard, but it changes shared code with three consumers.
(3) is the right end state. It is a redesign of code that landed after this branch was written, so it should be the author's call, not a merge-conflict resolution.
Review notes on the current implementation, which still hold
I verified the cache logic before finding the collision, and it is sound:
build-dashboard-bucket-counts.test.ts's oracle is a faithful port of the removed loop.- The
validUntilmath is correct and errs conservative.isExplicitAgentStatusFreshisnow - observedAt <= STALE;validUntilis the minimum futureobservedAt + STALE; the gate isnow >= computedAt && now <= validUntil. The dangerous direction —validUntiltoo large, which would show a stale agent count — is not reachable.doneentries andrestoredUnconfirmedentries are handled conservatively (extra rebuilds, never a stale count). - I traced every clock consumer in the row pipeline: only
worktree-agent-rows.ts:176and:221readnowin a way that can move a bucket. Title-derived rows stampupdatedAt: nowbut carrystartedAt: 0, whichdashboardRowBucketProjectionshort-circuits, so they cannot. activeWorkspacesCache's four-slice key is exactly right: withincludeMapMetadata: false,collectActiveDashboardWorkspacesprovably reads onlyrepos,worktreesByRepo,folderWorkspaces,projectGroups.
Two things to fix whichever route is taken:
- The PR body is fix(diff-comments): stop review refreshes from blanking inline comment cards #18142's body verbatim — it describes the diff-comment decorator, not sidebar bucket counts.
- The equivalence matrix covers
NOW,NOW + STALE + 1andNOW + STALE * 4, but never exactlyNOW + STALE— the last-fresh instant, and the only point where a cache hit returns a freshness verdict. Correct today, untested.
Invariants for whoever owns the dashboard bucket cache nextRecording these from the readiness review of this branch so they survive it being closed. They apply to 1.
|
|
Closing as superseded, with the still-valid parts re-landed in #18241. Why
What was salvaged into #18241Route (2) from #18141 (comment), layered onto main's row cache rather than replacing it:
Re-measured against The
|

ELI5
Every time Orca refreshed a pull request, it deleted the contents of every inline comment box in the diff but left the empty boxes behind — so you got blank gaps where your review comments used to be. Then it did it again on the next refresh, stacking up more blank gaps.
What was wrong
useDiffCommentDecoratormemoizedcommentableLineSeton the identity of thecommentableLineNumbersarray:On review surfaces that array is
fileByPath.get(path)?.reviewCommentLineNumbers(pull-request-page/files/combined-diff-viewer.tsx:362,github-item-dialog/inspect-pull-request/pr-files-combined-diff-body.tsx:154). It is rebuilt fresh in the main process on every fetch (src/main/github/pull-request-file-data.ts:148) and shipped over IPC, and the renderer never value-compares it. So an identical set of line numbers still produced a new array -> newSet-> new dep.That dep sat on the effect that owns both the add-button overlay and the view-zone teardown. Its cleanup unmounted every comment card's React root and emptied
zonesRef, but never calledaccessor.removeZone. The effect that actually creates zones does not depend oncommentableLineSet, so it never re-ran. Net result per refresh: Monaco still holds the view zones (still consuming vertical space), they are now blank, untracked, unremovable, and never re-rendered. If new review comments arrived between refreshes, the now-empty map made the create-effect rebuild zones for every comment on top of the stranded ones — quadratic accumulation.Local worktree diffs were unaffected:
CombinedDiffViewer.tsxdoes not passgetCommentableLineNumbers, so the set isnulland stable.The fix
commentableLineNumbers?.join(',')). This kills the churn at the root and follows the existing house pattern incombined-diff-viewer.tsx(diffEntrySignature).commentableLineSetdoes not belong on the zone-teardown effect — but it cannot simply be dropped, becauseinstallDiffCommentAddButtonOverlaycloses over the set by value and would go stale (the "+" button would keep offering the old commentable lines). So the overlay moved into its own effect ([addButtonLabel, commentableLineSet, editor, monacoModelIdentity]) and the teardown kept only[cancelScrollToZoneFrame, editor, monacoModelIdentity]. The teardown's deps are now a strict subset of the zone-creating effect's, which is the invariant that was missing: a teardown is now always followed by a rebuild.accessor.removeZonewas a second, real bug, latent even after the memo fix. The cleanup clearszonesRef, so anything left in Monaco is unreachable by definition. It still fires on a genuine model swap under a retained editor, and on any future dep added to that effect. Verified safe inmonaco-editor:ViewZones._removeZoneis guarded byhasOwnProperty(no-op for an id Monaco already dropped on model swap), andCodeEditorWidget.changeViewZonesearly-returns when_modelDatais null (no-op on a disposed editor).Measurements
Real numbers from the new regression suite (
useDiffCommentDecorator.commentable-lines.test.tsx), same test run against unmodifiedmainand against this branch.Scenario A — 5 refreshes shipping value-equal line numbers, fixed set of 3 review notes:
createRootcallsAll three cards were destroyed; all three zones survived as blank gaps.
Scenario B — 5 refreshes, each also bringing one new review comment (6 notes live at the end):
createRootcallsScenario C — model swap under a retained editor: before, 2 view zones for 1 comment (1 stranded); after, 1.
Failing assertions on unmodified code
All 4 fail on
main, all 4 pass on this branch.Tests
New
src/renderer/src/components/diff-comments/useDiffCommentDecorator.commentable-lines.test.tsxdrives the hook against a fake Monaco editor with a real view-zone registry and acreateRootcounter scoped to zone containers:createRoot, no unmounts, constant zone count, and a subsequent comment deletion still reclaims the zone (proving the zones stayed tracked, not just present)[10,11,12]to[10,11,12,40]makes the "+" button appear on line 40, while the existing note's zone and React root are neither rebuilt nor orphanedProvider coverage
The fix lives in the provider-generic decorator hook, so any review surface inherits it. Today only the GitHub path populates
reviewCommentLineNumbers(src/main/github/pull-request-file-data.ts); GitLab / Bitbucket / Azure DevOps MR views do not passgetCommentableLineNumbersyet, so they cannot hit the bug today and will be safe when they do. Naming and comments in the changed code say "PR/MR" rather than GitHub-specific terms.Negative user-facing trade-offs
None. This is a strict improvement: it fixes visible blank gaps in the reviewed diff and stops inline comment cards from being wiped on every PR refresh. It also does strictly less work — fewer React root teardowns and, in the interleaved case, 21 -> 6
createRootcalls. The only behavior that can now differ is a genuine model swap, where stale view zones are removed instead of being left behind; the zone-creating effect re-runs on the same dep and rebuilds them, which the model-swap test asserts.Verification
pnpm tc— cleannpx oxlint <changed files>— cleannpx vitest run --config config/vitest.config.ts src/renderer/src/components/diff-comments src/renderer/src/components/pull-request-page src/renderer/src/components/github-item-dialog— 12 files, 64 tests passednpx vitest run --config config/vitest.config.ts src/renderer/src/components/editor— 192 files, 1295 tests passed (the hook's two consumers live there)Verification
pnpm tc— clean.npx oxlint src/renderer/src/components/dashboard/— clean.npx vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard src/renderer/src/components/sidebar— 2884 passed. The 7 remaining failures are all 20s/30s test-or-hook timeouts inWorktreeCard.*/WorktreeList.lineage-*plus twodashboard-popout/AgentMap*cases; they reproduce in isolation on this machine (which was running ~10 parallel agent test runs) and none of those files import anything from the changed modules —WorktreeCard.compact-hover.test.tsxhas only a type-onlyDashboardAgentRowimport, and no file undersidebar/ordashboard-popout/reachesuseAgentBucketCounts/build-dashboard-bucket-counts/dashboard-worktree-bucket-counts.expected 193 to be 1for the ping case,expected 193 to be 1for the pane-title case, andexpected 193 to be +0for the re-derive case.