Skip to content

perf(terminal): defer cold worktree activation tab mounts until first reveal - #8597

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/workspace-slow-startup-agent
Jul 14, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/workspace-slow-startup-agent

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Activating a worktree mounts a TerminalPane for every saved terminal tab in one render pass. Each mount replays scrollback through xterm, attaches a WebGL renderer, runs synchronous fit/reflow, and issues a sync-IPC scrollback read — so a worktree with many agent-session tabs freezes the renderer for tens of seconds.

Field evidence from the trace log (main.trace.ndjson): activating a 12-tab review worktree produced 222 terminal_replay_guard_wedged_release breadcrumbs in one minute — replay-guard stall timers all firing ~20s late, the post-mortem signature of a renderer main thread pegged through the whole activation. The un-ACKed replays also trip the restore-marker feedback loop, which re-fetches and re-replays main-buffer snapshots at ~4/sec into panes that are still parsing, compounding the freeze. Bursts of ~100 simultaneous daemon PTY attaches accompany activations of the largest worktrees.

ELI5

Before this change, opening a worktree with lots of saved terminal or agent tabs was like turning on every TV in a house at the same time. Even though only one tab was visible, Orca rebuilt every hidden terminal, replayed its scrollback, laid it out, and attached its renderer all at once. That burst could temporarily pin the renderer and appear as intermittent UI lag or a long freeze.

After this change, Orca starts only the terminal tabs that are visible or immediately required. The other eligible local terminals stay safely parked and load when first opened. Small worktrees behave as before, and remote or uncertain hosts still mount eagerly for safety. The first reveal of a deferred tab can still take its normal bounded restore cost, but the large all-tabs-at-once activation spike is removed.

Why this is the standard architectural fix rather than a hack:

  • It changes scheduling, not terminal semantics. Orca already has targeted background mounting, parked watchers, on-demand reveal, and a parking kill switch. This change composes those existing lifecycle primitives instead of inventing a second terminal implementation.
  • It is capability-based and conservative. Deferral is allowed only for a positively identified local host with a snapshot-backed daemon PTY and watcher coverage, and only when more than four tabs would mount. Anything uncertain, remote, visible, live, or immediately required stays eager.
  • It adds no arbitrary sleeps, polling loop, protocol shortcut, or fake terminal state. The PTY keeps running under the existing daemon; only the expensive renderer view is delayed. Reveal follows the same mount and reattach path used elsewhere.
  • Cleanup follows normal ownership rules. Stale React cleanup removes registrations only when it still owns them, so a replacement pane cannot be deleted by an older effect.
  • The abstraction boundaries are tested. Pure policy tests cover eligibility, lifecycle tests cover ownership and cleanup, and Electron journeys exercise the real local-daemon and Linux SSH paths end to end.

We tested both the immediate and eventual reopen paths:

  • Needed immediately: after a renderer reload, the visible local terminal still mounts immediately. Tabs with pending startup work or other safety requirements are also never deferred. Remote and unresolved hosts remain eager by design; the Docker/Linux SSH test restored all 6 terminals immediately with the same 6 PTY identities.
  • Opened later: every deferred local terminal keeps a lightweight parked watcher, so exits and important side effects are still handled while no view is mounted. The Electron test proves deferred tabs do not silently mount on a timer, opens one on demand, verifies its watcher hands ownership back to the real pane, runs a command through it, and observes the expected terminal output.
  • Regression safety: 497 targeted terminal close, retirement, PTY, parking, and restore tests passed, along with both local and real SSH Electron journeys.

This directly addresses the reported intermittent lag when activating terminal-heavy worktrees. It does not claim to fix unrelated lag from other parts of the app.

Fix

Cold activations now mount only the tabs the user can see, plus tabs that must mount:

  • the active tab (global and per-worktree remembered), each split group's active tab (group.activeTabId is a unified-tab id — mapped to the terminal entity id), activity-portal tabs, and tabs with a queued startup (pendingStartupByTabId);
  • tabs that are already live (registered TerminalPanes are never narrowed);
  • tabs the parked byte watchers cannot cover (canWatcherCoverParkedTerminalTab) — deferring those would drop bell/title/completion side effects, so they mount eagerly.

