Skip to content

fix(activity): bound Activity portal readiness oscillation (React #185) - #11326

Merged
nwparker merged 3 commits into
mainfrom
nwparker/fix-activity-portal-react-185-render-loop
Jul 29, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/fix-activity-portal-react-185-render-loop

Conversation

@nwparker

@nwparker nwparker commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

What this does

Activity embeds a live terminal and watches its DOM to decide whether it is loading, ready, or unavailable.

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:

  1. Readiness updates are coalesced to one per animation frame, so rapid pane-selection or subscription churn cannot build a synchronous update chain.
  2. A fixed (target, paneKey) subscription that keeps oscillating settles on unavailable after eight flips.

The result is a degraded-but-alive Activity pane showing “Terminal unavailable” instead of a crashed Orca window. A genuine later ready state 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

  • Activity suite: 5 files, 35 tests
  • Web typecheck
  • Native code-quality audit
  • React Doctor on changed files
  • Max-lines ratchet
  • Targeted Oxlint
  • git diff --check

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

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-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds two complementary safeguards against React error #185 (Maximum update depth exceeded) in the Activity portal's readiness loop: all setReadiness calls are now coalesced through requestAnimationFrame (at most one commit per frame), and a per-subscription readinessLatch halts loading ↔ unavailable oscillation after eight flips, settling on unavailable until a genuine ready signal releases it. The portal thread reconciliation and swap logic are also extracted into a new testable module.

  • useActivityTerminalPortalStatus in ActivityPrototypePage.tsx is refactored to route every readiness update through scheduleReadiness (RAF coalescing) and createActivityPortalReadinessLatch; a target/paneKey guard on the return value ensures stale 'ready' never leaks across pane switches.
  • activity-portal-thread-reconciliation.ts is a faithful extraction of the existing visibleThread/stagedThread/resolveSwap logic with no behavioral changes.
  • Five new test files cover rapid pane-key churn, fixed-pane oscillation, latch release on genuine ready, and same-tab vs cross-tab convergence.

Confidence Score: 5/5

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

Important Files Changed

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)"]
Loading

Reviews (3): Last reviewed commit: "test(activity): tighten readiness regres..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c7965f7c-e07c-4b60-9b2a-0e21a427ad80

📥 Commits

Reviewing files that changed from the base of the PR and between 4e49b99 and 9a2b2fb.

📒 Files selected for processing (2)
  • src/renderer/src/components/activity/ActivityPrototypePage.tsx
  • src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/activity/ActivityPrototypePage.tsx

📝 Walkthrough

Walkthrough

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

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary and testing, but it omits required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing template sections and include concise content for screenshots, AI review, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly names the Activity portal readiness oscillation fix and the React #185 crash it addresses.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

🧹 Nitpick comments (1)
src/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsx (1)

289-299: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider a deterministic wait instead of a fixed 60ms sleep.

Both oscillation tests await a real-time setTimeout(..., 60) inside act(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 #185 crash 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

📥 Commits

Reviewing files that changed from the base of the PR and between fa449bc and 92bb375.

📒 Files selected for processing (5)
  • src/renderer/src/components/activity/ActivityPrototypePage.tsx
  • src/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsx
  • src/renderer/src/components/activity/activity-portal-readiness-oscillation.test.ts
  • src/renderer/src/components/activity/activity-portal-readiness-oscillation.ts
  • src/renderer/src/components/activity/activity-portal-thread-reconciliation.ts

@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 (3)
src/renderer/src/components/activity/ActivityPrototypePage.tsx (2)

136-145: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider reusing the exported status union instead of re-declaring it.

activity-portal-readiness-oscillation.ts already defines ActivityPortalReadinessStatus; the inline union here must stay in lockstep with the latch's next() signature.

♻️ Suggested change
 type ActivityTerminalPortalReadiness = {
   target: HTMLElement | null
   paneKey: string | null
-  status: 'loading' | 'ready' | 'unavailable'
+  status: ActivityPortalReadinessStatus
 }

Requires adding ActivityPortalReadinessStatus to the type import from ./activity-portal-readiness-oscillation.


347-367: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The priming updateReadiness('loading') is now a no-op that still spends a latch flip.

Since scheduleReadiness coalesces into a single frame, the 'loading' at Line 366 is overwritten by the synchronous checkReadiness() before anything commits, yet readinessLatch.next('loading') still records a loading→unavailable transition. 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 win

Prefer polling over a fixed 30ms sleep for the frame-coalesced commit.

The readiness commit lands on a requestAnimationFrame callback; a hard-coded sleep is the kind of assumption that goes flaky on loaded CI machines. vi.waitFor keeps 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 vi to the vitest import.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b693de01-cac0-420e-b0d9-c3f39ad65015

📥 Commits

Reviewing files that changed from the base of the PR and between 92bb375 and 4e49b99.

📒 Files selected for processing (6)
  • src/renderer/src/components/activity/ActivityPrototypePage.tsx
  • src/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsx
  • src/renderer/src/components/activity/activity-portal-readiness-oscillation.test.ts
  • src/renderer/src/components/activity/activity-portal-readiness-oscillation.ts
  • src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx
  • src/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

@nwparker
nwparker merged commit 4543bb6 into main Jul 29, 2026
25 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
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