Skip to content

perf(sidebar): stop recounting every workspace's agents for four sidebar numbers - #18141

Closed
nwparker wants to merge 1 commit into
mainfrom
perf/sidebar-agent-bucket-counts
Closed

nwparker wants to merge 1 commit into
mainfrom
perf/sidebar-agent-bucket-counts

Conversation

@nwparker

@nwparker nwparker commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

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

useDiffCommentDecorator memoized commentableLineSet on the identity of the commentableLineNumbers array:

const commentableLineSet = useMemo(
  () => (commentableLineNumbers ? new Set(commentableLineNumbers) : null),
  [commentableLineNumbers]
)

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 -> new Set -> 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 called accessor.removeZone. The effect that actually creates zones does not depend on commentableLineSet, 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.tsx does not pass getCommentableLineNumbers, so the set is null and stable.

The fix

  1. Memoize on the values, not the array identity (commentableLineNumbers?.join(',')). This kills the churn at the root and follows the existing house pattern in combined-diff-viewer.tsx (diffEntrySignature).
  2. Split the effect. commentableLineSet does not belong on the zone-teardown effect — but it cannot simply be dropped, because installDiffCommentAddButtonOverlay closes 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.
  3. The missing accessor.removeZone was a second, real bug, latent even after the memo fix. The cleanup clears zonesRef, 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 in monaco-editor: ViewZones._removeZone is guarded by hasOwnProperty (no-op for an id Monaco already dropped on model swap), and CodeEditorWidget.changeViewZones early-returns when _modelData is null (no-op on a disposed editor).

Measurements

Real numbers from the new regression suite (useDiffCommentDecorator.commentable-lines.test.tsx), same test run against unmodified main and against this branch.

Scenario A — 5 refreshes shipping value-equal line numbers, fixed set of 3 review notes:

createRoot calls root unmounts Monaco view zones orphaned (blank) zones
before 3 3 3 3
after 3 0 3 0

All 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):

createRoot calls root unmounts Monaco view zones orphaned (blank) zones
before 21 15 21 15
after 6 0 6 0

Scenario C — model swap under a retained editor: before, 2 view zones for 1 comment (1 stranded); after, 1.

Failing assertions on unmodified code

× keeps every comment root and view zone alive across value-equal review refreshes
AssertionError: expected { createRootCalls: 3, …(2) } to deeply equal { createRootCalls: 3, …(2) }
    "createRootCalls": 3,
    "monacoViewZones": 3,
-   "rootUnmounts": 0,
+   "rootUnmounts": 3,

× does not accumulate orphan zones when refreshes interleave with new review comments
AssertionError: expected { createRootCalls: 21, …(2) } to deeply equal { createRootCalls: 6, …(2) }
-   "createRootCalls": 6,
-   "monacoViewZones": 6,
-   "rootUnmounts": 0,
+   "createRootCalls": 21,
+   "monacoViewZones": 21,
+   "rootUnmounts": 15,

× rebuilds the add-button overlay when the commentable lines really change
AssertionError: expected { createRootCalls: 1, …(2) } to deeply equal { createRootCalls: 1, …(2) }
    "createRootCalls": 1,
    "monacoViewZones": 1,
-   "rootUnmounts": 0,
+   "rootUnmounts": 1,

× removes its zones from Monaco when the model swaps under a retained editor
AssertionError: expected 2 to be 1 // Object.is equality

All 4 fail on main, all 4 pass on this branch.

Tests

