Repository navigation
fix(activity): bound Activity portal readiness oscillation (React #185) - #11326
Conversation
React error #185 is "Maximum update depth exceeded" -- an unbounded render loop, not setState-after-unmount as the crash reports superficially suggest. Verified in [email protected]'s production bundle: getRootForUpdatedFiber throws Error(formatProdErrorMessage(185)) when 50 < nestedUpdateCount. That frame is the top of all 14 crash stacks across shipped 1.4.156 / 1.4.158 / 1.4.159. nestedUpdateCount and rootWithNestedUpdates are module-level globals keyed on the ROOT, not on a component. One runaway loop saturates the counter and the throw lands on whichever fiber calls setState next, so SortableTab (terminal.workbench), the Radix Presence/MenuPortal (page.settings) and the sidebar.worktrees button are innocent bystanders with misleading component stacks -- four boundaries, one bug. The driver is Activity's portal readiness pass. When 'ready' is unreachable while 'unavailable' stays reachable, updateReadiness flips loading<->unavailable from inside useLayoutEffect -- React's sync lane, the lane that increments nestedUpdateCount -- so it saturates and throws rather than merely being slow. A prior investigation captured this live on Windows via CDP at 239 renders in 847ms. Bound the oscillation: after ACTIVITY_PORTAL_READINESS_MAX_FLIPS consecutive loading<->unavailable transitions the latch parks on 'unavailable' until a real 'ready' arrives. The latch rewrites only the hook's output, never the DOM probe, so a terminal that churns during a slow attach and then genuinely comes up still releases it. Because the counter is global per root, this also protects every innocent bystander in the app -- most of the user-visible value. Extract reconcileActivityPortalThreads and resolveActivityPortalSwap so the portal loop is testable against the real collaborators. Note the reconciliation keeps its worktree+tab comparison deliberately: Terminal mounts one TerminalPane per (worktree, tab) and routes it by worktree+tab, so staging a same-tab pane would leave the staged slot empty and its readiness stuck on 'loading' forever. Same-tab switches swap in place via isolatedPaneKey instead. Co-authored-by: Orca <[email protected]>
Greptile SummaryThis PR adds two complementary safeguards against React error #185 (
Confidence Score: 5/5Safe to merge; the changes are a well-bounded defense against a known crash with correct cleanup, stale-guard on the hook return, and thorough test coverage. The RAF coalescing and readiness latch are isolated to a single hook and two new pure modules. The return guard correctly prevents stale status from leaking after a pane switch, and the latch's ready path always breaks through and resets the flip budget. Thread reconciliation and swap resolution are faithful extractions with no logic changes. Files Needing Attention: The timer-based tests in activity-portal-readiness-loop.react185.test.tsx (tests 1, 2, and 4) use real wall-clock setTimeout without stubbing RAF and warrant a watch for intermittent failures in constrained CI environments.
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/activity/ActivityPrototypePage.tsx | useActivityTerminalPortalStatus now routes all setReadiness calls through scheduleReadiness (RAF coalescing) and a per-subscription readinessLatch; the return guard (target/paneKey check) correctly prevents stale 'ready' from leaking after a pane switch |
| src/renderer/src/components/activity/activity-portal-readiness-oscillation.ts | New module: latch that bounds non-ready status flips to ACTIVITY_PORTAL_READINESS_MAX_FLIPS (8) before settling on 'unavailable'; 'ready' always breaks through and resets the budget |
| src/renderer/src/components/activity/activity-portal-thread-reconciliation.ts | New module: extracts reconcileActivityPortalThreads and resolveActivityPortalSwap from ActivityPrototypePage; logic is a faithful extraction with no behavioral changes |
| src/renderer/src/components/activity/activity-portal-readiness-oscillation.test.ts | Unit tests for the latch: covers normal startup, ready refunds the budget, tolerates a few legitimate flips, and releases after a latched churny attach |
| src/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsx | Integration tests for React #185 prevention; oscillation and latch-release tests rely on real setTimeout timers (40ms/180ms) which may be flaky under heavy CI load |
| src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx | Integration test for subscription churn: uses flushSync to drive 29 rapid pane-key switches and verifies React does not throw #185; deterministic and correctly bounded |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A["MutationObserver fires\nor forceUnavailable/target/paneKey changes"] --> B["checkReadiness()"]
B --> C{"DOM status"}
C -->|unavailable| D["updateReadiness('unavailable')"]
C -->|ready| E["updateReadiness('ready')"]
C -->|loading| F["updateReadiness('loading')"]
D --> G["readinessLatch.next(status)"]
E --> G
F --> G
G --> H{"latched &&\nstatus != 'ready'?"}
H -->|Yes| I["Return 'unavailable'"]
H -->|No| J{"flips >= 8?"}
J -->|Yes, latch!| I
J -->|No| K["Return status as-is"]
I --> L["scheduleReadiness(latchedStatus)"]
K --> L
L --> M{"readinessFrame\nalready pending?"}
M -->|Yes| N["Update pendingStatus only\n(coalesce)"]
M -->|No| O["requestAnimationFrame()\nschedule RAF"]
O --> P["RAF fires:\ncommit pendingStatus\nvia setReadiness"]
P --> Q{"readiness.target === target\n&& readiness.paneKey === paneKey?"}
Q -->|Yes| R["Return readiness.status"]
Q -->|No| S["Return 'loading'\n(stale guard)"]
Reviews (3): Last reviewed commit: "test(activity): tighten readiness regres..." | Re-trigger Greptile
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe activity portal now reconciles selected and displayed terminal threads through shared utilities and resolves pane transitions as explicit clear, staged-swap, or visible-settle actions. Terminal portal readiness is exported and processed through a per-subscription latch that bounds loading/unavailable oscillations and releases on readiness. New tests cover latch transitions, same-tab and cross-tab portal convergence, DOM-driven oscillation limits, and recovery after terminal attachment. 🚥 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.
🧹 Nitpick comments (1)
src/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsx (1)
289-299: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider a deterministic wait instead of a fixed 60ms sleep.
Both oscillation tests await a real-time
setTimeout(..., 60)insideact(async () => {...})to let MutationObserver callbacks and cascading layout effects settle. All the work here is synchronous (layout effects) plus one microtask hop, so 60ms is generous and low-risk today, but a polling/vi.waitFor-style wait on the latched status or render count would remove the residual timing dependency for a test that specifically guards the React#185crash regression.Also applies to: 351-363
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 85a09ce9-61f1-43c7-88b2-89e23d0e5a7f
📒 Files selected for processing (5)
src/renderer/src/components/activity/ActivityPrototypePage.tsxsrc/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsxsrc/renderer/src/components/activity/activity-portal-readiness-oscillation.test.tssrc/renderer/src/components/activity/activity-portal-readiness-oscillation.tssrc/renderer/src/components/activity/activity-portal-thread-reconciliation.ts
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/renderer/src/components/activity/ActivityPrototypePage.tsx (2)
136-145: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider reusing the exported status union instead of re-declaring it.
activity-portal-readiness-oscillation.tsalready definesActivityPortalReadinessStatus; the inline union here must stay in lockstep with the latch'snext()signature.♻️ Suggested change
type ActivityTerminalPortalReadiness = { target: HTMLElement | null paneKey: string | null - status: 'loading' | 'ready' | 'unavailable' + status: ActivityPortalReadinessStatus }Requires adding
ActivityPortalReadinessStatusto the type import from./activity-portal-readiness-oscillation.
347-367: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe priming
updateReadiness('loading')is now a no-op that still spends a latch flip.Since
scheduleReadinesscoalesces into a single frame, the'loading'at Line 366 is overwritten by the synchronouscheckReadiness()before anything commits, yetreadinessLatch.next('loading')still records aloading→unavailabletransition. Net effect is one flip of the eight-flip budget consumed per subscription without any observable status change.♻️ Suggested cleanup
- updateReadiness('loading') checkReadiness()If the intent is to reset the displayed status on resubscribe, call
scheduleReadiness('loading')directly so it bypasses the latch.src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx (1)
74-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPrefer polling over a fixed 30ms sleep for the frame-coalesced commit.
The readiness commit lands on a
requestAnimationFramecallback; a hard-coded sleep is the kind of assumption that goes flaky on loaded CI machines.vi.waitForkeeps the same assertion while tolerating slower frames.♻️ Suggested change
- await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 30)) - }) - expect(status).toBe('unavailable') + await act(async () => { + await vi.waitFor(() => { + expect(status).toBe('unavailable') + }) + }) expect(renders).toBeLessThanOrEqual(32)Add
vito thevitestimport.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b693de01-cac0-420e-b0d9-c3f39ad65015
📒 Files selected for processing (6)
src/renderer/src/components/activity/ActivityPrototypePage.tsxsrc/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsxsrc/renderer/src/components/activity/activity-portal-readiness-oscillation.test.tssrc/renderer/src/components/activity/activity-portal-readiness-oscillation.tssrc/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsxsrc/renderer/src/components/activity/activity-portal-thread-reconciliation.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/renderer/src/components/activity/activity-portal-readiness-oscillation.ts
- src/renderer/src/components/activity/activity-portal-readiness-oscillation.test.ts
- src/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsx
- src/renderer/src/components/activity/activity-portal-thread-reconciliation.ts
…blyai#185) (stablyai#11326) * fix(activity): bound Activity portal readiness oscillation (React stablyai#185) React error stablyai#185 is "Maximum update depth exceeded" -- an unbounded render loop, not setState-after-unmount as the crash reports superficially suggest. Verified in [email protected]'s production bundle: getRootForUpdatedFiber throws Error(formatProdErrorMessage(185)) when 50 < nestedUpdateCount. That frame is the top of all 14 crash stacks across shipped 1.4.156 / 1.4.158 / 1.4.159. nestedUpdateCount and rootWithNestedUpdates are module-level globals keyed on the ROOT, not on a component. One runaway loop saturates the counter and the throw lands on whichever fiber calls setState next, so SortableTab (terminal.workbench), the Radix Presence/MenuPortal (page.settings) and the sidebar.worktrees button are innocent bystanders with misleading component stacks -- four boundaries, one bug. The driver is Activity's portal readiness pass. When 'ready' is unreachable while 'unavailable' stays reachable, updateReadiness flips loading<->unavailable from inside useLayoutEffect -- React's sync lane, the lane that increments nestedUpdateCount -- so it saturates and throws rather than merely being slow. A prior investigation captured this live on Windows via CDP at 239 renders in 847ms. Bound the oscillation: after ACTIVITY_PORTAL_READINESS_MAX_FLIPS consecutive loading<->unavailable transitions the latch parks on 'unavailable' until a real 'ready' arrives. The latch rewrites only the hook's output, never the DOM probe, so a terminal that churns during a slow attach and then genuinely comes up still releases it. Because the counter is global per root, this also protects every innocent bystander in the app -- most of the user-visible value. Extract reconcileActivityPortalThreads and resolveActivityPortalSwap so the portal loop is testable against the real collaborators. Note the reconciliation keeps its worktree+tab comparison deliberately: Terminal mounts one TerminalPane per (worktree, tab) and routes it by worktree+tab, so staging a same-tab pane would leave the staged slot empty and its readiness stuck on 'loading' forever. Same-tab switches swap in place via isolatedPaneKey instead. Co-authored-by: Orca <[email protected]> * fix(activity): coalesce portal readiness updates * test(activity): tighten readiness regression coverage --------- Co-authored-by: Orca <[email protected]>
What this does
Activity embeds a live terminal and watches its DOM to decide whether it is
loading,ready, orunavailable.Under a bad portal state, readiness can keep alternating:
loading → unavailable → loading → unavailable → …Each transition schedules a React update. Enough synchronous updates trigger React error #185 (
Maximum update depth exceeded) and crash the renderer.This PR adds two safeguards:
(target, paneKey)subscription that keeps oscillating settles onunavailableafter eight flips.The result is a degraded-but-alive Activity pane showing “Terminal unavailable” instead of a crashed Orca window. A genuine later
readystate releases the latch and displays the terminal normally.Scope
This is defense in depth, not a proven root-cause fix. The production trigger that creates the unstable terminal state is still unknown; the captured Windows harness used synthetic rapid selection churn.
This should prevent the observed Activity readiness loop from crashing the renderer. It does not prove that every React #185 report shares that driver, so this PR does not claim to fix all 14 reports.
The additional readiness latency is at most one animation frame. Portal publication remains synchronous, preserving the existing wrong-terminal-flash protection.
Verification
git diff --checkThe regression coverage includes rapid pane-key churn, a persistent fixed-pane oscillation, same-tab and cross-tab portal convergence, and recovery after the latch has fired.
Made with Orca 🐋