Repository navigation
perf(sidebar): stabilize worktree card props so cards memo-bail on order-preserving epoch bumps - #9392
Conversation
📝 WalkthroughWalkthroughWorktreeList now reuses array identities for unchanged derived worktree data and caches lineage toggle handlers by group key. The lineage handler cache preserves handler identity and delegates event behavior to the group toggle callback. New Vitest suites verify handler caching and event delegation, plus WorktreeCard memo behavior across unchanged sort epochs and worktree data updates. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 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
🧹 Nitpick comments (1)
src/renderer/src/components/sidebar/WorktreeList.card-memo-stability.test.tsx (1)
300-323: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winStrengthen test 2 to also assert the unaffected sibling doesn't re-render.
This test confirms
wt-are-renders when its data changes, but doesn't verifywt-b(unchanged, alongside asortEpochbump) stays stable. That's the exact "reuse array identity for unchanged elements" claim from the PR objective — asserting it here would directly validate it, complementing test 1's coarser same-state/no-op check.♻️ Proposed addition
// The changed card re-renders; identity reuse must not freeze real updates. expect(cardRenderSpy.mock.calls.length).toBeGreaterThan(countAfterMount) expect(cardRenderSpy).toHaveBeenCalledWith('wt-a') + // The unaffected sibling must not re-render: array identity reuse should + // still bail it out even though the sibling's own worktree object changed. + expect(cardRenderSpy).not.toHaveBeenCalledWith('wt-b') })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: d0aac01a-cbc5-4055-936a-c18b9f82bdc1
📒 Files selected for processing (5)
src/renderer/src/components/sidebar/WorktreeList.card-memo-stability.test.tsxsrc/renderer/src/components/sidebar/WorktreeList.tsxsrc/renderer/src/components/sidebar/worktree-agent-row-selectors.tssrc/renderer/src/components/sidebar/worktree-lineage-toggle-handler-cache.test.tssrc/renderer/src/components/sidebar/worktree-lineage-toggle-handler-cache.ts
| // Why: epoch-driven recomputes (agent status, sort) often produce arrays whose | ||
| // contents and order are unchanged. Reusing the previous identity when | ||
| // element-wise equal keeps downstream memos and React.memo'd cards bailing out. | ||
| // Safe because the elements (Worktree objects / id strings) are immutably | ||
| // REPLACED on any change — a `===`-equal element means the rendered data is | ||
| // unchanged. Do not use this to wrap arrays of mutated-in-place objects. | ||
| function useReusedArrayIdentity<T>(next: T[]): T[] { | ||
| const previousRef = useRef<T[]>(next) | ||
| const result = reuseArrayIfEqual(previousRef.current, next) | ||
| previousRef.current = result | ||
| return result | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Move ref mutation to an effect to support Concurrent React.
Mutating previousRef.current during render is an anti-pattern in React because React can pause, replay, or discard render work. If a render is discarded before committing, the ref mutation leaks an uncommitted array identity. A subsequent render would compare against this uncommitted array and potentially return its identity, defeating downstream React.memo boundaries which have only seen the previously committed array.
Move the ref update into a useEffect (or useLayoutEffect) so it only updates when the render is actually committed.
🐛 Proposed fix
function useReusedArrayIdentity<T>(next: T[]): T[] {
const previousRef = useRef<T[]>(next)
const result = reuseArrayIfEqual(previousRef.current, next)
- previousRef.current = result
+ useEffect(() => {
+ previousRef.current = result
+ }, [result])
return result
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Why: epoch-driven recomputes (agent status, sort) often produce arrays whose | |
| // contents and order are unchanged. Reusing the previous identity when | |
| // element-wise equal keeps downstream memos and React.memo'd cards bailing out. | |
| // Safe because the elements (Worktree objects / id strings) are immutably | |
| // REPLACED on any change — a `===`-equal element means the rendered data is | |
| // unchanged. Do not use this to wrap arrays of mutated-in-place objects. | |
| function useReusedArrayIdentity<T>(next: T[]): T[] { | |
| const previousRef = useRef<T[]>(next) | |
| const result = reuseArrayIfEqual(previousRef.current, next) | |
| previousRef.current = result | |
| return result | |
| } | |
| // Why: epoch-driven recomputes (agent status, sort) often produce arrays whose | |
| // contents and order are unchanged. Reusing the previous identity when | |
| // element-wise equal keeps downstream memos and React.memo'd cards bailing out. | |
| // Safe because the elements (Worktree objects / id strings) are immutably | |
| // REPLACED on any change — a `===`-equal element means the rendered data is | |
| // unchanged. Do not use this to wrap arrays of mutated-in-place objects. | |
| function useReusedArrayIdentity<T>(next: T[]): T[] { | |
| const previousRef = useRef<T[]>(next) | |
| const result = reuseArrayIfEqual(previousRef.current, next) | |
| useEffect(() => { | |
| previousRef.current = result | |
| }, [result]) | |
| return result | |
| } |
🧰 Tools
🪛 React Doctor (0.7.6)
[error] 326-326: This ref is mutated during render. React can replay or discard render work, so the mutation can leak from UI that never commits.
Move ref writes into an event handler or effect. Render must stay pure because React can replay or discard it. The predictable null-guarded lazy initialization pattern remains supported.
(no-ref-current-in-render)
Source: Linters/SAST tools
bc876d0 to
0e86081
Compare
…arent WorktreeCards memo-bail Co-authored-by: Orca <[email protected]>
…ktrees so cards memo-bail on epoch bumps Co-authored-by: Orca <[email protected]>
0e86081 to
95dcc89
Compare
…der-preserving epoch bumps (stablyai#9392) * perf(sidebar): stable per-group onLineageToggle identity so lineage-parent WorktreeCards memo-bail Co-authored-by: Orca <[email protected]> * perf(sidebar): reuse array identity for visible/rendered/selected worktrees so cards memo-bail on epoch bumps Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
perf(sidebar): stable card props so WorktreeCards memo-bail on order-preserving epoch bumps
Description
WorktreeCardis wrapped inReact.memo, but on every agent-status/sort epoch bump (which fires repeatedly while agents cycle turn states) every card re-rendered anyway, because several props handed to it at theWorktreeList.tsxcall site got fresh identities on each parent render even when nothing visible changed:onLineageToggle— built as a fresh inline arrow per row per render. Fixed with a per-group-key handler cache (worktree-lineage-toggle-handler-cache.ts): the same lineage group key now returns the same handler instance across renders. The cache is aMapbounded by the number of lineage groups and is recreated only iftoggleGroupWithScrollAnchorchanges identity (it doesn't — it and its deps are stable useCallbacks/store actions). Handler behavior is identical:preventDefault(),stopPropagation(),toggleGroupWithScrollAnchor(groupKey)with scroll anchoring preserved.selectedWorktrees, and transitivelyonSelectionGesture/onContextMenuSelect/onCardDragStart— these callbacks' dependency chains bottom out invisibleWorktrees→rows/sectionRows→renderedWorktreeIds/selectedWorktrees, all of which were rebuilt as new arrays on every epoch bump even when membership and order were unchanged. Fixed by reusing the previous array identity when the recomputed array is element-wise identical (same length, same elements, same order — exact===per element, no approximate compare). This uses the codebase's existingreuseArrayIfEqual(now exported fromworktree-agent-row-selectors.ts) wrapped in a smalluseReusedArrayIdentityhook, applied to the results of the existing useMemos forvisibleWorktrees(outer component),renderedWorktreeIds, andselectedWorktrees(viewport component). When contents differ in any way the fresh array is returned, so selection/drag/context-menu always operate on current data.With those stable, collapsed worktree cards pass the memo shallow-compare and skip re-render on order-preserving epoch bumps. Known remainder (intentionally out of scope): expanded lineage-parent cards still re-render because their
lineageChildrenprop is a freshly built React element array each render — a smaller, separate issue.Evidence
Render-count proof in
WorktreeList.card-memo-stability.test.tsx: mounts the realWorktreeListwith a memo'dWorktreeCardmock instrumented with a render spy, re-renders the list after an order-preservingsortEpochbump, and asserts the card render function is not invoked again.expected 4 to be 2, i.e. both cards re-rendered on the epoch bump.worktree-lineage-toggle-handler-cache.test.ts): same key ⇒ same handler instance, different key ⇒ different instance, and invoking calls preventDefault/stopPropagation + toggle with the bound key.No-Regression Proof
worktree-multi-selection,worktree-drag-units,worktree-lineage-drag-drop,worktree-sidebar-drag-autoscroll,worktree-sidebar-drop-preview,worktree-sidebar-pointer-drag-dom,WorktreeContextMenu,worktree-agent-row-selectors,worktree-card-dom-events— all pass.WorktreeCard.lineage,WorktreeList.lineage-agent-expansion-coupling,WorktreeList.lineage-child-card,WorktreeList.lineage-child-real-card,workspace-delete-lineage— all pass. (16 files, 137 tests in this batch.)worktree-list-virtual-rows,worktree-list-groups,worktree-list-scroll-adjustment,worktree-list-sticky-headers,worktree-list-indentation,worktree-list-folder-reveal,worktree-list-host-filtering,worktree-list-imported-rows,worktree-list-review-cache-inputs,worktree-list-visible-refresh,visible-worktrees,worktree-manual-order— 12 files, 238 tests, all pass.pnpm run typecheck:web— clean. Changed files formatted with oxfmt; pre-commit oxlint clean.ELI5
Every few seconds the app pokes the sidebar to say "an agent's status changed — maybe re-sort." Even when nothing actually moved, the sidebar rebuilt its internal lists from scratch, and React saw "new lists = new props" and redrew every workspace card for nothing. Now, when a rebuilt list comes out identical to the old one, we hand React the old one back, so it can tell nothing changed and skip the redraw. Anything that really changes still redraws exactly as before.
Made with Orca 🐋