New src/renderer/src/components/diff-comments/useDiffCommentDecorator.commentable-lines.test.tsx drives the hook against a fake Monaco editor with a real view-zone registry and a createRoot counter scoped to zone containers:

  • value-equal refreshes: no extra createRoot, no unmounts, constant zone count, and a subsequent comment deletion still reclaims the zone (proving the zones stayed tracked, not just present)
  • refreshes interleaved with new comments: no orphan accumulation
  • a genuine change to the commentable line set is not made stale — widening [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 orphaned
  • model swap under a retained editor removes the stale zone ids

Provider 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 pass getCommentableLineNumbers yet, 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 createRoot calls. 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 — clean
  • npx oxlint <changed files> — clean
  • npx 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 passed
  • npx 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 in WorktreeCard.* / WorktreeList.lineage-* plus two dashboard-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.tsx has only a type-only DashboardAgentRow import, and no file under sidebar/ or dashboard-popout/ reaches useAgentBucketCounts / build-dashboard-bucket-counts / dashboard-worktree-bucket-counts.
  • The new scaling assertions were confirmed to fail without the fix (per-worktree gate disabled): expected 193 to be 1 for the ping case, expected 193 to be 1 for the pane-title case, and expected 193 to be +0 for the re-derive case.

…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.
@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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 fec0c

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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 l… Rewrite the description to match the dashboard performance changes. Complete the required template sections, add a linked issue after Fixes #, and mark Visual Proof as N/A with a reason if there is no UI change.
Linked Issues check ⚠️ Warning The required Linked Issue section contains only Fixes # and does not identify an issue. Add the complete issue reference in the required Fixes #<issue-number> format.
✅ Passed checks (2 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed 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 performan…
Title check ✅ Passed The title clearly describes the main change: it prevents repeated recounting of workspace agents for sidebar bucket counts. It is concise and specific.
Full details: Description check

Explanation

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 check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/renderer/src/components/dashboard/dashboard-worktree-bucket-counts.ts (1)

83-88: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename liveEntriesThisPass to 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. endWorktreeBucketCountPass compares it against cacheByWorktreeId.size to 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

📥 Commits

Reviewing files that changed from the base of the PR and between f37d2fe and fec0c8e.

📒 Files selected for processing (5)
  • src/renderer/src/components/dashboard/build-dashboard-bucket-counts.test.ts
  • src/renderer/src/components/dashboard/build-dashboard-bucket-counts.ts
  • src/renderer/src/components/dashboard/dashboard-worktree-bucket-counts.ts
  • src/renderer/src/components/dashboard/useAgentBucketCounts.test.tsx
  • src/renderer/src/components/dashboard/useAgentBucketCounts.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ts memoizes each workspace's attention/working/done/idle contribution on its own input identities (tabs, live/migration/retained entry arrays, orchestration, acknowledgements, per-tab layout/title/pty values) plus a validUntil freshness boundary, so an agent ping re-walks only the owning worktree.
  • Active-workspace descriptor cache — build-dashboard-bucket-counts.ts reuses the collected workspace descriptors until repos/worktreesByRepo/folderWorkspaces/projectGroups change identity.
  • Stable selector identity — useAgentBucketCounts.ts replaces useShallow + useMemo with a module-scoped gate and countsEqual, 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 a buildWorktreeAgentRows spy.

⚠️ 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

  • nextFreshnessBoundary iterates all entries including done entries, which never decay (shouldDecay only fires for working/blocked/waiting). A recently-finished done entry therefore drags validUntil earlier than the true first decay, causing an occasional no-op rebuild. Skipping non-decayable states would tighten the boundary.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Re-measured against current main — still additive, but needs a redesign, not a rebase

main has moved. 61e010079f7 (New agent dashboard, #18222) added worktree-agent-rows-cache.ts and rewired buildDashboardBucketCounts to take a per-hook cache plus an agentStatusEpoch generation token. That attacks the same walk this PR attacks, so the "before" numbers in this PR body are no longer a valid baseline.

I re-benchmarked this branch's implementation against current main at this PR's own fixture scale (10 repos / 423 worktrees / 193 with tabs / 382 tabs). Deterministic operation counts, because wall-clock on a loaded machine swung 5x between runs and at one point inverted the result:

Scenario A — ordinary agent status ping (agentStatusEpoch unchanged; the dominant idle-app traffic)

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:

  1. Layer a counts memo on top of selectWorktreeAgentRowsCached. Recovers the 423 descriptors and 381 of 383 projections; does not recover the epoch-bump win, because main's rows cache still invalidates wholesale on generation.
  2. Same, plus hoist the activeWorkspacesCache memo, which is independent of either cache design and is a clean standalone change.
  3. Move this branch's per-worktree validUntil freshness boundary into worktree-agent-rows-cache.ts, replacing the coarse generation token. 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 validUntil math is correct and errs conservative. isExplicitAgentStatusFresh is now - observedAt <= STALE; validUntil is the minimum future observedAt + STALE; the gate is now >= computedAt && now <= validUntil. The dangerous direction — validUntil too large, which would show a stale agent count — is not reachable. done entries and restoredUnconfirmed entries are handled conservatively (extra rebuilds, never a stale count).
  • I traced every clock consumer in the row pipeline: only worktree-agent-rows.ts:176 and :221 read now in a way that can move a bucket. Title-derived rows stamp updatedAt: now but carry startedAt: 0, which dashboardRowBucketProjection short-circuits, so they cannot.
  • activeWorkspacesCache's four-slice key is exactly right: with includeMapMetadata: false, collectActiveDashboardWorkspaces provably reads only repos, worktreesByRepo, folderWorkspaces, projectGroups.

Two things to fix whichever route is taken:

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Invariants for whoever owns the dashboard bucket cache next

Recording these from the readiness review of this branch so they survive it being closed. They apply to main's worktree-agent-rows-cache.ts as much as to this branch's dashboard-worktree-bucket-counts.ts — any cache in this area keyed on time-based freshness depends on all four.

1. startedAt: 0 on title-derived rows is load-bearing (the landmine)

buildTitleDerivedAgentRow (worktree-title-derived-agent-rows.ts) stamps updatedAt, stateStartedAt, and observation.revision/observedAt from args.now. Those look freshness-dependent, and a reader could reasonably conclude a title-derived row decays with the clock.

It does not — solely because the row carries startedAt: 0, which makes dashboardRowBucketProjection set isTitleDerived and short-circuit unseen.

Give title-derived rows a real timestamp and every freshness-boundary-keyed cache in this area starts serving stale counts, with no test failing at the point of the change. main's coarse generation token happens to survive it; a computed validUntil boundary does not. Now recorded as a code comment in #18240.

2. A counts memo must key on acknowledgedAgentsByPaneKey

main deliberately re-counts over the (reused) rows on every call, so acknowledging an agent recounts without rebuilding any rows. Anyone layering a counts memo on top of selectWorktreeAgentRowsCached must put acknowledgedAgentsByPaneKey in its key — this branch's cache entry did. Omitting it shows stale unseen/attention counts after the user acknowledges an agent, which is exactly the "sidebar lies about agent state" failure the cache is supposed to avoid.

3. Only two call sites read the clock in a bucket-affecting way

worktree-agent-rows.ts:176 and :221, both via isExplicitAgentStatusFresh. applyAgentRowLineage, dashboardRowBucketProjection, markCompletedWorkerParentPaneKeysSeen, resolveDecayedAgentRowState and effectiveWorktreeAgentRowStartedAt contain no Date.now() at all. That is what makes a computed freshness boundary a complete invalidation key rather than a guess — and it is worth re-checking if any of those grow a clock read.

Two related subtleties:

  • done entries contribute a freshness boundary even though shouldDecay excludes done, so they cause extra rebuilds but never a wrong count. Safe to optimise away — but only while subagent rows stay excluded from counts (rowSource === 'subagent' continue). If subagent rows ever start counting, buildSubagentChildRows({ parentIsFresh }) makes parent freshness bucket-relevant and that shortcut breaks.
  • restoredUnconfirmed entries are never fresh at any clock reading, so they have no future transition and are correctly skipped.

4. Per-worktree selector completeness

selectRuntimePaneTitlesForWorktree, selectLivePtyIdsForWorktree and selectTerminalLayoutsForWorktree derive purely from tabsByWorktree[worktreeId] plus per-tab lookups into terminalLayoutsByTabId / runtimePaneTitlesByTabId / ptyIdsByTabId. That is the reason comparing those three maps per tab is a complete invalidation key. If any of them ever reads a fourth slice, every cache in this area under-invalidates — main's shallowRecordEqual comparison and this branch's index-aligned comparison alike.

One non-obvious consequence: getLiveEntriesByWorktree attributes agent-session tabs via unifiedTabsByWorktree, so a worktree's liveEntries can contain entries whose tab is not in tabsByWorktree[worktreeId]. Those fall through to the "orchestration worker attributed before its tab arrives" branch in buildWorktreeAgentRows. Pre-existing and identical in both designs, but it surprises you when reasoning about what a cache key has to cover.

5. Test gap, if the validUntil approach is ever revived

The equivalence matrix in build-dashboard-bucket-counts.test.ts covers NOW, NOW + STALE + 1 and NOW + STALE * 4, but never exactly NOW + STALE — the last instant at which an entry is still fresh, and the only point where a cache hit returns a freshness verdict rather than recomputing one. Correct as written (the gate is now <= validUntil and isExplicitAgentStatusFresh is now - observedAt <= STALE, so both agree at the boundary), but untested.

@nwparker

nwparker commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Closing as superseded, with the still-valid parts re-landed in #18241.

Why

61e010079f7 ("New agent dashboard", #18222) landed worktree-agent-rows-cache.ts and rewired buildDashboardBucketCounts to take a per-hook cacheRef plus an agentStatusEpoch generation token. That attacks the same walk this PR attacks, but with the opposite invalidation model: main caches rows per worktree and recounts buckets on every call (so acknowledgement changes are free), while this PR caches counts per worktree keyed on a computed validUntil clock boundary with acknowledgedAgentsByPaneKey in the key. The two do not merge — git rebase origin/main conflicts semantically in both build-dashboard-bucket-counts.ts and useAgentBucketCounts.ts. Main's design is the one that stayed.

What was salvaged into #18241

Route (2) from #18141 (comment), layered onto main's row cache rather than replacing it:

  • the activeWorkspacesCache descriptor memo, with its four-slice key re-verified against current main;
  • a per-worktree bucket-tally memo keyed on (rows identity, acknowledgedAgentsByPaneKey identity), which recovers the projection win without reintroducing a clock-keyed count cache;
  • the module-level 14-identity gate replacing the useShallow selector;
  • countsEqual identity reuse of the returned counts object.

Re-measured against main at this PR's own fixture scale: 423 → 0 workspace descriptors and 193 → 1 bucket projections per ordinary agent ping (0.33 ms → 0.24 ms), and 1122 ns → 10 ns per store write for the selector.

The NOW + STALE boundary gap, for whoever owns the dashboard cache

This PR's equivalence matrix covered NOW, NOW + STALE + 1 and NOW + STALE * 4 but never exactly NOW + STALE. That is the last instant an entry is still fresh — isExplicitAgentStatusFresh is now - observedAt <= STALE, inclusive — and it is the only point where a cache hit, rather than a recompute, has to return a freshness verdict. The behaviour was correct here and is correct on main; it was simply untested. #18241 adds it to the matrix with a dedicated non-vacuous case (working: 1 on a cache hit at NOW + STALE, working: 0 one millisecond later).

Any future change to the row cache's invalidation token needs that case. It is the boundary a coarse generation token cannot express, and the reason the validUntil idea below is worth revisiting.

What was deliberately not salvaged

The epoch-bump win. agentStatusEpoch is a coarse token: main's rows cache discards every worktree's rows when it moves, and the epoch bumps on retention-relevant changes, migration changes, orphan eviction, and the freshness scheduler's stale-boundary tick. Measured at 423 row-pipeline recomputes per call on main versus ~1 on this branch — the single biggest number in the comparison.

Recovering it means moving this PR's per-worktree validUntil boundary into worktree-agent-rows-cache.ts, which has three other consumers (build-dashboard-snapshot.ts, useDashboardPopoutBridge.ts, useLiveDashboardSnapshot.ts). #18241's description carries a costed assessment of that work — what it would touch, what has to hold for it to be safe, and the measured prize — so it stays a decision rather than a lost idea.

Note on this PR's body

It was #18142's body verbatim (diff-comment decorator text on a sidebar-counts PR) and the numbers in it predate #18222, so they were never a valid baseline for this change. Rather than rewrite it to describe an implementation that is not landing, this comment records what the PR actually did and where each piece went.

@nwparker nwparker closed this Sep 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant