Skip to content

Fix: settle sortEpoch in store to prevent React update depth exceeded - #25313

Merged
AmethystLiang merged 6 commits into
mainfrom
fix-185-settled-sort-epoch
Oct 4, 2026
Merged

AmethystLiang merged 6 commits into
mainfrom
fix-185-settled-sort-epoch

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​507 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​507
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​151 $\color{#cf222e}{\Huge{\mathbf{−}}}$​58 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​93

Problem

When workspaces are reordered via drag-and-drop, the app triggers many rapid sortEpoch bumps. The sidebar component was mirroring this into React state with an effect, creating nested updates that exceeded React's maximum update depth and crashed with "Maximum update depth exceeded" (issue #185).

Solution

Move the sortEpoch settling logic from a React effect in the sidebar component to a store listener that runs once per state change. The store now tracks settledSortEpoch — the epoch value the sidebar sort actually reads.

Settling rules:

  • 3-second debounce for time-decaying sorts (smart/recent/name) so background score changes don't jar row positions
  • Immediate settle for Manual sort (direct manipulation), structural changes (adds/removes), and sort mode switches
  • Store listener runs before hook subscribers, so they never see unsettled state

User-facing change:

  • When a drop reorders and switches to Manual, show a toast: "Sort changed to Manual" with an option to restore the previous sort mode

What Changed

  • Moved useDebouncedSortEpoch logic from sidebar hook to settled-sort-epoch.ts store listener
  • Added settledSortEpoch state field; sidebar sort reads this instead of sortEpoch
  • Replaced direct setSortBy('manual') calls with switchSortToManualAfterDrop() function that shows a toast
  • Removed allWorktrees parameter from useSidebarWorktreeSortOrder (no longer needs local worktree count)
  • Added i18n strings for manual sort switch toast
  • Comprehensive tests for settling behavior, toast lifecycle, and sort order with settled epoch

Testing

  • I manually tested these changes locally
  • Automated tests added/updated: settled-sort-epoch.test.ts, manual-sort-switch-toast.test.ts, use-sort-order.test.tsx, and existing worktree-manual-order-store-write.test.ts updated

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • N/A for UI changes (toast styling uses existing tokens)
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

🧰 Additional context used
📚 Code guidelines (1)
AGENTS.md — auto-discovered
📝 Walkthrough

Walkthrough

The store now tracks a settled sort epoch, and the sidebar sorting hook uses it to recompute worktree order. Drops and reorders that change ordering use a shared function to switch to Manual sorting and show a toast with an optional restore action. Tests cover epoch settling, sort behavior, toast dismissal, and reorder cases. English locale strings were added for the toast.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 5a929

A newly hydrated worktree may appear at the end of the sidebar for up to three seconds instead of moving immediately to its sorted position. This is a bounded visual delay, but the structural-change handling should be corrected.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 5a929

The inspected changes remain focused on sidebar ordering and reuse existing worktree mutation operations. No introduced security issue was established, but incomplete lifecycle and downstream coverage prevents a stronger assurance.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated propagation is within renderer store notifications, sidebar ordering, and the existing sorted-ID persistence call. The inspected change does not establish increased tenant, credential, infrastructure, or service authority.

Trust Boundaries and Controls

  • observed — The restore callback captures the prior sort mode and checks retirement before calling the existing setter. Later sort changes retire the callback, preventing an old restore action from overriding a newer choice.

Resilience and Maintainability Implications

  • observed — Sort-mode selection still precedes the asynchronous metadata update, as in the base handlers. The new restore action is not an atomic rollback of that update and does not claim to recover a failed metadata write.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.25% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 13 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the store-based sortEpoch settling change and the React update-depth problem it addresses.
Description check ✅ Passed The description explains the problem, solution, user-facing change, and automated tests. It does not provide a linked issue in the template’s Fixes field, and it marks visual proof as N/A even though …
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 31.25% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 13 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 09e9b2ee-c328-461c-88a1-59c3f8e468c7
📥 Commits

Reviewing files that changed from the base of the PR and between 6c07570 and 5a92914746e18e94b1d049043bcbd18ca10bd821.

📒 Files selected for processing (15)
  • src/renderer/src/components/sidebar/WorkspaceKanbanDrawer.tsx
  • src/renderer/src/components/sidebar/WorktreeList.tsx
  • src/renderer/src/components/sidebar/manual-sort-switch-toast.test.ts
  • src/renderer/src/components/sidebar/manual-sort-switch-toast.ts
  • src/renderer/src/components/sidebar/use-workspace-kanban-worktree-actions.ts
  • src/renderer/src/components/sidebar/worktree-list/drag/use-status-mutations.ts
  • src/renderer/src/components/sidebar/worktree-list/listing/use-sort-order.test.tsx
  • src/renderer/src/components/sidebar/worktree-list/listing/use-sort-order.ts
  • src/renderer/src/components/sidebar/worktree-manual-order-store-write.test.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/store/index.ts
  • src/renderer/src/store/settled-sort-epoch.test.ts
  • src/renderer/src/store/settled-sort-epoch.ts
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees/session/worktree-slice-initial-state.ts
💤 Files with no reviewable changes (1)
  • src/renderer/src/components/sidebar/WorkspaceKanbanDrawer.tsx

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain 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's own CI is red: anti-slop/no-reflect-get rejects Reflect.get in the new use-sort-order.test.tsx, and the verify job cascades off that preflight failure. One-line fix below.

Reviewed changes

  • Store-level settle (settled-sort-epoch.ts) — new listener installed in the store creator coalesces sortEpoch bursts into settledSortEpoch (3s debounce for time-decaying modes; immediate for Manual, structural add/remove, and mode switches).
  • Sidebar reads the settled epoch — use-sort-order.ts drops the useDebouncedSortEpoch React effect and the allWorktrees arg; the memo is now triggered by settledSortEpoch. WorktreeList.tsx call site updated.
  • Manual-sort toast — switchSortToManualAfterDrop() replaces direct setSortBy('manual') at the three drop sites and offers a "Back to " action; i18n keys added.
  • State + tests — settledSortEpoch field/initial state; new settle, toast, and hook tests plus updated manual-order-write test.

The settle rules read correctly: the early settledSortEpoch === sortEpoch return retires the pending timer on settle()/reset, and mode switches settle before hook subscribers re-read. pnpm tc passes and the touched suites I ran (settled-sort-epoch, use-sort-order, manual-order-write, toast, WorktreeList mock tests, and the epoch-sensitive store slice tests) are green.

ℹ️ Nitpicks

  • WorktreeList.card-memo-stability.test.tsx's mock state never provides settledSortEpoch, so useSidebarWorktreeSortOrder now reads undefined there and the "does not re-render cards on an order-preserving sortEpoch bump" case no longer triggers a recompute — it passes vacuously. Adding settledSortEpoch to the mock and bumping that field (alongside sortEpoch) would restore what the test claims to pin.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

In Manual mode the sort hook copied every sortEpoch bump into state from an
effect, adding a nested React update per bump. A burst of store bumps at
startup stacked those into 'Maximum update depth exceeded' (React #185).
Manual now reads the live epoch directly; debounced modes are unchanged.
Reordering by drag still switches the sidebar to Manual so the drop sticks,
but it used to happen silently. Show a toast with a 'Back to <previous sort>'
action; it retires itself on any later sort change so it can't override a
newer choice. Drops while already in Manual stay silent.
Add settledSortEpoch plus a 3 s settle timer owned by a store listener
installed in the state creator. Every write path (slice actions, the web
session sync patch) goes through it, so the settled value stays correct
with no sidebar mounted. Manual, a sort-mode switch, and a bump that
changes the non-archived row count settle in the same notify; other bumps
restart the window. A reset that lands settled clears the timer, and the
disposer runs on HMR teardown.
…o state

The sort hook no longer copies sortEpoch into React state from an effect in
any mode; it reads the store's settledSortEpoch directly. That pattern added
a nested update per bump and stacked into "Maximum update depth exceeded"
(React #185) under flushSync bursts. Tests cover Manual, add/remove, burst
reset, no-bump row changes, mode switch, and 80 flushSync bumps in Recent
while worktrees are added.
Detect structural changes on worktreesByRepo updates in addition to sort
epoch changes. When a row arrives without its own bump during a pending
settlement window, the changed composition must still trigger settlement.
@AmethystLiang
AmethystLiang force-pushed the fix-185-settled-sort-epoch branch from 883c8b1 to dc6bb39 Compare October 4, 2026 22:55
@AmethystLiang
AmethystLiang merged commit 4a41e24 into main Oct 4, 2026
3 checks passed
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