Skip to content

perf(terminal): mount only the visible pane on a worktree switch - #20034

Merged
nwparker merged 3 commits into
mainfrom
nwparker/instant-switch-worktrees
Sep 11, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/instant-switch-worktrees

Conversation

@nwparker

@nwparker nwparker commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​638 $\color{#cf222e}{\Huge{\mathbf{−}}}$​14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​624
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​154 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​153

ELI5

Switching to a worktree used to rebuild every terminal tab it holds — even the ones hidden behind other tabs — before showing you the one you clicked on. Like a clerk pulling every file in the drawer onto the desk before handing you the one you asked for. The more tabs a worktree had, the longer you stared at a blank terminal.

Now a switch builds only the terminal you're looking at. The hidden ones are built moments later, on idle frames, so by the time you'd click one it's already there. Nothing was removed or cut — the work just moved off the moment you're watching.

Problem

COLD_ACTIVATION_TAB_DEFER_THRESHOLD was 4, so cold-activation deferral (#8597) only engaged past four deferrable hidden tabs. That exempted the 2–5 tab worktrees that make up almost every real switch, and those paid the full fan-out: per hidden tab a new Terminal + open() + 5 addons, an unchunked snapshot terminal.write(), and — precisely because the tab is hidden and has no WebGL — a synchronous _core.refresh(…, true) DOM repaint.

The threshold was deliberate blast-radius control when deferral first shipped ("small worktrees … keep today's behavior exactly", #8597), not a measured optimum. At many-worktree scale it is the common case: the profile that motivated this has 449 worktrees / 846 tabs, median 2–3 tabs each, and hot-retain only keeps 4 worktrees warm — so nearly every switch lands on a worktree with no panes mounted.

Fix

  1. COLD_ACTIVATION_TAB_DEFER_THRESHOLD: 4 → 0 — an activation mounts only what the user can see. Tabs that are live, have a pending spawn, or that parked byte watchers cannot cover still mount immediately; eligibility is otherwise untouched.
  2. useActivationDeferredTabAdmission — admits the skipped siblings one per idle frame after the reveal, capped by ACTIVATION_DEFERRED_ADMISSION_LIMIT = 4, exactly the population the old threshold would have mounted eagerly. A worktree that deferred more than that keeps every deferred tab unmounted, as before.

The cap is what makes this free rather than a trade: steady-state pane, WebGL-context and heap population is unchanged — only the frame the mounts land on moved.

One tab per effect run, not a loop: admitting bumps the mount revision, which re-runs the effect and schedules the next. The drain is the render cycle.

Eligibility is judged on the high-water mark of the deferred set, not a single reading. At launch the active worktree is restored before hydration opens the startup gate, so the first reading is an empty set; only re-reading on growth lets that worktree's real plan be judged when it lands. An over-cap worktree still stays ineligible however far its set drains.

Proof

tests/e2e/worktree-switch-first-paint.spec.ts: first activation of a worktree whose tabs are in the persisted session but have never been mounted — the state nearly every switch lands in past a handful of worktrees. 200 filler worktrees + ~400 filler tabs for a field-scale store, production parking timings, median of 4 rounds, same build pipeline both arms.

Real hardware (M4 MacBook Air, headful GPU-backed window, before/after built and run back-to-back on the same machine):

Worktree Before After
3 terminal tabs 221 ms (worst 449) 127 ms (worst 132) 1.7×
5 terminal tabs 508 ms (worst 647) 127 ms (worst 153) 4.0×

First paint is now flat in tab count (127 ms either way) where it previously scaled 221 → 508 ms. Activation latency also drops: 74 → 49 ms and 141 → 54 ms.

Headless CI, same spec, for reference: 299 → 90 ms (3 tabs), 744 → 99 ms (5 tabs).

Zero trade-offs, measured not asserted — the spec pins both halves:

  • panes at switch: 1, 1, 1, 1 after vs 3,3,3,3 / 5,5,5,5 before — the switch mounts only the visible pane.
  • settled panes: 4,4,4,4 (3-tab) and 6,6,6,6 (5-tab), identical before and after on both machines — the warm working set is restored, so later tab switches stay as warm as they were.

WebGL

An earlier revision of this description claimed the measurements excluded WebGL because the harness reported 0 attached contexts. That was a bug in the probe, not the product. PaneManager.getPanes() returns a public projection (pane-public-view.ts:3-15) with no webglAddon field, so the count could never be anything but 0. Fixed to read getRenderingDiagnostics(), which now reports attached contexts as expected. WebGL is live on every visible pane, so the numbers above do include per-pane WebGL cost on both arms.

Verification

  • pnpm tc clean; check:code-quality:changed 0 new findings; max-lines and reliability-gate ratchets pass.
  • 4,585 unit tests across terminal/ + terminal-pane/ pass.
  • E2E sweep, 14 passed: cold-activation deferral, hidden-view parking, parked memory, background-mount authority, parked CLI split, tab-switch visual restore.

Known limits

  • SSH / remote worktrees get none of this. canDeferColdActivationTabsForHost restricts deferral to local hosts and paired runtimes — true before and after this change. Provably unchanged: for a non-deferrable host every tab lands in initial, so deferredCount is 0 and 0 <= 0 returns false exactly as 0 <= 4 did.
  • Paired remote runtimes are deferral-eligible and now defer below 4 hidden tabs; the per-tab watcher-coverage gate is the same one the >4 case already relied on, but this path was not measured.
  • A tab clicked before admission reaches it pays one mount — the same mount the old design paid during the switch itself, so not a net regression.

Also included

tests/tools/benchmarks/terminal-{perf,cold-park-resource,cold-park-reveal}-bench.mjs imported ../../config/scripts/... from a directory three levels deep, so all three crashed on startup with ERR_MODULE_NOT_FOUND. Corrected to ../../../config/... — broken on main, and needed to measure this area.

Activating a worktree mounted a TerminalPane for every tab it holds, not just
the one on screen. Cold-activation deferral existed for this but engaged only
past four deferrable hidden tabs, which exempted the 2-5 tab worktrees that
make up almost every real switch.

Deferral now engages for any deferrable hidden tab, and the siblings it skips
are admitted one per idle frame after the reveal, capped at the population the
old threshold would have mounted eagerly. Steady-state pane, WebGL-context and
heap population are therefore unchanged; only the frame the mounts land on
moved.

@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 idle-frame admission drain never runs for the worktree restored active at app launch, leaving its hidden tabs cold — the one case this PR claims to leave unchanged.

Reviewed changes

  • Threshold to zero — COLD_ACTIVATION_TAB_DEFER_THRESHOLD drops 4 → 0, so a cold activation mounts only the visible pane.
  • Idle-frame admission — new useActivationDeferredTabAdmission hook mounts skipped siblings one per idle frame, capped at ACTIVATION_DEFERRED_ADMISSION_LIMIT = 4.
  • Pure admission helpers — activation-deferred-tab-admission (pick-next, eligibility, scheduler) with focused unit tests.
  • E2E paint-budget spec — measures switch → painted content and pins the "1 pane at switch, warm set restored" invariant.
  • Benchmark import fix — ../../ → ../../../ in three terminal bench scripts.

ℹ️ Nitpicks

  • background-terminal-worktree-mount.test.ts's mounts everything at once when few tabs would defer test now drives tabIds(COLD_ACTIVATION_TAB_DEFER_THRESHOLD + 1) = a single immediate tab, so it exercises the degenerate zero-deferred boundary rather than the "few tabs" case its name describes. That intent is now covered by the new single-hidden-tab test; consider renaming or dropping this one.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

return
}
const deferredTabIds = activationDeferredMountTabIdsByWorktreeRef.current.get(worktreeId)
if (admissionRef.current?.worktreeId !== worktreeId) {

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.

Eligibility is cached keyed only by worktreeId, but deferral for the worktree restored active at launch is planned only after workspaceSessionReady flips true (applyTerminalColdActivation gates on canMountTerminalWorkspaceForStartup). On startup renderedActiveWorktreeId is restored before the session is ready, so this effect first runs against an empty deferred set, caches eligible: false, and — because the guard only re-evaluates on a worktree change — never recomputes once deferral is planned during hydration. The launch worktree's hidden tabs then stay unmounted instead of warming up, breaking the PR's steady-state guarantee.

Technical details
# Launch worktree's deferred tabs are never admitted

## Affected sites
- `src/renderer/src/components/terminal/use-activation-deferred-tab-admission.ts:43-48` — `admissionRef` caches the verdict keyed only by `worktreeId`, so it cannot flip `false` → `true` without leaving and re-entering the worktree.
- `src/renderer/src/components/terminal-cold-activation.ts:42-49` — deferral is planned only once `workspaceSessionReady` is true.

## Required outcome
- Hidden tabs on the worktree restored active at app launch must still be admitted on idle frames once deferral is planned, so the warm working set matches pre-deferral behaviour.

## Suggested approach (optional)
- Reset `admissionRef.current` to `null` whenever the deferred set for the current worktree transitions from empty to non-empty (deferral freshly planned), or drop the cached verdict and instead re-check the deferred count against `ACTIVATION_DEFERRED_ADMISSION_LIMIT` each run.

## Open questions for the human (optional)
- Is `renderedActiveWorktreeId` reliably non-null (restored from the persisted session) before `workspaceSessionReady`? `tests/e2e/helpers/orca-app.ts:408` implies yes.

@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: cc9848e9-e459-4f86-96c2-b9456f9584cf

📥 Commits

Reviewing files that changed from the base of the PR and between 7bd7da7 and 65412d4.

📒 Files selected for processing (1)
  • tests/e2e/worktree-switch-first-paint.spec.ts

📝 Walkthrough

Walkthrough

The change adds bounded, idle-time admission for activation-deferred terminal tabs. Cold activation now defers hidden tabs, and the new hook admits them one per idle cycle. Unit and end-to-end tests cover selection, scheduling, draining, first paint, and deferred warming. Benchmark scripts also receive corrected helper import paths and repository root resolution.

Merge Risk: 🟡 Moderate · up to 7bd7d

Performance validation can overstate visible readiness and resource behavior, while revisiting a worktree after an over-limit activation can leave otherwise eligible hidden tabs unmounted. These should be addressed before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely summarizes the main change: mounting only the visible terminal pane during a worktree switch.
Description check ✅ Passed The description is detailed and covers the problem, solution, rationale, testing, performance results, limitations, and related issue context. It does not include the exact template headings for What …
  • Fix all pre-merge checks with AI
✨ 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.

Actionable comments posted: 5


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 69c41b5b-3b98-4e50-9db1-32c6acc3757b

📥 Commits

Reviewing files that changed from the base of the PR and between 2ecde71 and e08ca3f.

📒 Files selected for processing (10)
  • src/renderer/src/components/terminal/activation-deferred-tab-admission.test.ts
  • src/renderer/src/components/terminal/activation-deferred-tab-admission.ts
  • src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts
  • src/renderer/src/components/terminal/background-terminal-worktree-mount.ts
  • src/renderer/src/components/terminal/use-activation-deferred-tab-admission.ts
  • src/renderer/src/components/use-terminal-controller.ts
  • tests/e2e/worktree-switch-first-paint.spec.ts
  • tests/tools/benchmarks/terminal-cold-park-resource-bench.mjs
  • tests/tools/benchmarks/terminal-cold-park-reveal-bench.mjs
  • tests/tools/benchmarks/terminal-perf-bench.mjs

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

Comment on lines +39 to +40
if (!worktreeId) {
return

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

Reset admissionRef when an activation ends.

When the deferred set drains, the effect runs again but reuses the previous verdict for the same worktreeId. A later activation with a different deferred count can therefore strand eligible tabs or admit more than four tabs. Clear the ref when no worktree or deferred tabs remain, and add a same-worktree reactivation test.

Comment on lines +54 to +58
// and this one, and admitting a stale id would strand the restriction.
const allTabIds = (useAppStore.getState().tabsByWorktree[worktreeId] ?? []).map(
(tab) => tab.id
)
const nextTabId = pickNextActivationDeferredTabId(

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

When an activation-deferred tab closes before its idle callback runs, pickNextActivationDeferredTabId returns null and the callback exits without cleaning stale deferred entry IDs from the restriction set. These entries remain until pruneClosedBackgroundMountTabs runs separately, causing unnecessary idle callback cycles. Clean up closed deferred IDs at the point where nextTabId is null so the admission loop exits immediately and the restriction is released once no live deferred tabs remain.

Comment on lines +195 to +207
if (probe.contentPaintedMs === null && pane) {
// Painted = the revealed viewport actually carries restored text, not
// an empty grid. A blank reveal fails this until the replay lands.
const buffer = pane.terminal.buffer.active
let filledRows = 0
for (let row = 0; row < pane.terminal.rows; row += 1) {
const line = buffer.getLine(buffer.viewportY + row)
if (line && line.translateToString(true).trim().length > 0) {
filledRows += 1
}
}
if (filledRows >= Math.min(5, pane.terminal.rows)) {
probe.contentPaintedMs = now

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

Measure rendered output, not terminal buffer readiness.

pane.terminal.buffer.active can contain restored text before xterm renders it. The probe reads that buffer inside requestAnimationFrame, which runs before the browser paints. It can therefore record contentPaintedMs before the text is visible. Record the timestamp after render completion and a subsequent frame, or validate the rendered output directly.

🧰 Tools
🪛 ast-grep (0.45.3)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFileSync } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Comment on lines +401 to +404
const warmedTabIds = await waitForMountedTabs(orcaPage, targetTabIds)
expect(warmedTabIds, 'deferred tabs never joined the warm working set').toEqual(
[...targetTabIds].sort()
)

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 | 🟠 Major | ⚡ Quick win

Assert the settled pane and WebGL populations.

This assertion proves only that each target tab has a pane manager. The test records settledPanes and settledWebglContexts, but it never validates them. A regression that omits panes or WebGL contexts can pass this test.

Add assertions for the expected settled pane count and WebGL-context count.

🧰 Tools
🪛 ast-grep (0.45.3)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFileSync } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

…t seen

Review found the launch worktree never warms up: it is restored active before
hydration opens the startup gate, so admission read an empty deferred set,
cached ineligible, and never recomputed once the real plan landed. Judge on the
high-water mark instead - an over-cap worktree still stays ineligible as its set
drains, but a later plan is seen.

Also from review: the e2e WebGL counter read getPanes(), which returns a public
projection with no webglAddon field, so it was always 0; read
getRenderingDiagnostics() instead. Filler worktrees now clean up on failure
(testRepoPath is worker-scoped), and the restore metric is named for what it
measures rather than implying a pixel assertion.
@nwparker

Copy link
Copy Markdown
Contributor Author

Thanks — the launch-worktree finding was a real bug and is fixed in 7bd7da7.

@pullfrog / @coderabbitai (latched eligibility verdict) — confirmed and fixed. At launch renderedActiveWorktreeId is restored before canMountTerminalWorkspaceForStartup opens the startup gate, so admission's first read was an empty deferred set; it cached ineligible and, because the guard only re-evaluated on a worktree change, never recomputed once hydration planned the real deferral. The launch worktree's hidden tabs stayed cold — exactly the steady-state guarantee this PR claims to preserve.

Fixed by judging on the high-water mark of the deferred set rather than one reading. That closes CodeRabbit's variant in the same stroke: an over-cap worktree stays ineligible however far it drains (so admission can never exceed the pre-deferral warm set), while a plan that lands later is still seen. Regression test added covering launch (0 → 3 ⇒ eligible), draining (0,3,2,1 ⇒ still eligible), and over-cap (7,4,2 ⇒ never eligible).

@coderabbitai (e2e WebGL counter) — not one of your comments, but your review prompted the check that found it: the counter read pane.webglAddon off getPanes(), which returns a public projection (pane-public-view.ts:3-15) with no such field. It was structurally pinned at 0. Now reads getRenderingDiagnostics(). This corrected a false claim in the PR description — WebGL is attached, so the measurements do include its cost.

@coderabbitai (filler worktree cleanup) — fixed. addFillerWorktrees now removes every path it created before rethrowing, and the scenario body is wrapped in try/finally so cleanup runs on assertion failure too. testRepoPath is worker-scoped, so a half-built fixture would have leaked into later specs.

@coderabbitai (buffer readiness vs rendered output) — fair, and taken as a naming fix rather than a behaviour change. The metric is now contentRestoredMs with a comment stating it is read on a frame callback and is therefore the frame the content became renderable, not a pixel assertion. Both arms are measured identically, so the comparison holds; I'd rather the name not overstate it.

@coderabbitai (stale deferred IDs causing extra idle cycles) — declining, I believe the premise is off. When pickNextActivationDeferredTabId returns null the callback returns without bumping the mount revision, so the effect does not re-run and no further idle callback is scheduled — the loop exits immediately rather than spinning. The stale entry is then cleared by pruneClosedBackgroundMountTabs, which runs on every render of the controller. Happy to reopen if you're seeing a path where the revision does get bumped there.

@pullfrog

pullfrog Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Verified both open points against the current code.

Launch-worktree fix (high-water mark) — correct. The first read of the deferred set is empty because the active worktree is restored before canMountTerminalWorkspaceForStartup opens the startup gate; admissionRef now tracks the max seen for the worktree, so the plan that lands later is still judged while an over-cap set can never drain its way into eligibility. max = max(prev, current) with isActivationAdmissionEligible(max) is the right shape, and the 0 → 3, 0,3,2,1, and 7,4,2 cases are all pinned by the new test.

Stale deferred IDs — agreeing with the decline; the premise doesn't hold. pickNextActivationDeferredTabId iterates the fresh allTabIds read from the store inside the callback, so it can never return a closed tab's id. When only stale ids remain it returns null, and the callback returns before setBackgroundMountRevision; the effect is keyed on [backgroundMountRevision, renderedActiveWorktreeId], so no bump means no re-run and no further idle callback — the loop exits rather than spins. Each non-null pick also guarantees forward progress (the picked id is in the deferred set but not the restriction, so grew is always true and the set shrinks by one), so there's no no-progress cycle either. The lingering stale entry is reaped by pruneClosedBackgroundMountTabs on the next controller render, which is harmless given nothing is being scheduled in the interim.

No further action from me.

Pullfrog  | View workflow run | via Pullfrog | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/e2e/worktree-switch-first-paint.spec.ts (2)

192-207: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add a pixel-presentation assertion or rename the first-paint contract.

contentRestoredMs reads pane.terminal.buffer.active in requestAnimationFrame; it does not inspect presented pixels. FIRST_PAINT_BUDGET_MS compares this value, while reveal presentation occurs separately and may refresh only on a later settled frame. The test can therefore pass before the terminal pixels are presented. Rename the budget and test output to content restoration, or add a pixel-level assertion.


434-462: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Assert settled resource limits after deferred admission. measureSwitch() snapshots pane and WebGL counts before waitForMountedTabs() establishes that deferred admission is complete. The test only publishes those counts, so excess panes or WebGL contexts can pass. Capture the counts after waitForMountedTabs() returns and assert the established post-admission limits for every sample.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c680f0ce-e57d-42a4-bbac-edc6de0222ec

📥 Commits

Reviewing files that changed from the base of the PR and between e08ca3f and 7bd7da7.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal/activation-deferred-tab-admission.test.ts
  • src/renderer/src/components/terminal/use-activation-deferred-tab-admission.ts
  • tests/e2e/worktree-switch-first-paint.spec.ts

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

Comment on lines +39 to +40

useEffect(() => {

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.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Reset admissionRef at each activation-plan boundary. When a worktree previously has more than four deferred tabs, a later plan with four or fewer tabs retains the old high-water count through lines 51–56. isActivationAdmissionEligible then remains false, so scheduleActivationDeferredAdmission never runs and the hidden tabs remain unmounted. Reset the entry when applyTerminalColdActivation starts a new plan.

@coderabbitai

coderabbitai Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline src/renderer/src/components/terminal/use-activation-deferred-tab-admission.ts --items all
ast-grep outline src/renderer/src/components/terminal/activation-deferred-tab-admission.test.ts --items all
ast-grep outline tests/e2e/worktree-switch-first-paint.spec.ts --items all

printf '\n--- deferred admission hook ---\n'
cat -n src/renderer/src/components/terminal/use-activation-deferred-tab-admission.ts

printf '\n--- deferred admission tests ---\n'
cat -n src/renderer/src/components/terminal/activation-deferred-tab-admission.test.ts

printf '\n--- e2e relevant references ---\n'
rg -n -C 5 'getRenderingDiagnostics|webglAddon|addFillerWorktrees|contentRestoredMs|requestAnimationFrame|finally|cleanup' \
  tests/e2e/worktree-switch-first-paint.spec.ts

Length of output: 20496


@nwparker Thanks for the detailed follow-up.

I verified the fixes in the current PR revision.

  • The admission hook uses the per-worktree high-water mark. It can admit a launch plan that arrives after the initial empty read. It keeps an over-cap plan ineligible while the set drains.
  • The e2e probe now reads WebGL state through getRenderingDiagnostics().
  • The e2e metric is contentRestoredMs. Its comment accurately states the frame-based, non-pixel-assertion semantics.
  • The scenario calls filler.cleanup() in finally.

I withdraw the stale deferred-ID finding. When pickNextActivationDeferredTabId returns null, the callback returns before setBackgroundMountRevision. The effect does not schedule another admission callback on that path.

🐇 ✅


✏️ Learnings added
Learnt from: nwparker
URL: https://github.com/stablyai/orca/pull/20034

Timestamp: 2026-09-11T07:04:24.296Z
Learning: In `src/renderer/src/components/terminal/use-activation-deferred-tab-admission.ts`, launch can restore `renderedActiveWorktreeId` before hydration creates the activation-deferred set. Admission eligibility must use the largest deferred-tab count observed for each worktree. This permits a deferred plan that arrives after an initial empty read, while preserving ineligibility for a plan that exceeded the admission limit before it drained.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

@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 high-water mark removes the latched false verdict, but it does not make the effect re-run once deferral is planned during launch hydration — so the worktree restored active at startup still leaves its hidden tabs unmounted, the exact case this PR claims to leave unchanged.

Reviewed changes

  • High-water-mark eligibility — useActivationDeferredTabAdmission now tracks the largest deferred count seen per worktree instead of latching a one-time verdict, and skips empty reads.
  • High-water-mark unit test — new judges eligibility on the largest deferred set seen, not the latest case.
  • E2E diagnostics fix — contentPaintedMs → contentRestoredMs, and settledWebglContexts reads getRenderingDiagnostics() (the supported observer) instead of the always-falsy pane.webglAddon projection.
  • E2E fixture cleanup — filler-worktree teardown moved behind try/finally so a half-built fixture doesn't leak worktrees into later specs.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

setBackgroundMountRevision((revision) => revision + 1)
})
// oxlint-disable-next-line react-hooks/exhaustive-deps -- controller refs and setters preserve their original stable identities.
}, [backgroundMountRevision, renderedActiveWorktreeId])

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.

The high-water mark fixes the latched false verdict but not the trigger. This effect still only re-runs when backgroundMountRevision or renderedActiveWorktreeId changes, and neither changes when planColdActivationTabDeferral populates the deferred set: renderedActiveWorktreeId (= activeWorktreeId) is restored before workspaceSessionReady/hydrationSucceeded flip and then stays stable, and backgroundMountRevision only bumps on background-mount IPC — the visible pane's cold activation calls planColdActivationTabDeferral directly (a ref write, no state change). The launch worktree's hidden tabs therefore still never admit, so the effect needs a dependency that actually changes when deferral is planned (e.g. workspaceSessionReady/hydrationSucceeded, or a revision bumped from applyTerminalColdActivation).

Technical details
# Launch worktree's deferred tabs are still never admitted

## Affected sites
- src/renderer/src/components/terminal/use-activation-deferred-tab-admission.ts:40-82 — deps are only `[backgroundMountRevision, renderedActiveWorktreeId]`; deferral planning mutates a ref, not state.
- src/renderer/src/components/terminal-cold-activation.ts:96-120 — `planColdActivationTabDeferral` runs in the render body, writes `activationDeferredMountTabIdsByWorktreeRef.current`, no `setBackgroundMountRevision`.
- src/renderer/src/components/use-terminal-workspace-foundation.ts:29-30 — `renderedActiveWorktreeId = activeWorktreeId`, restored before the gate opens and stable thereafter.
- src/renderer/src/components/use-terminal-parking-foundation.ts:93-101 — `backgroundMountRevision` only bumps via `applyBackgroundMount` ← background-mount IPC.

## Required outcome
- The effect must re-run once deferral is planned during startup hydration so the launch-active worktree's hidden tabs are admitted on idle frames.

## Open questions for the human (optional)
- Was the intended trigger `backgroundMountRevision` bumping on the visible pane's mount? That path never fires for the visible pane (all `requestBackgroundTerminalWorktreeMount` call sites target hidden/background tabs).

// Judging on the high-water mark is what lets that plan still be admitted,
// while an over-cap worktree stays ineligible as its set drains.
it('judges eligibility on the largest deferred set seen, not the latest', () => {
const highWaterMark = (counts: readonly number[]): number =>

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.

This test reimplements the high-water mark with a local highWaterMark reduce and then feeds it to the pure isActivationAdmissionEligible — it never exercises the hook's actual Math.max accumulation or its previous?.worktreeId !== worktreeId reset in use-activation-deferred-tab-admission.ts:50-55. It would still pass if the hook regressed to judging the live count. Extract the high-water-mark computation into a testable pure function (e.g. nextActivationAdmissionMaxDeferredCount(previous, worktreeId, count)) and assert on that, or add a renderHook test that drives the effect across an empty → planned deferred set.

…et off CI

CI failed with 'revealed terminal never restored its content': the harness
sampled a fixed 4s window, which a shared runner can outlast, so a slow restore
was recorded as no restore. Poll for the restore instead.

Also stop asserting a latency budget on CI. Shared runners cannot hold a
threshold; the structural invariants (one pane mounted by the switch, warm set
restored) are exact and stay asserted everywhere.
@nwparker
nwparker merged commit 5fa62fe into main Sep 11, 2026
4 checks passed

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

ℹ️ No critical issues in this test-only delta — one minor suggestion inline.

Reviewed changes

  • Content-restore polling — measureSwitch now polls contentRestoredMs (30s timeout) instead of a fixed 4s wait, so a slow runner reports the real restore time rather than a false "never restored".
  • CI-scoped latency budget — the FIRST_PAINT_BUDGET_MS assertion now returns early on process.env.CI, leaving the structural invariants (mountedAtActivation === 1, warm-set restore) as the CI guards.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

// Why CI is exempt from the budget and not from the invariants: shared
// runners cannot hold a latency threshold, but "the switch mounted one pane"
// and "the warm set came back" are exact and are the real regression guards.
if (process.env.CI) {

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.

Exempting CI removes the latency budget from every automated run, so a regression that keeps the switch at one pane but slows the restore is now only caught by a human running this spec locally. The mountedAtActivation === 1 invariant guards the fan-out, not latency. Since your headless "before" (299–744 ms) already exceeds the 250 ms budget, a CI-scaled budget would still catch that while tolerating shared-runner variance.

Technical details
# Latency budget is unenforced in CI

## Affected sites
- tests/e2e/worktree-switch-first-paint.spec.ts:473-476 — `if (process.env.CI) { ... return }` skips `expect(median(restored)).toBeLessThanOrEqual(FIRST_PAINT_BUDGET_MS)`.

## Required outcome
- Decide whether the latency budget should retain any automated guard (e.g. `process.env.CI ? FIRST_PAINT_BUDGET_MS * 4 : FIRST_PAINT_BUDGET_MS`) rather than dropping it entirely on CI.

nwparker added a commit that referenced this pull request Sep 11, 2026
…the main merge

#20034 replaced connect-pane-pty's inline tab resolution with
findTerminalTabForPane, and this branch had rewritten the line below it to read
the recovery epoch off the row that block used to bind. The merge was textually
clean and semantically broken: `terminalTab` no longer existed, so typecheck
failed and every test that connects a pane threw ReferenceError.

Resolve the row once through the new helper and feed both epochs from it, which
keeps #20034's refactor and this branch's reason for reading the row here — a
second lookup would put another tabsByWorktree scan on the connect path.

captureTabRecoveryGeneration is narrowed to the one field it reads so the
helper's record type can carry it.
nwparker added a commit that referenced this pull request Sep 11, 2026
…on observed outcome (#20025)

* fix(terminal): move the recovery ledger onto the tab row and gate it on outcome

The recovery budget lived in module-level Maps keyed by tabId. Anything keyed
outside the row needs a release path, and that release fired on every
remount-driven pane disposal, so each remount erased the budget it had just
consumed (crash b5cfc6ca). Put the ledger on TerminalTab and write it in the
same set() as the generation bump: reading the budget is now reading the tab,
so releasing it independently has no expression.

Counting was also the wrong control. Every remount mounts a pane that captures
a FRESH recovery epoch, so the epoch check can never refuse its request —
recovery re-requested the exact action that had just failed with no evidence
anything changed. Gate on an observed outcome instead, reusing the direct-SSH
pane retry vocabulary (success | failed | timed-out | superseded) and its
settle call sites: an unsettled attempt blocks the next one, and a settled
failure refuses the same reason until a new trigger arrives (generation move,
or the user's Retry). The 3-per-5min cap stays as a breadcrumb-emitting
backstop, not the control.

viewMode now also lands on the row from the local toggles, mirroring how pin
already does it, so the chat-ownership guard reads one index instead of OR-ing
two.

* fix(terminal): persist the row's viewMode and keep both chat-ownership reads

The narrowed chat-ownership guard read a field the session schema strips:
terminalTabSchema never declared viewMode, so the terminal row lost it on every
load while the unified tab kept it. After a restart the row read undefined and
recovery would remount a chat-owned tab's hidden surface — the race #19745's
guard exists to prevent.

Declare viewMode on terminalTabSchema so the row is durable, and keep the
disjunction rather than replacing it. The schema cannot retroactively add the
field to sessions already on disk, so the first load after upgrade still has it
only on the unified tab; and for a safety check over two partly-redundant
sources, a hole in either index should err toward declining a heal.

Also cover three structural guards that no test was holding: both remote
ledger-carry paths (terminal-build, remote-workspace-session-merge) and the
only success settle in the state machine, including its placement past the
failure branches.

* fix(terminal): settle a fresh spawn's outcome and prove the ownership guard across a reload

spawn-left-pane-unbound was the one recovery reason with no success settle:
its remount heals by spawning, not reattaching, so it reached none of the
reattach settle points and left the attempt 'pending' for the full 31s bound.
A fresh spawn that binds a PTY now reports it, the dual of the unbound settle
that already reported failure.

Two tests outside src/ still called remountTerminalTabForRecovery by its old
boolean contract and broke CI; both are updated to the admission result.

Also strips the client-local recovery ledger at the remote-workspace projection
boundary, in the type as well as the destructure, so a future producer cannot
put another machine's Date.now() on the wire.

* fix(terminal): resolve the pane's tab row once for both epochs after the main merge

#20034 replaced connect-pane-pty's inline tab resolution with
findTerminalTabForPane, and this branch had rewritten the line below it to read
the recovery epoch off the row that block used to bind. The merge was textually
clean and semantically broken: `terminalTab` no longer existed, so typecheck
failed and every test that connects a pane threw ReferenceError.

Resolve the row once through the new helper and feed both epochs from it, which
keeps #20034's refactor and this branch's reason for reading the row here — a
second lookup would put another tabsByWorktree scan on the connect path.

captureTabRecoveryGeneration is narrowed to the one field it reads so the
helper's record type can carry it.
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