Every other tab defers like a cold-parked tab from birth: no view until first reveal. While deferred, the existing parked byte watchers own exit handling and side effects — wired in both hosts (the legacy watcher reconciliation effect and useTerminalTabColdParking via a new deferredMountTabIds arg). The restriction reuses the targeted-background-mount mechanism (backgroundMountTabIdsByWorktreeRef), grows on each reveal, and lifts once every tab has been revealed.

pendingActivationSpawn is deliberately not an immediate-mount trigger: session hydration blanket-marks every persisted tab with it, so honoring it would disable deferral for the exact scenario it targets (the new e2e caught this). A deferred tab's reveal consumes the flag exactly like an activation mount would — just later. Sleep/wake respawn flows go through targeted background mounts and are unaffected.

Deferral only engages when more than 4 tabs would mount cold, and only while hidden-view parking is enabled — small worktrees and the parking kill switch keep today's behavior exactly.

Verification

  • New e2e terminal-cold-activation-deferral.spec.ts reproduces the field scenario: child worktree, 8 tabs with live daemon PTYs, renderer reload so persisted tabs hydrate cold. Asserts: only the visible tab mounts, deferred tabs stay unmounted (no late timer mounts), every deferred tab has parked byte-watcher coverage, and revealing a deferred tab mounts it on demand. This spec failed against two earlier iterations of the change (caught the pendingActivationSpawn blanket flag and the primary-vs-child worktree coverage rule) before passing.
  • e2e: terminal-sleep-wake-restore, terminal-hidden-view-parking, worktree-lifecycle, tab-close-navigation all pass.
  • 2,100+ unit tests across terminal/ + terminal-pane/ pass, including 7 new tests for the deferral policy.
  • tsc, oxlint, and react-doctor clean on all touched files.

Known limits

  • Deferral requires snapshot-backed daemon PTYs (repoId::path session ids), so primary-worktree tabs are conservatively never deferred — same rule as per-tab parking.
  • A deferred tab's daemon session is not attached until reveal, so PTY-byte-driven side effects (bells, OSC titles) are silent until first shown — the same baseline as tabs of a never-visited worktree. Agent status still flows through hooks.
  • The legacy (non-split) host still remounts all tabs when returning to a worktree parked at the worktree level; per-tab parking covers returns in the split host.
  • First click on a deferred tab pays its mount + bounded restore (~100–300ms), the same cost a parked-tab reveal pays today.

Tests

  • pnpm run typecheck
  • pnpm run lint (existing unrelated warnings only; reliability/max-lines/localization gates passed)
  • git diff --check and merge-conflict checks
  • 497 targeted terminal close, retirement, PTY, and restore tests passed on the final merged tree
  • Local cold-activation Electron e2e passed: eligible hidden local terminals defer and reveal on demand
  • Docker/Linux SSH Electron e2e passed: 6/6 original PTYs restored, 6/6 managers mounted, no SSH tabs parked, and restored input reached the remote proof file
  • Latest main merged; GitHub reports the PR as mergeable
  • A fresh field before/after latency trace was not collected; the deterministic policy and Electron journeys validate removal of the all-tabs-at-once activation path

… reveal

Activating a worktree mounted a TerminalPane for every saved terminal tab
in one render pass. Each mount replays scrollback through xterm, attaches
a WebGL renderer, and issues a sync-IPC snapshot read, so a worktree with
many agent-session tabs froze the renderer for tens of seconds (field
trace: 200+ replay-guard stall releases inside one activation window,
plus restore-marker feedback loops re-fetching snapshots at ~4/sec).

