Skip to content

perf(sidebar): stabilize worktree card props so cards memo-bail on order-preserving epoch bumps - #9392

Merged
nwparker merged 2 commits into
mainfrom
nwparker/perf-lineage-memo
Jul 21, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/perf-lineage-memo

Conversation

@nwparker

@nwparker nwparker commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

perf(sidebar): stable card props so WorktreeCards memo-bail on order-preserving epoch bumps

Description

WorktreeCard is wrapped in React.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 the WorktreeList.tsx call site got fresh identities on each parent render even when nothing visible changed:

  1. 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 a Map bounded by the number of lineage groups and is recreated only if toggleGroupWithScrollAnchor changes 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.
  2. selectedWorktrees, and transitively onSelectionGesture / onContextMenuSelect / onCardDragStart — these callbacks' dependency chains bottom out in visibleWorktrees → 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 existing reuseArrayIfEqual (now exported from worktree-agent-row-selectors.ts) wrapped in a small useReusedArrayIdentity hook, applied to the results of the existing useMemos for visibleWorktrees (outer component), renderedWorktreeIds, and selectedWorktrees (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 lineageChildren prop 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 real WorktreeList with a memo'd WorktreeCard mock instrumented with a render spy, re-renders the list after an order-preserving sortEpoch bump, and asserts the card render function is not invoked again.

  • Before (fix stashed): test FAILS — expected 4 to be 2, i.e. both cards re-rendered on the epoch bump.
  • After: test PASSES — zero additional card renders on the epoch bump.
  • Companion test proves the reverse: when a worktree's data actually changes, its card does re-render (identity reuse doesn't freeze real updates).
  • Referential-stability unit test for the lineage-toggle cache (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

  • Selection / drag / context-menu suites (the regression-sensitive areas for array identity reuse): 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.
  • Lineage suites: 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.)
  • WorktreeList pipeline suites: 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 🐋

@nwparker
nwparker marked this pull request as ready for review July 20, 2026 03:32
@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

WorktreeList 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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it misses several required template sections like Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes. Rewrite the PR description to follow the template and add Summary, Screenshots, Testing, AI Review Report with cross-platform checks, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main perf change: stabilizing worktree card props so memoized cards skip redundant re-renders.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 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.

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 win

Strengthen test 2 to also assert the unaffected sibling doesn't re-render.

This test confirms wt-a re-renders when its data changes, but doesn't verify wt-b (unchanged, alongside a sortEpoch bump) 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

📥 Commits

Reviewing files that changed from the base of the PR and between 927ca9e and bc876d0.

📒 Files selected for processing (5)
  • src/renderer/src/components/sidebar/WorktreeList.card-memo-stability.test.tsx
  • src/renderer/src/components/sidebar/WorktreeList.tsx
  • src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts
  • src/renderer/src/components/sidebar/worktree-lineage-toggle-handler-cache.test.ts
  • src/renderer/src/components/sidebar/worktree-lineage-toggle-handler-cache.ts

Comment on lines +317 to +328
// 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
}

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.

🩺 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.

Suggested change
// 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

@nwparker
nwparker force-pushed the nwparker/perf-lineage-memo branch from bc876d0 to 0e86081 Compare July 21, 2026 00:55
nwparker and others added 2 commits July 20, 2026 18:57
…ktrees so cards memo-bail on epoch bumps

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the nwparker/perf-lineage-memo branch from 0e86081 to 95dcc89 Compare July 21, 2026 01:57
@nwparker
nwparker merged commit 8182141 into main Jul 21, 2026
1 check passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
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