Skip to content

fix(terminal): stop park-verdict oscillation remounting a pane at commit cadence (#15136) - #17009

Merged
nwparker merged 1 commit into
mainfrom
worktree-agent-ab7ee125b9da6559a
Aug 28, 2026
Merged

nwparker merged 1 commit into
mainfrom
worktree-agent-ab7ee125b9da6559a

Conversation

@nwparker

@nwparker nwparker commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​228 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​228
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​192 $\color{#cf222e}{\Huge{\mathbf{−}}}$​37 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​155

Fixes the CPU/heat half of #15136.

ELI5

Orca can put a terminal "to sleep" (park) when you can't see it, and wake it up when you look at it. Waking up is expensive — it rebuilds the terminal from scratch.

The rule for "is it safe to sleep?" is: can the background watchers still hear this terminal while its screen is gone? But the honest answer to that question changes depending on whether the screen is there right now. So: screen is up → "yes, safe to sleep" → screen goes away → "no, not safe" → screen comes back → "yes, safe" → … The terminal ends up flickering between asleep and awake dozens of times a second, and each flicker pays the full wake-up cost. That's the fan.

Someone already noticed this and added a brake: if a terminal flips 3 times in a second, hold it awake for 60 seconds. The brake was wired to only one of the several things that can order a terminal to sleep. When any of the other things was the one flapping, the brake pressed on nothing — but it still turned off the warning light for 60 seconds. So the terminal kept thrashing all session, silently, and the counter in the log ticked once a minute forever.

This PR wires the brake to the final answer instead of one input, so it actually stops the wheel it is supposed to stop.


Counters, before and after

The reporter's session (issue body):

Counter Count
terminal_replay_guard_wedged_release 2125 (all one pane)
terminal_webgl_diagnostic / webgl-atlas-reset 950 (visibility-resume, settled-reveal, tab-reveal)
terminal_park_verdict_churn 39

I reproduced the same signature in a local main.trace.ndjson (25 h session, ~10 mounted pane managers). The hypothesis in the issue thread holds. Evidence:

terminal_park_verdict_churn  x10 — every one for the SAME tabId
  web-terminal-65bee935-64b8-416a-92fe-c3b413801333
  trigger=burst  flips=3..6  elapsedMs=75..153  windowMs=1000  pinnedForMs=60000

Two things fall straight out of that:

  1. 3–6 flips in 75–153 ms = 20–45 park/reveal flips per second on one pane — the reporter's "3–11 times within one second", worse.
  2. The bursts recur at 60 008 / 60 020 / 60 012 ms spacing. That is exactly pinnedForMs. The pin engages, goes quiet, expires, and the very next flip (8–31 ms later) re-bursts. flips: 6 crumbs prove flips kept accumulating while a pin was live. The existing damping was a treadmill: it silenced its own breadcrumb and stopped nothing.

Atlas resets in the same log: visibility-resume 122 / settled-reveal 122 — a perfect 1:1 pair, both reveal-shaped, exactly the reporter's reason mix. Every heavy reveal pays two registry-wide glyph-atlas wipes.

The wedged replay guards line up too: replayIntoTerminal arms a 10 s probe on reveal; if the pane is unmounted again before xterm drains, the write never parses and 10 s later releases as wedged. 2125 of them on one pane ≈ 2125 reveal→re-park cycles, at the code's own stated ~170 ms flat remount cost ≈ 6 minutes of pure remount CPU, plus the GC churn of allocating and destroying a multi-MB xterm buffer 2000 times. That is the heat. Park churn is the driver; the atlas resets and the wedged guards are symptoms, as @OrcaWin suspected.

Measured on the deterministic repro added here (one park/reveal loop, one tab):

flips pane mounts renders
before 400 200 401 (stopped only by the test's hard stop)
after 4 3 6, settled

terminal_park_verdict_churn goes from ~1 crumb per 60 s with churn continuing underneath it to ~1 crumb per 60 s with the verdict actually held still, which drops the reveal-driven webgl-atlas-reset and terminal_replay_guard_wedged_release traffic with it.


Root cause

The park verdict a tab renders is built here:

src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts:303

if (
  (coldParkTerminalPanes ||          // <- worktree-level park (prop from Terminal.tsx)
    (!isVisible && coldParkedTerminalTabIds.has(terminalTab.id) && …)) && …
) parked.add(terminalTab.id)
…
if (activationDeferredMountTabIds?.has(terminalTab.id) && … canWatcherCoverParkedTerminalTab(…))
  parked.add(terminalTab.id)   // second, entirely separate branch

The oscillation itself is the one this repo already documents in terminal-cold-park-verdict-loop.test.tsx:5-9: canWatcherCoverParkedTerminalTab is re-derived from store and registry state that mounting/unmounting the very pane the verdict controls rewrites. Terminal.tsx:1035-1046 runs that same predicate as a worktree-level park veto (worktreeTabsAreWatcherCovered), and that verdict arrives here as coldParkTerminalPanes.

The loop-breaker was withholdUnparkableTerminalTabs (terminal-cold-park-withheld-tabs.ts:32), which filters only coldParkedTabIds — the right-hand side of that ||. So:

  • a loop driven by coldParkTerminalPanes short-circuits past the pin entirely;
  • so does the activationDeferredMountTabIds branch;
  • and getParkVerdictUnparkPinUntilMs, which is also the only place a pin expires, is likewise reached only for cold-park candidates — so the record never re-arms cleanly, which is why the field trace shows a clean 60 s re-burst cadence forever instead of a settle.

The module's own docstring said so out loud (terminal-park-verdict-flip-telemetry.ts:6-10, before this PR): "the pin can only subtract from the cold-park candidate set … read a repeating burst crumb for one tab as 'damping did not reach the oscillating input'." The field data is exactly that repeating crumb.

Fix

selectParkVerdictPinnedTabIds (terminal-park-verdict-flip-telemetry.ts:188) resolves and expires pins for every live tab, and useTerminalParkVerdictPin (use-terminal-park-verdict-pin.ts) applies them as the last gate on the rendered verdict — the same quantity the flip telemetry observes. Whichever input oscillates, the loop is now broken, on the safe (mounted) side that the existing contract already chose.

Why damping is the correct fix here, not a cop-out. The plant is inside the feedback path by design: parking's precondition is "will the byte watchers cover this tab once its pane is gone?", and the honest answer depends on state only the pane's presence establishes. You cannot delete that feedback without redesigning watcher coverage. What you can do — and what was already agreed as the mechanism — is break the loop at the actuator. This PR does not add a new threshold, raise an existing one, or debounce a symptom: it changes where the existing, already-derived brake is applied, from one input to the verdict, and makes it expire on its own. The atlas reset and the replay guard are deliberately untouched; they are downstream of the reveal.

Fix evidence

Test: terminal-park-verdict-worktree-driver-loop.test.tsx. Single tab, so selectIdsBeyondHotRetain spares it via the last-active exemption and the cold-park set is provably empty — coldParkTerminalPanes is the only driver, which is exactly what the old pin could not reach.

Reverted (pinnedTabIds.size === 0 → >= 0, i.e. the pin never reaches the rendered verdict):

 FAIL  src/renderer/src/components/terminal-pane/terminal-park-verdict-worktree-driver-loop.test.tsx > park-verdict damping reaches the worktree-level driver > settles a verdict whose only driver is the worktree-level park prop
AssertionError: expected 400 to be less than or equal to 4
 ❯ src/renderer/src/components/terminal-pane/terminal-park-verdict-worktree-driver-loop.test.tsx:186:34
    186|     expect(parkVerdictFlipCount).toBeLessThanOrEqual(SETTLED_FLIP_BUDG…
       |                                  ^

 Test Files  1 failed (1)
      Tests  1 failed (1)

Restored: passes at 4 flips / 3 mounts / 6 renders.

Also added a direct unit case in terminal-park-verdict-flip-telemetry.test.ts for the property the old wiring broke — a pin must be selectable and expirable for a tab the cold-park selector never proposed.

Checks

  • tsc clean on all three configs (tsconfig.node.json, tsconfig.tc.cli.json, tsconfig.tc.web.json)
  • oxlint clean on every changed file; no max-lines disable added (the new hook is a separate module precisely so use-terminal-tab-cold-parking.ts stays under the 300-line budget)
  • vitest — 2179 files / 17 813 tests pass across src/renderer/src/components, src/renderer/src/lib/pane-manager, src/renderer/src/store/terminals
  • The pin-expiry wakeup is a single setTimeout per live pin, armed off an absolute deadline and skipped when that deadline is unchanged, so a busy agent pane re-minting the tab model many times a second does not re-arm it. No polling added.

Behaviour change worth knowing

A pinned tab now stays mounted even when the worktree-level verdict (including retention-budget force-park) says park. That is bounded to the 60 s pin window and only triggers after ≥3 verdict round-trips inside one second — which the policy's own hysteresis (30 s cold-park delay) says cannot happen honestly. Two existing assertions in use-terminal-tab-cold-parking.test.ts drove three park round-trips with frozen fake timers and so read as an oscillation; they now advance the clock past the burst window between transitions.

What this does not fix, honestly

This stops the pane from remounting at commit cadence. It does not remove the self-referential coverage predicate that makes the loop possible in the first place — canWatcherCoverParkedTerminalTab still answers differently depending on whether the pane it gates is currently mounted, and Terminal.tsx's worktree-level use of it still has no damping of its own. I could not isolate, from static reading alone, exactly which term inside that predicate flips for the reporter's SSH panes; the trace records the flip, not the input. Making the churn breadcrumb carry the deciding input is the obvious follow-up, and is now much cheaper to act on because the pane is no longer thrashing while you read it.

Closes the perf half of #15136.

…15136)

The verdict-flip pin was computed from flips on the rendered park verdict but
applied only to the cold-park candidate set, so a loop driven by the
worktree-level park prop or the activation-deferred branch kept remounting a
pane at commit cadence while the pin silenced its own breadcrumb for 60s.

Apply the pin to the rendered verdict via selectParkVerdictPinnedTabIds, and
expire pins for every live tab so damping lapses on its own instead of
re-arming forever.
@coderabbitai

coderabbitai Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds useTerminalParkVerdictPin to damp rendered park-verdict flips across all parking sources. It adds telemetry selection for live pinned tabs and pin expiry deadlines. Cold parking now returns the damped verdict and no longer records flips directly. Existing timer-based tests advance past the burst window. A new happy-dom test verifies that a worktree-level verdict oscillation settles within a bounded flip count with the pane mounted.

Merge Risk: 🔵 Low · up to 34281

The PR applies damping to the final terminal parking verdict, preventing rapid pane remounts and reducing CPU and heat. It is mergeable with owner awareness of a bounded edge case where a backward clock adjustment could delay the 60-second pin expiry until another render occurs.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives detailed ELI5 context, root cause, implementation, linked issue, regression evidence, testing results, behavior impact, and limitations. However, it omits the required template s… Add the missing template sections, especially Visual Proof with before-and-after evidence or an exact N/A justification. Complete the Testing, Notes, Review, Agent skill upstream boundary, and Checklist sections, including the required chec…
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the terminal park-verdict oscillation fix and its remounting impact.
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: Description check

Explanation

The description gives detailed ELI5 context, root cause, implementation, linked issue, regression evidence, testing results, behavior impact, and limitations. However, it omits the required template sections and does not provide visual proof or the required N/A explanation for this behavior change.

Resolution

Add the missing template sections, especially Visual Proof with before-and-after evidence or an exact N/A justification. Complete the Testing, Notes, Review, Agent skill upstream boundary, and Checklist sections, including the required checkboxes and platform or CI coverage details.

  • Fix all pre-merge checks with AI
✨ 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.

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/use-terminal-park-verdict-pin.ts (1)

1-15: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Please consolidate the repeated park-verdict damping commentary into one concise invariant. Keep the regression test focused on the worktree-driver behavior and bounded result, and keep implementation comments focused on applying the pin to the merged rendered verdict and expiring it independently. Remove duplicated driver walkthroughs, field traces, and source-path history.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6fb2bfee-ca99-4d96-bf77-7b5abafd0565

📥 Commits

Reviewing files that changed from the base of the PR and between 65dd06a and 342816d.

📒 Files selected for processing (6)
  • src/renderer/src/components/terminal-pane/terminal-park-verdict-flip-telemetry.test.ts
  • src/renderer/src/components/terminal-pane/terminal-park-verdict-flip-telemetry.ts
  • src/renderer/src/components/terminal-pane/terminal-park-verdict-worktree-driver-loop.test.tsx
  • src/renderer/src/components/terminal-pane/use-terminal-park-verdict-pin.ts
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@nwparker
nwparker merged commit 50c8812 into main Aug 28, 2026
48 of 50 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
…tablyai#15136) (stablyai#17009)

The verdict-flip pin was computed from flips on the rendered park verdict but
applied only to the cold-park candidate set, so a loop driven by the
worktree-level park prop or the activation-deferred branch kept remounting a
pane at commit cadence while the pin silenced its own breadcrumb for 60s.

Apply the pin to the rendered verdict via selectParkVerdictPinnedTabIds, and
expire pins for every live tab so damping lapses on its own instead of
re-arming forever.

(cherry picked from commit 50c8812)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#15136) (stablyai#17009)

The verdict-flip pin was computed from flips on the rendered park verdict but
applied only to the cold-park candidate set, so a loop driven by the
worktree-level park prop or the activation-deferred branch kept remounting a
pane at commit cadence while the pin silenced its own breadcrumb for 60s.

Apply the pin to the rendered verdict via selectParkVerdictPinnedTabIds, and
expire pins for every live tab so damping lapses on its own instead of
re-arming forever.
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