Cold activations now mount only the tabs the user can see (active tab,
each split group's active tab, activity-portal tabs, pending spawns) plus
tabs that are already live or that parked byte watchers cannot cover.
Every other tab defers like a cold-parked tab from birth: no view until
first reveal, with the parked byte watchers owning bell/title/completion
side effects meanwhile. The restriction reuses the targeted background
mount mechanism and lifts once every tab has been revealed.

Deferral only engages when more than four tabs would mount cold, and only
while hidden-view parking is enabled, so small worktrees and the parking
kill switch keep today's behavior.
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Terminal activation now defers selected tab mounts and reveals them as tabs become visible. Parked watchers provide coverage and optional title restoration for deferred tabs. PTY reconnect and exit handling now buffer live data, suppress duplicate exits, coordinate primary and sidecar callbacks, and avoid respawning sessions that exited before attachment. Watcher disposal, terminal close callbacks, pinned-tab confirmation queuing, worktree removal cleanup, SSH startup reconnect, host resolution, and registration cleanup were also updated.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed, but it does not follow the required template and omits Summary, Screenshots, AI Review Report, Security Audit, and Notes. Rewrite it using the repo template with Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections.
✅ Passed checks (3 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 summarizes the main change: deferring cold worktree terminal mounts until first reveal.

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

Caution

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

⚠️ Outside diff range comments (1)
src/renderer/src/components/Terminal.tsx (1)

1070-1136: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Include the deferral inputs in the watcher-sync deps. groupsByWorktree, activeTabIdByWorktree, and pendingStartupByTabId feed the render-body immediateTabIds / revealActivationDeferredTabs path, so leaving them out can delay legacy parking reconciliation until some unrelated dependency changes. src/renderer/src/components/Terminal.tsx:1122-1136


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1a00c1a1-751e-4ec1-810f-3039814d9eed

📥 Commits

Reviewing files that changed from the base of the PR and between 9a23792 and 8abf6ee.

📒 Files selected for processing (6)
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.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/runtime/sync-runtime-graph.ts

… past hydration's blanket spawn flag

The new e2e (child worktree, 8 tabs, renderer reload against live daemon
sessions) caught the deferral never engaging: session hydration marks
every persisted tab pendingActivationSpawn, and treating that flag as
must-mount-now put all tabs in the immediate set. Only explicit queued
startups (pendingStartupByTabId) mount eagerly; a deferred tab's reveal
consumes the hydration flag exactly like an activation mount would.
Sleep/wake respawn flows go through targeted background mounts and are
unaffected (terminal-sleep-wake-restore passes).

The spec asserts the visible tab mounts, deferred tabs stay unmounted
with parked byte-watcher coverage, and a revealed tab mounts on demand.

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

Caution

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

⚠️ Outside diff range comments (1)
src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts (1)

254-284: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

restoreTitleOnRegister is skipped in byte-parser mode. src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts:265-284 forwards this only through registerTerminalSideEffectFactConsumer(), so when mainSideEffectAuthority is off the flag does nothing. That leaves cold-started parked tabs without a title snapshot, and their title can stay blank/stale until fresh bytes arrive. Add a byte-parser fallback or gate the option to main-authority-only parks.

🧹 Nitpick comments (1)
tests/e2e/terminal-cold-activation-deferral.spec.ts (1)

62-79: 🧹 Nitpick | 🔵 Trivial

Confirm child worktree cleanup after this test.

The test creates a new child worktree (e2e-cold-defer-${Date.now()}) but the spec has no visible teardown removing it. If the orca-app fixture doesn't reset repo/worktree state between runs, repeated CI runs will accumulate orphaned worktrees on disk.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3dabc3a7-484b-4f3a-88b2-10d05e34aa84

📥 Commits

Reviewing files that changed from the base of the PR and between 8abf6ee and 0659d7b.

📒 Files selected for processing (8)
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts
  • src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.ts
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
  • tests/e2e/terminal-cold-activation-deferral.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
  • src/renderer/src/components/Terminal.tsx

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Follow-up hardening fixes are pushed in commit 2fee0a71d.

What was fixed:

  • Kept cold-activation deferral limited to tabs with valid parked-watcher coverage; newly added, live, remote, or no-PTY tabs mount immediately when they cannot be safely deferred.
  • Corrected parked watcher ownership across targeted background mounts, reveal/unmount transitions, split panes, and worktree removal.
  • Hardened PTY exit delivery: one-shot primaries, complete sidecar fanout, duplicate suppression, exception safety, and correct handling of exits that arrive before or during attach.
  • Preserved terminal output ordering by rendering authoritative reattach snapshots before post-snapshot live bytes, with a bounded deferred-data queue and dropped-output recovery.
  • Prevented dead same-ID sessions from respawning/orphaning fresh shells; removed sessions now use time-bounded data/exit tombstones and mint fresh PTY IDs on later reconnect.
  • Fixed sole-tab and multi-leaf parked exits, including final-frame retention, dead-leaf collapse, and cleanup when a worktree is explicitly removed.
  • Routed overlay close and exit paths through pinned-tab confirmation, delayed leave-worktree cleanup until an actual close, queued concurrent confirmations safely, and guarded rapid double activation.
  • Added regression coverage for activation deferral, background ownership, buffered exit/data races, reconnect ordering, pinned close cancellation/confirmation, split layouts, and delayed worktree-removal exits.

Validation on the pushed commit:

  • 168 test files / 2,285 tests passed
  • Web TypeScript check passed
  • Full oxlint completed with no errors
  • Max-lines and reliability gates passed
  • git diff --check passed

@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 (4)
src/renderer/src/components/Terminal.tsx (1)

1062-1083: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Guard the per-render coverage-check loop once deferral has fully resolved.

On every render of an already-active worktree with coldActivationDeferralEnabled === true, the loop over worktreeTabs calling canWatcherCoverParkedTerminalTab for every tab (lines 1071-1075) runs unconditionally — even after revealActivationDeferredTabs has nothing left to do because the worktree's deferred entry was already cleared. Skipping the loop (and the revealActivationDeferredTabs call) when activationDeferredMountTabIdsByWorktreeRef.current has no entry for renderedActiveWorktreeId would avoid repeated per-tab work in the common steady state.

♻️ Suggested guard
     } else {
       // Why: tabs added after activation never passed the original coverage
       // gate. Uncoverable/no-PTY tabs must mount now so they can spawn or keep
       // their non-snapshot-backed live transport.
-      for (const tab of worktreeTabs) {
-        if (!canWatcherCoverParkedTerminalTab(renderedActiveWorktreeId, tab)) {
-          immediateTabIds.add(tab.id)
+      if (activationDeferredMountTabIdsByWorktreeRef.current.has(renderedActiveWorktreeId)) {
+        for (const tab of worktreeTabs) {
+          if (!canWatcherCoverParkedTerminalTab(renderedActiveWorktreeId, tab)) {
+            immediateTabIds.add(tab.id)
+          }
         }
+        revealActivationDeferredTabs({
+          restrictions: backgroundMountTabIdsByWorktreeRef.current,
+          deferredMountTabIdsByWorktree: activationDeferredMountTabIdsByWorktreeRef.current,
+          worktreeId: renderedActiveWorktreeId,
+          allTabIds: worktreeTabs.map((tab) => tab.id),
+          immediateTabIds
+        })
       }
-      revealActivationDeferredTabs({
-        restrictions: backgroundMountTabIdsByWorktreeRef.current,
-        deferredMountTabIdsByWorktree: activationDeferredMountTabIdsByWorktreeRef.current,
-        worktreeId: renderedActiveWorktreeId,
-        allTabIds: worktreeTabs.map((tab) => tab.id),
-        immediateTabIds
-      })
     }
src/renderer/src/components/terminal-pane/pty-exit-delivery.ts (1)

36-45: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Silently dropped sidecar errors beyond the first.

for (const sidecar of delivery.sidecars) { try { sidecar(delivery.code, { hadPrimary: delivery.primary !== undefined }) } catch (error) { if (!hasError) { firstError = error hasError = true } } } Only the first error across primary+sidecars is ever surfaced; any second/third sidecar failure is discarded with no trace at all. If two exit observers regress simultaneously, one failure disappears silently instead of being logged (unlike the analogous cleanup-failure path in pty-transport.ts's registerPtyExitHandler, which logs via console.error).

🔍 Proposed fix to log swallowed secondary errors
   for (const sidecar of delivery.sidecars) {
     try {
       sidecar(delivery.code, { hadPrimary: delivery.primary !== undefined })
     } catch (error) {
       if (!hasError) {
         firstError = error
         hasError = true
+      } else {
+        console.error('[pty] exit sidecar failed after a prior error', error)
       }
     }
   }
src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts (1)

49-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Rename the discard-spy to match what it actually tests.

const consumePreHandlerPtyState = vi.fn() vi.mock('./pty-pre-handler-buffer', () => ({ discardPreHandlerPtyState: (ptyId: string) => consumePreHandlerPtyState(ptyId) })) This spy is wired to discardPreHandlerPtyState, not the real consumePreHandlerPtyState export, yet every assertion in this file (e.g. expect(consumePreHandlerPtyState).toHaveBeenCalledWith(PTY_ID)) reads as if it verifies the latter. This is confusing when a test fails and someone traces the wrong production function.

✏️ Proposed rename
-const consumePreHandlerPtyState = vi.fn()
+const discardPreHandlerPtyStateSpy = vi.fn()
 vi.mock('./pty-pre-handler-buffer', () => ({
-  discardPreHandlerPtyState: (ptyId: string) => consumePreHandlerPtyState(ptyId)
+  discardPreHandlerPtyState: (ptyId: string) => discardPreHandlerPtyStateSpy(ptyId)
 }))

(and update every expect(consumePreHandlerPtyState) call-site accordingly)

src/renderer/src/components/terminal-pane/pty-connection.test.ts (1)

7872-7898: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test mocks around the real synchronous exit dispatch instead of exercising it.

This test's mock calls callbacks.onData(...) then resolves { id, exitedBeforeAttach: true } directly, bypassing the real createIpcPtyTransport + pre-handler-buffer path that actually produces this result (see pty-transport.ts, which synchronously drains a buffered exit and invokes onPtyExit — i.e. this pane's own onExit() — before connect() resolves). Consolidated with the ordering concern raised in pty-connection.ts.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b66da4b8-2f2b-419e-8a74-24365d2214d8

📥 Commits

Reviewing files that changed from the base of the PR and between 0659d7b and 2fee0a7.

📒 Files selected for processing (25)
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-dispatcher-pi-routing.test.ts
  • src/renderer/src/components/terminal-pane/pty-dispatcher.ts
  • src/renderer/src/components/terminal-pane/pty-exit-delivery.ts
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.test.ts
  • src/renderer/src/components/terminal-pane/pty-pre-handler-buffer.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-watcher-registry.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-watcher-registry.ts
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.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/terminal-tab-actions.test.ts
  • src/renderer/src/components/terminal/terminal-tab-actions.ts
  • src/renderer/src/store/slices/pinned-tab-close-confirm.test.ts
  • src/renderer/src/store/slices/pinned-tab-close-confirm.ts
  • src/renderer/src/store/slices/worktrees.ts
  • tests/e2e/terminal-cold-activation-deferral.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
  • src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts
  • tests/e2e/terminal-cold-activation-deferral.spec.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Merged current main, resolved the pty-connection conflict, and pushed the regression fixes in 4eb58df.

Fixed:

  • startup now publishes the authoritative state returned by SSH connect before persisted terminal reconnect runs
  • cold activation deferral is limited to positively resolved local execution hosts; SSH, remote-runtime, and unresolved hosts mount eagerly
  • stale React cleanup can no longer unregister a replacement runtime terminal or remove its replacement PaneManager probe
  • retained both sides of the pty-connection conflict: live-data deferral and the in-flight transport recovery guard
  • added a Docker/Linux SSH renderer-reload regression covering six relay-backed terminals and recorded the coverage in the reliability gate

Validation:

  • 475 focused Vitest tests passed across six files
  • pnpm run typecheck passed
  • pnpm run lint passed (pre-existing warnings only)
  • local cold-activation Electron E2E passed
  • Docker/Linux SSH Electron E2E passed: 6/6 original PTYs restored, 6/6 managers mounted, 0 parked SSH tabs, and restored input wrote the expected proof file on the remote host
  • git diff checks and merge-conflict checks passed

One Docker startup attempt hit an sshd readiness flake before the test began; the clean retry and final instrumentation-free run both passed.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Follow-up: main advanced again after the first push, including terminal session retirement changes. I merged the new tip and resolved the three close-path conflicts in 838450d, preserving both pinned-close callbacks and the new PTY-exit retirement metadata.

Revalidated on the final merged tree:

  • 497 targeted terminal close/retirement/PTY tests passed
  • typecheck and full lint passed
  • local cold-activation Electron E2E passed
  • Docker/Linux SSH reload E2E passed again with all six original PTYs restored and remote input working
  • origin/main is now an ancestor of the PR head.

@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

Run ID: 1db6a2cb-5105-4888-a083-c7d12fa89688

📥 Commits

Reviewing files that changed from the base of the PR and between 2fee0a7 and 4eb58df.

📒 Files selected for processing (17)
  • config/reliability-gates.jsonc
  • src/renderer/src/App.tsx
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.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/lib/resolved-worktree-execution-host.test.ts
  • src/renderer/src/lib/resolved-worktree-execution-host.ts
  • src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts
  • src/renderer/src/runtime/sync-runtime-graph.ts
  • src/renderer/src/startup/ssh-startup-reconnect.test.ts
  • src/renderer/src/startup/ssh-startup-reconnect.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts
  • src/renderer/src/components/terminal/background-terminal-worktree-mount.ts
  • src/renderer/src/components/Terminal.tsx

Comment thread config/reliability-gates.jsonc Resolved
@brennanb2025
brennanb2025 merged commit 9d51732 into main Jul 14, 2026
2 of 3 checks passed
Jinwoo-H added a commit that referenced this pull request Jul 16, 2026
… they don't render blank (STA-1840) (#8811)

* fix(mobile): background-mount never-mounted terminals on subscribe so they don't render blank (STA-1840)

A mobile terminal.subscribe to a tab the desktop never mounted this session —
a workspace the desktop isn't currently showing, a cold-activation-deferred tab
(#8597), or a cold-parked tab — has no attached PTY, so the runtime has no
headless emulator and the initial snapshot is empty. The mobile terminal then
renders blank (repro: on the phone, scroll to an old workspace whose terminals
the desktop unmounted; they stay blank).

When a mobile subscribe hits an empty snapshot (or resolves no PTY), the runtime
now asks the renderer to background-mount that tab so the PTY attaches and the
live data stream — already subscribed on that path — delivers its output.

A never-mounted workspace has no renderer-graph leaf, so its terminals are
surfaced to mobile via synthetic pty:<ptyId> handles that carry no real UI
tabId. The runtime passes the ptyId through the mount request and the renderer
resolves the owning tab from the persisted tab model (resolveTerminalTabIdForPtyId),
falling back to a whole-worktree background mount if it cannot. The request is
idempotent for already-mounted tabs and never unmounts a live pane, so the worst
case is the same blank as before — no regression.

Validated on an iOS simulator with a two-workspace desktop: opening the
workspace the desktop was not showing rendered a fully blank terminal without
the fix and the live shell prompt with it.

Tests: runtime mount-request gating (real-tab / pty-form / no-ptyId / unknown),
subscribe-handler empty-snapshot-vs-content, and the ptyId->tabId resolver; all
608 RPC method tests pass.

* test(mobile): mock onRequestTerminalTabMount in useIpcEvents tests (fixes CI for #8811)

* fix(mobile): harden blank terminal recovery mounts

* perf(mobile): avoid redundant terminal recovery mounts

* fix(mobile): ignore stale terminal mount requests

* fix(mobile): skip recovery mounts for closed streams

* fix(mobile): reject ambiguous terminal mount ownership

* fix(mobile): preserve terminal handle through recovery mount

* fix(mobile): recover legacy terminal history safely

---------

Co-authored-by: Jinwoo-H <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… reveal (stablyai#8597)

* perf(terminal): defer cold worktree activation tab mounts until first reveal

Activating a worktree mounted a TerminalPane for every saved terminal tab
in one render pass. Each mount replays scrollback through xterm, attaches
a WebGL renderer, and issues a sync-IPC snapshot read, so a worktree with
many agent-session tabs froze the renderer for tens of seconds (field
trace: 200+ replay-guard stall releases inside one activation window,
plus restore-marker feedback loops re-fetching snapshots at ~4/sec).

Cold activations now mount only the tabs the user can see (active tab,
each split group's active tab, activity-portal tabs, pending spawns) plus
tabs that are already live or that parked byte watchers cannot cover.
Every other tab defers like a cold-parked tab from birth: no view until
first reveal, with the parked byte watchers owning bell/title/completion
side effects meanwhile. The restriction reuses the targeted background
mount mechanism and lifts once every tab has been revealed.

Deferral only engages when more than four tabs would mount cold, and only
while hidden-view parking is enabled, so small worktrees and the parking
kill switch keep today's behavior.

* test(terminal): prove cold-activation deferral end-to-end; unblock it past hydration's blanket spawn flag

The new e2e (child worktree, 8 tabs, renderer reload against live daemon
sessions) caught the deferral never engaging: session hydration marks
every persisted tab pendingActivationSpawn, and treating that flag as
must-mount-now put all tabs in the immediate set. Only explicit queued
startups (pendingStartupByTabId) mount eagerly; a deferred tab's reveal
consumes the hydration flag exactly like an activation mount would.
Sleep/wake respawn flows go through targeted background mounts and are
unaffected (terminal-sleep-wake-restore passes).

The spec asserts the visible tab mounts, deferred tabs stay unmounted
with parked byte-watcher coverage, and a revealed tab mounts on demand.

* fix(terminal): harden deferred activation lifecycle

* docs(reliability): correct SSH startup assertion evidence
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… they don't render blank (STA-1840) (stablyai#8811)

* fix(mobile): background-mount never-mounted terminals on subscribe so they don't render blank (STA-1840)

A mobile terminal.subscribe to a tab the desktop never mounted this session —
a workspace the desktop isn't currently showing, a cold-activation-deferred tab
(stablyai#8597), or a cold-parked tab — has no attached PTY, so the runtime has no
headless emulator and the initial snapshot is empty. The mobile terminal then
renders blank (repro: on the phone, scroll to an old workspace whose terminals
the desktop unmounted; they stay blank).

When a mobile subscribe hits an empty snapshot (or resolves no PTY), the runtime
now asks the renderer to background-mount that tab so the PTY attaches and the
live data stream — already subscribed on that path — delivers its output.

A never-mounted workspace has no renderer-graph leaf, so its terminals are
surfaced to mobile via synthetic pty:<ptyId> handles that carry no real UI
tabId. The runtime passes the ptyId through the mount request and the renderer
resolves the owning tab from the persisted tab model (resolveTerminalTabIdForPtyId),
falling back to a whole-worktree background mount if it cannot. The request is
idempotent for already-mounted tabs and never unmounts a live pane, so the worst
case is the same blank as before — no regression.

Validated on an iOS simulator with a two-workspace desktop: opening the
workspace the desktop was not showing rendered a fully blank terminal without
the fix and the live shell prompt with it.

Tests: runtime mount-request gating (real-tab / pty-form / no-ptyId / unknown),
subscribe-handler empty-snapshot-vs-content, and the ptyId->tabId resolver; all
608 RPC method tests pass.

* test(mobile): mock onRequestTerminalTabMount in useIpcEvents tests (fixes CI for stablyai#8811)

* fix(mobile): harden blank terminal recovery mounts

* perf(mobile): avoid redundant terminal recovery mounts

* fix(mobile): ignore stale terminal mount requests

* fix(mobile): skip recovery mounts for closed streams

* fix(mobile): reject ambiguous terminal mount ownership

* fix(mobile): preserve terminal handle through recovery mount

* fix(mobile): recover legacy terminal history safely

---------

Co-authored-by: Jinwoo-H <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant