Skip to content

fix(activity): bound the portal readiness loop with a decaying flip window (React #185) - #12485

Closed
nwparker wants to merge 2 commits into
mainfrom
crashfix/w7-activity-latch
Closed

nwparker wants to merge 2 commits into
mainfrom
crashfix/w7-activity-latch

Conversation

@nwparker

@nwparker nwparker commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

fix(activity): bound the portal readiness loop with a decaying flip window

What this fixes

Signature: Error: Minified React error #185 ("Maximum update depth exceeded") thrown from
getRootForUpdatedFiber ← enqueueConcurrentHookUpdate ← dispatchSetState ← commitHookEffectListMount ← commitLayoutEffectOnFiber, caught by RecoverableRenderErrorBoundary with boundary_id: page.activity,
active_view: activity.

Coverage: 3 of the 127 reports in this batch — the page.activity subgroup (d) of the 13-report
G1-react185 cluster. It does not cover the other 10 G1 reports (those are active_view=terminal
with ActivityPrototypePage unmounted; separate workstream).

Representative reports:

Slack Report ID Version Platform
p1785707545376969 49fd99b1-2edf-4313-bde2-18e0c0cdaf5c 1.4.164 darwin 25.5.0 arm64
p1785775829795559 c40e6986-d5e7-48f2-b8dc-140abae7bede 1.4.167 darwin 25.4.0 arm64
p1785806846610159 ba6ec3b8-cfb1-4d12-a451-ecd0ae0ae234 1.4.167 win32 10.0.26100 x64

Root cause

React code 185 in the shipped [email protected] is a nested update guard, not setState-after-unmount —
node_modules/react-dom/cjs/react-dom-client.production.js:2409-2415:

function getRootForUpdatedFiber(sourceFiber) {
  if (50 < nestedUpdateCount)
    throw (
      ((nestedUpdateCount = 0),
      (rootWithNestedUpdates = null),
      Error(formatProdErrorMessage(185)))
    );

4543bb6826 (shipped in v1.4.163) added a flip latch to bound the Activity portal's readiness repaint loop.
That latch is escapable, and the escape is structural. On origin/main:

  • src/renderer/src/components/activity/ActivityPrototypePage.tsx:350 — const readinessLatch = createActivityPortalReadinessLatch() is created inside the readiness layout effect.
  • src/renderer/src/components/activity/ActivityPrototypePage.tsx:383 — that effect's deps are
    [target, paneKey, forceUnavailable].
  • src/renderer/src/components/activity/ActivityPrototypePage.tsx:1592-1614 — the swap layout effect writes
    setActivePortalSlotId(inactivePortalSlotId) (:1608) and setDisplayedPaneKey(...)
    (:1603 / :1609 / :1614), which rewrite the slot DOM element and the pane key together.

So every oscillation step tears down the effect and rebuilds the latch with flips = 0.
ACTIVITY_PORTAL_READINESS_MAX_FLIPS (= 8) can never accumulate, and the repaint loop the latch exists to
bound runs unbounded. The latch's own comment admitted the scope limit verbatim:
activity-portal-readiness-oscillation.ts:3 — "stop a fixed subscription from repainting forever".

The fix

  1. Hoist the latch onto a useRef owned by the hook instance
    (ActivityPrototypePage.tsx:308 on this branch, consumed at :356), so nothing the loop can re-target
    resets it.
  2. Replace the sticky latched flag with a sliding burst window
    (activity-portal-churn-budget.ts, wired in activity-portal-readiness-oscillation.ts):
    ACTIVITY_PORTAL_READINESS_MAX_FLIPS flips inside ACTIVITY_PORTAL_READINESS_BURST_WINDOW_MS = 500.
    A live loop refills the window far faster than it drains, so the latch holds for as long as the churn runs;
    once the churn stops the window decays, so a burnt budget does not answer 'unavailable' for the next pane
    the slot shows (an SSH/relay pane that is merely still attaching gets its real 'loading' back).

What this does NOT claim

This is a bounded mitigation of a provable unbounded loop, not a reproduction of the field crash. React
raises #185 only after >50 consecutive commits that each leave a pending sync/default lane; any commit
leaving none resets nestedUpdateCount. The readiness subscription's only writer is an rAF callback that the
effect cleanup cancels on every churn step, so it contributes zero state updates to a synchronous cascade —
now pinned by a test that drives 60 flushSync churn steps and asserts no readiness commit and no throw.
Whatever schedules the field cascade is a different setState. The link from "this loop was unbounded" to
"these 3 crashes" is inference, not proven causation. The escape itself is proven (red test below).


Fix evidence

Windows verification status (from /tmp/crash-pr-meta.json): not required — pure renderer logic. One of the
three field reports is win32, but nothing in this change is platform-dependent (no paths, no key modifiers, no
native modules); the touched suite is happy-dom/vitest and platform-agnostic.

1. RED without the source fix

Scratch worktree at the branch commit, with only the two source files reverted to origin/main
(ActivityPrototypePage.tsx, activity-portal-readiness-oscillation.ts; the new
activity-portal-churn-budget.ts was left in place as an orphan module since it does not exist on main).
Tests unchanged.

$ git worktree add /tmp/prproof-w7-activity-latch crashfix/w7-activity-latch --detach
$ git checkout origin/main -- src/renderer/src/components/activity/ActivityPrototypePage.tsx \
                             src/renderer/src/components/activity/activity-portal-readiness-oscillation.ts
$ npx vitest run --config config/vitest.config.ts --reporter=verbose \
    src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx \
    src/renderer/src/components/activity/activity-portal-readiness-oscillation.test.ts

 RUN  v4.1.5 /private/tmp/prproof-w7-activity-latch

 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > latches to unavailable once loading<->unavailable keeps flipping 1ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > passes through a normal loading -> ready startup 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > does not latch when ready keeps refunding the budget 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > tolerates a few legitimate flips while xterm attaches 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > releases once the terminal genuinely comes up after a churny attach 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > holds the latch for as long as the DOM keeps flipping 0ms
 × activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > releases a latched pane once the churn stops, so a slow attach still reports loading 3ms
   → expected 'unavailable' to be 'loading' // Object.is equality
 × activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > ignores flips paced by a human clicking between threads 0ms
   → expected 'unavailable' to be 'loading' // Object.is equality
 ✓ activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > contributes no state updates to a synchronous churn cascade past React nested-update limit 12ms
 ✓ activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > coalesces pane-key churn and commits the latest readiness 3ms
 × activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > stops alternating readiness when the slot, pane key and tab id all churn together 14ms
   → expected Set{ 'unavailable', 'loading' } to deeply equal Set{ 'unavailable' }
 × activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > stops alternating readiness when only the pane key churns within one tab 10ms
   → expected Set{ 'unavailable', 'loading' } to deeply equal Set{ 'unavailable' }
 ✓ activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > does not answer for a later attaching pane after human-paced selections 8ms

 Test Files  2 failed (2)
      Tests  4 failed | 9 passed (13)

The two React-level failures are the escape itself. Verbatim assertion detail:

 FAIL  src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > stops alternating readiness when the slot, pane key and tab id all churn together
AssertionError: expected Set{ 'unavailable', 'loading' } to deeply equal Set{ 'unavailable' }

- Expected
+ Received

  Set {
+   "loading",
    "unavailable",
  }

 ❯ expectReadinessStopsAlternating src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx:151:27
    149|     const tail = statuses.slice(ACTIVITY_PORTAL_READINESS_MAX_FLIPS)
    150|     expect(tail.length).toBeGreaterThan(20)
    151|     expect(new Set(tail)).toEqual(new Set(['unavailable']))
       |                           ^
    152|   }
    153|
 ❯ src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx:193:5

 FAIL  src/renderer/src/components/activity/activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > ignores flips paced by a human clicking between threads
AssertionError: expected 'unavailable' to be 'loading' // Object.is equality

Expected: "loading"
Received: "unavailable"

 ❯ src/renderer/src/components/activity/activity-portal-readiness-oscillation.test.ts:88:67
     86|     for (let i = 0; i < ACTIVITY_PORTAL_READINESS_MAX_FLIPS * 4; i += …
     87|       clock.ms += 500
     88|       expect(latch.next(i % 2 === 0 ? 'loading' : 'unavailable')).toBe(
       |                                                                   ^
     89|         i % 2 === 0 ? 'loading' : 'unavailable'
     90|       )

Reading of the red output, stated plainly:

  • The two …churn together / …only the pane key churns failures prove the escape: on origin/main the
    status that drives the swap effect keeps alternating loading↔unavailable for all 40 churn steps, i.e. the
    8-flip budget never accumulates.
  • The two oscillation-unit failures prove the decay/no-bleed property is new: main's latch is sticky, so
    once engaged it answers 'unavailable' forever, and it also spends its budget on human-paced clicking.
  • contributes no state updates to a synchronous churn cascade… and does not answer for a later attaching pane… pass on main too. That is expected and stated honestly: the first documents a pre-existing property
    (rAF coalescing) that this change must not break, and the second passes on main only because main's latch
    is destroyed on every subscription change — the very bug. Both are regression guards, not the red proof.
  • The scratch worktree was removed with git worktree remove --force. No git stash was used at any point.

2. GREEN with the fix (same tests, on the branch)

$ npx vitest run --config config/vitest.config.ts --reporter=verbose \
    src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx

 RUN  v4.1.5 /Users/nwparker/orca/crashwork/w7-activity-latch

 ✓ src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > contributes no state updates to a synchronous churn cascade past React nested-update limit 12ms
 ✓ src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > coalesces pane-key churn and commits the latest readiness 2ms
 ✓ src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > stops alternating readiness when the slot, pane key and tab id all churn together 10ms
 ✓ src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > stops alternating readiness when only the pane key churns within one tab 15ms
 ✓ src/renderer/src/components/activity/activity-portal-readiness-subscription-churn.react185.test.tsx > Activity portal readiness subscription churn > does not answer for a later attaching pane after human-paced selections 3ms

 Test Files  1 passed (1)
      Tests  5 passed (5)
   Duration  2.15s

The regression tests assert loop termination, not a final value: under 40 churn steps the status the swap
effect reads alternates for the first ACTIVITY_PORTAL_READINESS_MAX_FLIPS samples (sanity — the fixture really
does churn) and then stops moving for the remaining 30+ samples. Date is frozen (vi.useFakeTimers({ toFake: ['Date'] }) — timers and rAF untouched) so the window is decided by the churn under test, not by CI load.

3. Full regression suite for the only touched module

src/renderer/src/components/activity/ is the sole touched directory.

$ npx vitest run --config config/vitest.config.ts --reporter=verbose src/renderer/src/components/activity/

 RUN  v4.1.5 /Users/nwparker/orca/crashwork/w7-activity-latch

 ✓ activity-portal-thread-reconciliation.test.ts > resolveActivityPortalSwap cascade > never resolves swap-staged twice in a row for a fixed selection 1ms
 ✓ activity-portal-thread-reconciliation.test.ts > resolveActivityPortalSwap cascade > stages across tabs and refuses to stage inside one tab 0ms
 ✓ activity-portal-churn-budget.test.ts > createActivityPortalChurnBudget > spends once the window holds a full burst 1ms
 ✓ activity-portal-churn-budget.test.ts > createActivityPortalChurnBudget > stays spent while the churn keeps firing 0ms
 ✓ activity-portal-churn-budget.test.ts > createActivityPortalChurnBudget > releases a window after the churn stops 0ms
 ✓ activity-portal-churn-budget.test.ts > createActivityPortalChurnBudget > never spends on events paced slower than the window allows 1ms
 ✓ activity-portal-churn-budget.test.ts > createActivityPortalChurnBudget > treats a backwards clock as an expired window 0ms
 ✓ activity-portal-churn-budget.test.ts > createActivityPortalChurnBudget > clears on demand 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > latches to unavailable once loading<->unavailable keeps flipping 1ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > passes through a normal loading -> ready startup 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > does not latch when ready keeps refunding the budget 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > tolerates a few legitimate flips while xterm attaches 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > releases once the terminal genuinely comes up after a churny attach 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > holds the latch for as long as the DOM keeps flipping 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > releases a latched pane once the churn stops, so a slow attach still reports loading 0ms
 ✓ activity-portal-readiness-oscillation.test.ts > createActivityPortalReadinessLatch > ignores flips paced by a human clicking between threads 0ms
 ✓ ActivityPrototypePage.test.ts > buildActivityEvents > (24 cases) …
 ✓ activity-portal-readiness-subscription-churn.react185.test.tsx > (5 cases) …
 ✓ ActivityThreadOptionsMenu.test.tsx > ActivityThreadOptionsMenu > opens without recursively updating composed Radix trigger refs 50ms
 ✓ activity-portal-readiness-loop.react185.test.tsx > Activity portal pane switching > converges on a newly selected pane of the tab already on screen 53ms
 ✓ activity-portal-readiness-loop.react185.test.tsx > Activity portal pane switching > stages and swaps when the selected pane belongs to a different tab 43ms
 ✓ activity-portal-readiness-loop.react185.test.tsx > Activity portal pane switching > bounds a readiness oscillation driven through the real portal-status hook 4ms
 ✓ activity-portal-readiness-loop.react185.test.tsx > Activity portal pane switching > releases a latched readiness once the terminal attaches 4ms

 Test Files  7 passed (7)
      Tests  50 passed (50)
   Duration  2.63s

(The buildActivityEvents / grouping / filter-shortcut block is elided above only for length — the run is
7 files / 50 tests, 0 failures, 0 pre-existing failures in this directory.)

4. Field data

Verbatim from the crash bundle for report 49fd99b1-2edf-4313-bde2-18e0c0cdaf5c
(~/.agent-slack/tmp/downloads/F0BMF0J45AA.txt), all three reports carry the identical shape:

App version: 1.4.164
Platform: darwin 25.5.0 arm64
Electron: 43.1.0

Details:
- boundary_id: page.activity
- surface: page
- error_name: Error
- error_message: Minified React error #185; visit https:/[redacted-path]
- error_stack: Error: Minified React error #185; visit https:/[redacted-path]
    at getRootForUpdatedFiber (file://[redacted-path])
    at enqueueConcurrentHookUpdate (file://[redacted-path])
    at dispatchSetStateInternal (file://[redacted-path])
    at dispatchSetState (file://[redacted-path])
    at file://[redacted-path]
    at commitHookEffectListMount (file://[redacted-path])
    at commitLayoutEffectOnFiber (file://[redacted-path])
    at recursivelyTraverseLayoutEffects (file://[redacted-path])
    at commitLayoutEffectOnFiber (file://[redacted-path])
    at recursivelyTraverseLayoutEffects (file://[redacted-path])
- component_stack: at ActivityPrototypePage (file://[redacted-path])
    at RecoverableRenderErrorBoundary (file://[redacted-path])
- active_view: activity

commitLayoutEffectOnFiber in the throw frame is what points at Activity's layout effects specifically —
the readiness effect (branch :310-389, main :304-383) and the swap effect (branch :1601, main :1592)
are the page's layout-phase setState writers. Consistent with the crash surviving 4543bb6826: the latch that commit added shipped in v1.4.163 and
these reports are v1.4.164 and v1.4.167.

Weakness of the field evidence, stated plainly: the diagnostic bundles carry no Activity-portal
breadcrumb. Breadcrumb inventory for the v1.4.164 bundle (F0BMJTBRCPK.txt, 564 spans) is
renderer_memory ×472, terminal_webgl_diagnostic ×13, renderer_bootstrap_started/rendered ×6 each,
main_process_lifecycle_started ×6, sidebar_worktree_activate ×4, and updater spans. Nothing instruments
the readiness loop. The "239 renders in 847 ms" figure quoted in the source comments is not from these
bundles — it comes from a prior CDP capture recorded in commit 4543bb6826's message. So the field data
establishes where (page.activity, layout effect, React 185) and the code establishes that the bound was
escapable
; it does not establish that this specific loop was the cascade in these three reports.


ELI5

The Activity page shows a live terminal by "teleporting" it into a slot on screen. Before it can do that it has
to keep asking a question: "is the terminal I'm pointing at ready yet?" The answer can be loading, ready,
or unavailable.

Sometimes the answer gets stuck flapping — loading, unavailable, loading, unavailable — because each
answer causes a repaint and each repaint changes what's being asked about. React allows about 50 of these
back-to-back repaints before it gives up and crashes the whole page with "Maximum update depth exceeded". That's
the crash users see.

A previous fix installed a circuit breaker: after 8 flip-flops, stop and just say unavailable. The problem is
where the breaker was installed. Think of a tally counted on a whiteboard that is mounted on the door of the
room being repainted
— every time the loop re-points at a different terminal it swings the door, and the tally
gets wiped. So the count never reached 8 and the breaker never tripped. The loop the breaker was built for was
exactly the loop that kept resetting it.

This change moves the whiteboard off the door and onto the wall, where nothing the loop does can wipe it. It also
changes the tally from "8 ever" to "8 within the last half-second" — a stopwatch, not a lifetime counter. That
matters because the whiteboard now outlives any one terminal: with a lifetime counter, a user clicking briskly
between a few threads would eventually trip the breaker by hand, and then the next terminal they opened — a
perfectly healthy one that just needed a few seconds to connect over SSH — would be reported as broken. With a
half-second window, a runaway loop (hundreds of flips a second) trips it instantly and keeps it tripped, while a
human would have to click 16 times a second to get anywhere near it, and the moment the flapping stops the
counter drains and the next terminal gets an honest answer.


Trade-offs

  1. The latch now spans threads, not just one terminal subscription. This is the point of the fix, but it
    means the mitigation is no longer perfectly isolated: a genuinely pathological pane can, in principle, put the
    Activity slot into 'unavailable' for up to 500 ms after the user has already navigated to a different,
    healthy pane. The 500 ms window (down from a 5 s window in review round 2) bounds the blast radius, and there
    is a dedicated React-level regression test for the cross-pane bleed
    (does not answer for a later attaching pane after human-paced selections), but the window is not zero.

  2. The latch is now releasable, so the bound is not permanent. On main the latch was sticky until a real
    'ready'. Now it decays after 500 ms of quiet. If a loop is bursty — flips hard, pauses >500 ms, flips
    hard again — each burst gets a fresh budget. It cannot run unbounded within a burst, which is what saturates
    nestedUpdateCount, but this is strictly weaker than "latch forever" and worth naming.

  3. 500 ms is a tuned constant with no field telemetry behind it. It was chosen from the 847 ms/239-render
    CDP capture in 4543bb6826 (~8 flips per 28 ms → >15× margin) and from the human-interaction floor
    (16 selections/second to spend it by hand). Neither of these three crash bundles contains a rate we could
    fit the constant to. If a real loop turns out to run slower than ~16 flips/second, this bound will not catch
    it. Known follow-up: add an activity_portal_readiness_flip breadcrumb so the next batch can validate or
    retune the constant instead of arguing about it. Not done here to keep this change small.

  4. A behaviour that existed on main is now removed: clicking rapidly between two threads where one reports
    loading and the other unavailable used to be free (each selection got a fresh latch). It now feeds a
    shared window. Below 16 selections/second there is no observable difference; above it, the slot will show
    "unavailable" instead of a spinner until the clicking stops.

  5. Reverted from review round 2: the slot-swap churn budget. An earlier revision of this branch also added a
    budget to the swap layout effect. It was removed because it is unreachable: swap-staged sets
    displayedPaneKey to selectedThread.paneKey, making displayedThread === selectedThread, so
    reconcileActivityPortalThreads returns no stagedThread on the next commit — the branch provably cannot
    resolve twice without a new selection (exhaustive proof in the new
    activity-portal-thread-reconciliation.test.ts). Its only reachable effect was to suppress the staging
    toggle after 8 real selections in 2 s, forcing a visible remount flash for fast keyboard users. Dropping
    it is a deliberate reduction in scope, not an oversight; if a swap-effect loop is ever demonstrated, that
    budget is the place to reinstate it.

  6. This does not fix the other 10 G1-react185 reports (active_view=terminal), and it is not proven to
    fix the 3 it targets — see "What this does NOT claim" above. Ship it as a bounded mitigation of a proven
    unbounded loop.

  7. Performance: the new budget allocates one small array per hook instance and does an Array.filter over
    at most 8 entries per readiness probe. /perf verdict: no-regression.


Adversarial review

4 independent adversarial review rounds, each run by a fresh reviewer with no memory of the prior round,
followed by 3 fix rounds. What they found:

  • Round 1 — the original hoist keyed the latch by tab id. Rejected: the swap moves the tab id in lockstep
    with the slot element and pane key (staging only ever happens across tabs), so a tab-id-keyed latch is
    escapable by exactly the same loop. Fixed by keying the latch to the hook instance instead, and by widening
    the React-level test to churn slot + pane key + tab id together.
  • Round 2 — flagged the swap layout effect (:1600-1626) as a second, un-coalesced sync-lane writer, and a
    churn budget was added there. See trade-off 5: round 3 then proved that budget unreachable, and it was
    removed with an exhaustive cascade test in its place.
  • Round 3 — found a real user-facing regression in the fix itself: the burst window was 5 s, wide enough to
    cover ordinary clicking, so 8 non-ready flips at 2 selections/s spent the page-scoped budget and the next pane
    the user opened was answered 'unavailable' for up to 5 s even though it was merely attaching. Fixed by
    tightening the window to 500 ms; a cross-pane-bleed regression test was added and the comment in
    useActivityTerminalPortalStatus that wrongly claimed a later pane could never be answered for was corrected.
  • Round 4 — clean: zero blocking, zero major findings.

Final verdict: clean (zero blocking, zero major).
/perf skill review verdict: no-regression.

Made with Orca 🐋

createActivityPortalReadinessLatch() lived inside the readiness layout effect,
whose deps are [target, paneKey, forceUnavailable]. The swap effect writes both
setActivePortalSlotId and setDisplayedPaneKey, so every oscillation step rebuilt
the latch with flips=0 and ACTIVITY_PORTAL_READINESS_MAX_FLIPS never accumulated;
the spin then saturated React's root-wide nestedUpdateCount (>50) -> error #185.

Hoist the latch onto a ref keyed by tab id, which the swap loop cannot toggle.
…indow

createActivityPortalReadinessLatch() lived inside the readiness layout effect, whose
deps are [target, paneKey, forceUnavailable]. A slot swap rewrites the target element
and the pane key together, so the latch was rebuilt with an empty budget by the very
churn it must bound and the readiness repaint loop could run unbounded.

Hoist the latch onto a ref for the hook instance and count flips in a sliding window
instead of a sticky flag. Nothing the loop can re-target resets it, and it self-decays,
so a burnt budget no longer answers 'unavailable' for every later pane the slot shows --
an SSH pane that only reports 'loading' while it attaches gets its real state back one
window after the churn stops.

Tests assert loop *termination*, not a final value: under 40 churn steps the status the
swap effect reads alternates for the first ACTIVITY_PORTAL_READINESS_MAX_FLIPS samples
and then stops moving. Both are red against main. Date is frozen (timers/rAF untouched)
so the window is decided by the churn, not by CI load.

What this does NOT claim. It is not a reproduction of the field React #185 crashes
(F0BMF0J45AA / F0BMTDBRDEG / F0BNM9GS3U0). React raises #185 only after >50 consecutive
commits that each leave a pending sync/default lane; any commit leaving none resets
nestedUpdateCount (react-dom-client.production.js). The readiness subscription's only
writer is an rAF callback that the effect cleanup cancels on every churn step, so it
contributes zero state updates to a synchronous cascade -- now pinned by a test that
drives 60 flushSync churn steps and asserts no readiness commit and no throw. Whatever
schedules the field cascade is a different setState; this change bounds a runaway
repaint loop, and the crash link remains unproven.

Also drop the slot-swap churn budget added in review round 2. `swap-staged` sets
displayedPaneKey to selectedThread.paneKey, which makes displayedThread ===
selectedThread, so reconcile returns no stagedThread on the next commit; the branch
provably cannot resolve twice without a new selection (new exhaustive
activity-portal-thread-reconciliation test). The budget was therefore unreachable by any
loop and could only be spent by 8 real selections in 2s -- where its only effect was to
suppress the staging toggle and force a visible remount flash for fast keyboard users.

Co-authored-by: Orca <[email protected]>

Review round 3: the window is a *burst* window, not a hold. At 5s it also covered ordinary
clicking -- 8 non-ready flips at 2 selections/s (a live thread reporting 'loading' alternating
with a retained agent thread reporting 'unavailable') spent the page-scoped budget, and the
next pane the user opened was answered 'unavailable' for up to 5s even though it was merely
still attaching. 500ms keeps >15x margin over the field loop (239 renders in 847ms, ~8 flips
per 28ms) while needing 16 selections a second to reach by hand, and it still doubles as the
hold because a live loop refills the window far faster than it drains. New React-level
regression test covers the cross-pane bleed; the comment in useActivityTerminalPortalStatus
that claimed a later pane could never be answered for is corrected.
@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds a sliding-window churn budget for activity portal readiness. The readiness latch records non-ready flips, clears on ready, and returns unavailable while the budget is spent. The activity page preserves the latch across portal subscription changes. Tests cover clock behavior, React 185 subscription churn, readiness stabilization, delayed pane attachment, and thread reconciliation swap outcomes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. 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 and concisely describes the main change: bounding the Activity portal readiness loop with a decaying flip window.
Description check ✅ Passed The description is detailed and on-topic, with testing evidence, AI review findings, platform coverage, trade-offs, and follow-up notes, but lacks an explicit Security Audit section.
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 💡 1
📝 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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a766ad2d-4037-41e8-9ccd-5cb72da11f01

📥 Commits

Reviewing files that changed from the base of the PR and between e9cf106 and 531bc0a.

📒 Files selected for processing (8)
  • src/renderer/src/components/activity/ActivityPrototypePage.tsx
  • src/renderer/src/components/activity/activity-portal-churn-budget.test.ts
  • src/renderer/src/components/activity/activity-portal-churn-budget.ts
  • 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.test.ts

Comment on lines +8 to +19
const thread = (tabId: string, leafId: string): ActivityPortalThreadRef => ({
paneKey: `${tabId}:${leafId}`,
worktree: { id: `wt-${tabId}` },
tab: { id: tabId }
})

// Two tabs in one worktree (staging applies) plus one in another worktree.
const ALL_THREADS = [
thread('tab-a', 'leaf-1'),
thread('tab-b', 'leaf-2'),
thread('tab-c', 'leaf-3')
]

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Model the cross-tab case in one worktree.

Lines 8-19 give each tab a distinct worktree.id. The cross-tab case at Lines 91-98 therefore changes both tab and worktree. A regression that keys terminal identity by worktree alone passes this test. Give tab-a and tab-b the same worktree ID, and update the same-tab fixture.

Based on the provided reconciliation contract, a terminal matches only when both worktree.id and tab.id match.

Proposed fix
-const thread = (tabId: string, leafId: string): ActivityPortalThreadRef => ({
+const thread = (
+  worktreeId: string,
+  tabId: string,
+  leafId: string
+): ActivityPortalThreadRef => ({
   paneKey: `${tabId}:${leafId}`,
-  worktree: { id: `wt-${tabId}` },
+  worktree: { id: worktreeId },
   tab: { id: tabId }
 })
 
 const ALL_THREADS = [
-  thread('tab-a', 'leaf-1'),
-  thread('tab-b', 'leaf-2'),
-  thread('tab-c', 'leaf-3')
+  thread('wt-main', 'tab-a', 'leaf-1'),
+  thread('wt-main', 'tab-b', 'leaf-2'),
+  thread('wt-other', 'tab-c', 'leaf-3')
 ]
@@
-      selectedThread: thread('tab-a', 'leaf-9'),
+      selectedThread: thread('wt-main', 'tab-a', 'leaf-9'),

Also applies to: 82-98

nwparker added a commit that referenced this pull request Aug 5, 2026
Breaks two independent React #185 (Maximum update depth exceeded) crash loops.

- Activity portal publication is idempotent by descriptor value, so a semantic
  no-op no longer bounces synchronously through Terminal and back into Activity.
- The Activity readiness burst budget survives slot, target, pane, and tab
  retargeting, and a quiet loading pane is rechecked when the window expires.
- Terminal cold-parking pins verdict bursts to the safe mounted side before
  React reaches its nested-update limit, with an expiry so tabs can park again.

Supersedes #12492 and #12485.

Portal descriptor equality is keyed off keyof ActivityTerminalPortalTarget so a
new field fails the build instead of silently suppressing a publish. Park-verdict
damping and breadcrumbs gate on pin liveness, and churn crumbs coalesce by
trigger so a burst cannot collapse into a slow-churn slot.
@nwparker

nwparker commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #12600, merged as 5f187e0.

This PR caught a real latch-lifetime bug, and that fix carries over: the readiness burst budget now survives slot, target, pane, and tab retargeting instead of being re-minted whenever portal subscription identities change.

#12600 adds the three things this one was missing:

  • The structural external-store guard. The decaying flip window alone did not reproduce the reported Activity cascade. The actual loop was portal publication bouncing synchronously through Terminal and back, so publication is now idempotent by descriptor value — keyed off keyof ActivityTerminalPortalTarget so a new field fails the build rather than silently suppressing an update.
  • An automatic recovery wakeup. A quiet loading pane has no mutation to release the latch on its own, so it is explicitly rechecked when the burst window expires.
  • The type-aware static analysis failures are fixed.

Closing as superseded — no work is lost.

@nwparker nwparker closed this Aug 5, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#12600)

Breaks two independent React stablyai#185 (Maximum update depth exceeded) crash loops.

- Activity portal publication is idempotent by descriptor value, so a semantic
  no-op no longer bounces synchronously through Terminal and back into Activity.
- The Activity readiness burst budget survives slot, target, pane, and tab
  retargeting, and a quiet loading pane is rechecked when the window expires.
- Terminal cold-parking pins verdict bursts to the safe mounted side before
  React reaches its nested-update limit, with an expiry so tabs can park again.

Supersedes stablyai#12492 and stablyai#12485.

Portal descriptor equality is keyed off keyof ActivityTerminalPortalTarget so a
new field fails the build instead of silently suppressing a publish. Park-verdict
damping and breadcrumbs gate on pin liveness, and churn crumbs coalesce by
trigger so a burst cannot collapse into a slow-churn slot.
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