fix(terminal): bound SSH & remote hidden-worktree terminal retention (C1) (#10625)

* fix(terminal): park SSH worktrees like local ones (C1 retention, slice A)

SSH ptys were blanket-excluded from hidden-view parking, so a hidden SSH
worktree retained every pane forever (C1: renderer heap climbs to the V8
ceiling). SSH bytes transit local main — fact-mode watchers already cover
them, and main keeps a headless model served over pty:getMainBufferSnapshot
that the SSH reattach path never consulted.

- isParkRestorableTerminalPty: snapshot-backed OR (SSH + policy); threaded
  through both park verdicts, both selectors, watcher coverage, and the
  watcher start guard. Remote-runtime/fail-open/foreign/null unchanged.
- Parked-SSH reveal paints from main's headless model (dimension-matched,
  ~5k rows) and degrades to the relay 100KiB replay unless the snapshot is a
  non-empty source==='headless' payload — never a blank/stale paint.
- Kill switch: settings.terminalSshViewParking (default on).

DESIGN.md records the approved plan and the H1 magnitude non-claim.

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): bound hidden-worktree retention with a force-park budget (C1, slice B)

Un-parkable worktrees (remote-runtime ptys, uncoverable tabs, SSH with the
slice-A switch off) had unlimited retention: the parking cap/TTL only ever
saw eligibility-passing worktrees, so one bad tab pinned a whole worktree's
panes forever. Retention is now memory-bounded, not eligibility-bounded.

- terminal-hidden-worktree-retention.ts: retention budget (12 hidden / 45min
  TTL, sized from the measured 2.5-19MB per-pane V8 cost, DESIGN.md §2) over
  hidden worktrees ordinary parking can never evict; reuses the hot-retain
  ranking so last-active exemption, deterministic ties, and deadline-driven
  rechecks hold. Fail-open/foreign-pty tabs are eviction-exempt (a remount
  would fresh-spawn and orphan the live shell).
- Terminal.tsx: force-parked ids join the parked set AFTER the coverage veto
  (darkness for uncoverable tabs is the accepted cost); buffers captured via
  the sleep-flow registry before the unmount render; retention TTL added to
  the recheck deadlines for budget candidates only.
- Verdict stays out of its own effect deps; policy test asserts idempotence
  and time-monotone membership (flip-loop dwell regression).
- Kill switch: settings.terminalHiddenWorktreeRetentionBudget (default on).

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): demote hidden scrollback for eviction-exempt worktrees (C1, slice C)

The retention budget (slice B) must exempt worktrees holding fail-open or
foreign-worktree ptys — a remount would fresh-spawn and orphan the live
shell — which would leave that class unbounded again. Instead, past the same
45min retention TTL their hidden panes drop to the minimum scrollback tier
(measured: ~19MB -> ~1.3MB V8 heap per 50k-row pane; trimmed history is
gone by design, reveal restores the configured cap for future output).

- terminal-hidden-scrollback-demotion.ts: module-state verdict registry
  (parked-watcher pattern) with content-equality notify damping; applied in
  the existing scrollback-rows effect in use-terminal-pane-lifecycle.
- selectScrollbackDemotedTerminalWorktrees: pure, TTL-gated, time-monotone.
- Retention TTL wakeups now also cover exempt worktrees so demotion fires.
- Kill switch: settings.terminalHiddenScrollbackDemotion (default on).

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): paint the SSH model snapshot inline, not via nested coordinator (C1 slice A fix)

applyMainBufferSnapshot runs its own structuralReplayCoordinator.run; calling
it from applyReattachPayload (already inside the coordinator when a relay
replay exists) deadlocks on the coordinator's tail chain. The model paint now
mirrors the daemon-snapshot branch inline (folded scrollback + rehydrate +
screen, dimension-matched, escape tail last) and arms the restored-snapshot
seq baseline so deferred/live chunks the snapshot covers dedupe instead of
double-painting. Also falls through (no early return) so reattachPayloadApplied
still latches. Adds the folder-workspace id parity unit case.

Co-authored-by: Orca <help@stably.ai>

* test(terminal): SSH park+reveal e2e round-trip + as-built design notes (C1)

Docker-gated (ORCA_E2E_SSH_DOCKER=1) spec: SSH tab parks behind a decoy and
reveal restores marker content at multi-viewport scrollback depth. DESIGN.md
records the as-built deltas (inline paint, force-park shape, last-active
floor) and the residuals so follow-ups aren't lost.

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): paint SSH reveal from main's model even when the relay replay is empty (C1 review #1)

A relay restart empties the replay buffer; the reveal previously painted
nothing even when main's headless model held the session. The reattach now
prefetches the model snapshot when no structural replay exists (SSH-shaped
ptys only) and paints it inside the coordinator; emptiness is judged on the
composed payload (scrollbackAnsi + data + pendingEscapeTailAnsi) so an
alt-screen snapshot with an empty screen frame still paints.

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): decouple scrollback demotion (slice C) from the retention-budget switch (C1 review #2)

Per the approved contract each slice reverts behind its own switch: slice C
now requires only the master terminalHiddenViewParking plus its own
terminalHiddenScrollbackDemotion flag. The TTL wakeup timer fires for
demotion candidates even with the budget switch off. No DEFAULT_SETTINGS
entries exist for sibling flags (defaults are the '!== false' optional
pattern), so no explicit defaults are added.

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): scope eviction exemption to the tab, not the worktree (C1 review #3)

One eviction-exempt tab (fail-open/foreign pty) previously vetoed force-park
for its whole worktree, pinning co-located remote-runtime tabs forever. The
worktree now force-parks while exempt tabs keep their mounted panes via a
per-tab exclusion mirroring the Activity-portal pattern (legacy watcher sync,
legacy render, and the overlay cold-parking hook). Ordinary parking is
untouched — a worktree with an exempt tab still cannot ordinary-park.
Slice C now also demotes exempt tabs' panes as soon as their worktree
force-parks under the count budget (they are the only panes left mounted).

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): demote un-parkable worktrees the force-park lever spared (C1 review #4)

The last-active exemption means a single hidden un-parkable worktree never
force-parks — and slice C previously only targeted exempt-tab worktrees, so
its panes held full scrollback forever. Demotion now also covers un-parkable
non-exempt worktrees past the retention TTL that are absent from the
force-parked set (last-active spared, or slice B switched off). Membership
stays time-monotone for fixed inputs; covered by new idempotence/monotone
selector tests.

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): keep the hidden clock running through transient background-measure windows (C1 review #5)

Whole-worktree background mounts (browser-automation bootstrap lease, mobile
mounts, agent wakes) open a ~3s self-clearing measure window that previously
deleted hiddenSince — every remount restarted the 30s hysteresis and the
45min retention TTL, so a periodically re-mounted force-parked worktree
never re-parked. The measure window still pauses parking/eviction verdicts
(all selectors skip measuring candidates); only the clock survives, so the
prior verdict resumes as soon as the window closes. Visible and
portal-holding worktrees still reset the clock.

Co-authored-by: Orca <help@stably.ai>

* test(terminal): make the SSH park+reveal depth assertion prove the model paint (C1 review #6a)

Pad the session with ~180KB of output after the numbered markers so the
earliest marker falls outside the relay's 100KiB rolling replay buffer while
staying inside main's ~5k-row headless model; asserting marker_1 after
reveal now proves the headless-model paint rather than passing under the
relay fallback.

Co-authored-by: Orca <help@stably.ai>

* docs(terminal): rewrite DESIGN.md as the single as-built C1 contract (review #7)

One contract matching the code: status IMPLEMENTED around force-park (not
the unmount proposal), real kill-switch names with coupling + revert
matrices, the true retention-floor formula with measured per-pane and
demotion numbers, an explicit when-OOM-is-still-possible paragraph naming
the H2 pendingSideEffects residual, the applyMainBufferSnapshot deadlock
constraint inside the slice-A section, stable-signal phrasing instead of a
capability latch, fail-open AND foreign-worktree exemption class, verified
cites, and a planned/landed/follow-up test matrix.

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): resolve the eviction exemption per pane, not per tab (C1 review #8)

isEvictionExemptTerminalTab read only tab.ptyId — the FIRST leaf's pty —
while the coverage veto that makes a worktree a retention candidate walks
every pane. A split tab whose second leaf held an unrestorable pty therefore
failed coverage (→ force-park target) yet looked exempt-free, so force-park
unmounted it and orphaned the live shell. The exemption now resolves panes
through the same resolveParkedTerminalPaneCandidates, keeping tab.ptyId in
the union for the no-layout/no-capture case.

Also from the same review round:
- force-park's capture passes includeLocalBuffers:false like every other
  shutdownBufferCaptures caller; it was serializing up to 512KB/pane of
  scrollback into the store inside a fix meant to bound renderer heap.
- Terminal.tsx unmount resets the scrollback-demotion registry — module
  state with no reset path, read by a pane effect that runs before the host
  effect that would clear it, so a stale verdict trimmed restore replays.
- memoize watcher coverage per tab within the parking pass; the retention
  candidates re-asked it for every mounted worktree, not just the parked few.

* docs(terminal): drop DESIGN.md — the as-built C1 contract moves to the PR body

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): cap the deferred PTY side-effect queue (C1 residual H2)

pendingSideEffects grew without bound under background timer throttling
(~64 drained/s vs hundreds queued/s overnight). Cap at 512 entries with
oldest-first eviction: titles drop (last-wins), a pending bell latches
onto the next survivor, agent-status payloads collapse onto the survivor
keeping the newest 16 (last-wins store state, KB-scale strings).

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): carry command-lifecycle facts through parked watchers (C1 follow-up)

Parked fact-mode watchers omitted onCommandFinished/onCommandCode*, so
OSC 133;D and Command Code scrape signals went dark while parked. New
parked-terminal-command-status.ts ports the store-level subset: git-UI
nudge on every command finish, same-turn status-row drop for SSH PTYs
(exact mounted-path parity — the foreground tracker refuses SSH ids),
and the Command Code working seed / 1500ms done settle. Byte mode scans
the same shared parsers for authority-off parity. Local-PTY status drops
stay with the mounted pane: they need pty-connection's process-confirm
ladder to tell a leaked nested-shell 133;D from a real agent exit.

Co-authored-by: Orca <help@stably.ai>

* test(terminal): retention-budget force-park e2e with a retentionLimit override (C1 6b)

ORCA_E2E_TERMINAL_RETENTION_LIMIT flows preload → e2e-config →
getTerminalParkingPolicyOverrides (exposeStore-gated, positive-integer
only) so a spec can shrink the force-park budget to 1. The Docker-gated
spec opens two remote worktrees on one relay target (second pre-seeded
remote repo), disables terminalSshViewParking to make both un-parkable,
hides both behind the local context, and proves the older one force-parks
while the last-active exemption spares the newest; re-activating the
evicted worktree restores the marker tail via relay replay.

Co-authored-by: Orca <help@stably.ai>

* test(terminal): retention-budget e2e via same-repo remote worktrees (passes docker lane)

The first draft added a second remote repo mid-session, whose pane pty
spawn misroutes to the local daemon with the remote cwd (pre-existing
multi-repo issue, reproducible without any retention override — a seeded
local repo plus one remote repo shows the same misroute). The spec now
budgets across three worktrees of the ONE connected repo, created through
the product createWorktree path (an external git-worktree-add only lands
as a detected worktree needing adoption) and polled through the relay's
transient post-connect reconnect window. Verified green on the local
Docker lane in 20.8s.

Co-authored-by: Orca <help@stably.ai>

* fix(terminal): prevent remount thrashing during post-measure cool-down (

Implements the C1 retention contract: preserve worktree `hiddenSinceMs` through a
background-measure window (so TTL/ranking stay honest), but re-park waits for a
full `coldParkDelayMs` cool-down after the measure ends. Without the cool-down,
every ~3s measure lease on a past-deadline worktree thrashes remount/reattach.

Core changes:
- Terminal.tsx: add measure clock (measuringTerminalWorktreeIdsRef) and post-measure
  cool-down tracking (terminalWorktreeParkCooldownUntilRef); gate parking candidates
  until cool-down expires.
- Extract snapshot replay choreography to shared terminal-snapshot-replay-paint.ts
  (used by SSH reattach + daemon restore paths).
- Add SSH model snapshot timeout (750ms) with fallback to relay replay.
- Move cold-park recheck deadline logic to terminal-cold-park-recheck-deadlines.ts;
  add cool-down deadline to scheduling.
- useTerminalTabColdParking: implement matching measure-clock contract with per-tab
  cool-down gate to keep tab deadlines synced with worktree retention clock.
- Add resolveTerminalMountScrollbackRows() to demote new xterms under demoted
  worktrees (pane births during demotion must take the demoted tier at create).
- Add kill switches: terminalSshViewParking, terminalHiddenWorktreeRetentionBudget,
  terminalHiddenScrollbackDemotion.

* fix(terminal): detect Command Code completion in parked mid-turn panes

Seed the byte watcher with in-flight turn state from agent status: the
watcher is recreated per park cycle with no startup command to arm it,
and the banner scrolled away before parking. Also memoize
eviction-exempt checks and use SSH PTY ID builder in tests.

* fix(terminal): flush pending command-code settles on reveal remount

When a parked pane reveals mid-Command Code turn, the new detector
cannot re-observe the already-passed idle composer. Cancelling the settle
leaves the row stranded at 'working', so dispose now flushes the pending
settle instead.

Extract readInFlightCommandCodeTurn to shared space and seed detectors
with in-flight turns so remounts complete mid-flight commands. Also
memoize SSH model probes to prevent double timeouts on reattach.

* fix(terminal): remove scrollback demotion (C1 slice C)

The scrollback demotion feature for eviction-exempt hidden worktrees is no longer needed. Retention budget limits are now sufficient without this additional bound. Remove the terminal-hidden-scrollback-demotion module, the selectScrollbackDemotedTerminalWorktrees function, and related per-pane demotion logic.

* test(terminal): assert bounded probe during stalled reveal

Add assertion to verify that a stalled reveal operation makes exactly one
`getMainBufferSnapshot` call, ensuring retry logic doesn't introduce
redundant probes that would extend the timeout window before relay fallback.

* fix(terminal): implement C1 retention budget for hidden parked worktrees

Addresses OOM regressions in hidden parked terminals by force-evicting
worktrees past a retention budget: at most 12 mounted while hidden, none
past 45 minutes (absolute, not exempted by last-active). Eviction is
least-recently-hidden-first. Exempt tabs (unrestorable local PTYs) keep
their panes to avoid orphaning shells; worktrees are force-parked even
if they contain exempts, and their buffers released elsewhere. SSH/remote
worktrees serialize buffers pre-eviction for reveal; local worktrees keep
daemon snapshots. Command Code's done-settle window is transferred across
park/reveal boundaries so the row cannot strand at 'working'. Model probe
on SSH reattach is scoped to park-reveal only, not ordinary reconnects.
Includes new E2E suite proving the budget actually releases memory.

* memoize eviction-exempt terminal tabs to avoid redundant store reads

Each tab's exemption check re-reads the store and walks the layout tree.
Introduce selectEvictionExemptTerminalTabIds() to resolve all exempt tabs
for a worktree in a single pass, then memoize the result in Terminal.tsx
and useTerminalTabColdParking. This prevents O(n) store reads when checking
exemptions across multiple tabs and ensures the set remains stable across
unrelated re-renders.

* refactor: reformat hidden-worktree retention comments

Reflow to 80-character lines and remove internal ticket references
(C1, C1 slice C).

* fix(lint): split overlay slot and eviction-exempt tabs under max-lines

Static analysis failed because TerminalPaneOverlayLayer (401) and
terminal-parked-tab-watchers (304) exceeded oxlint max-lines. Extract the
slot component and eviction-exempt helpers into dedicated modules.

* test(terminal): stabilize retention budget e2e control arm

Stage un-parkable remote pty ids only after both worktrees are hidden, and
keep re-staging during the control-arm poll so a late updateTabPtyId cannot
flip the decoy back to park-restorable and ordinary-park it before budget
engages.

* test(terminal): pin retention e2e decoy to a mounted pane snapshot

Use the active pane-identity snapshot for the decoy tab instead of all
worktree tabs, and re-assert un-parkable ids after the control-arm hold so
a deferred/empty tab id cannot fail the budget-off mounted-count check.

* fix: memoize terminal eviction exemptions on layout leaf PTYs

Splits add leaf panes to the layout store without changing the tabs
array. A memo keyed only on tabs misses this change, leaving new panes
unexempted for unmount. Include layout leaf PTYs in the exemption memo
key so it recalculates when splits occur or PTYs are re-minted.

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinjing
2026-07-29 00:47:18 -07:00
committed by GitHub
co-authored by Orca
parent e549dd3ef4
commit a7c8b8e071
59 changed files with 5003 additions and 614 deletions
+10 -1
View File
@@ -184,7 +184,9 @@ jobs:
name: ssh docker watcher isolation
needs: build
runs-on: ubuntu-latest
timeout-minutes: 20
# Why 35: the terminal parking + retention specs below add two more
# docker-rig tests capped at 240s each on top of the watcher isolation pair.
timeout-minutes: 35
steps:
- name: Checkout
@@ -227,6 +229,13 @@ jobs:
- name: Run Docker SSH watcher isolation E2E
run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:ssh-docker-watcher-isolation
# Why always(): these specs gate the C1 terminal parking/retention budget
# over a real SSH host and run in no other lane, so a watcher-isolation
# failure above must not silently skip them.
- name: Run Docker SSH terminal parking + retention E2E
if: always()
run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:ssh-docker-terminal-parking
- name: Upload watcher isolation traces
if: failure()
uses: actions/upload-artifact@v7
@@ -0,0 +1,45 @@
import { spawnSync } from 'node:child_process'
const rawExtraArgs = process.argv.slice(2)
const extraArgs = rawExtraArgs[0] === '--' ? rawExtraArgs.slice(1) : rawExtraArgs
const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
const env = {
...process.env,
ORCA_E2E_SSH_DOCKER: '1'
}
// Why: Node's CVE-2024-27980 hardening rejects .cmd spawns without shell on Windows.
const spawnOptions = {
stdio: 'inherit',
env,
shell: process.platform === 'win32'
}
const runtime = spawnSync(pnpm, ['run', 'ensure:electron-runtime'], spawnOptions)
if (runtime.status !== 0) {
process.exit(runtime.status ?? 1)
}
// Why both specs in one runner: they share the docker SSH rig and the same
// ORCA_E2E_SSH_DOCKER gate — the SSH parking spec proves SSH panes park and
// restore, the retention spec proves the C1 budget bounds what they retain.
const result = spawnSync(
pnpm,
[
'exec',
'playwright',
'test',
'tests/e2e/ssh-terminal-parking.spec.ts',
'tests/e2e/terminal-retention-budget.spec.ts',
'--config',
'tests/playwright.config.ts',
'--project',
'electron-headless',
'--workers=1',
...extraArgs
],
spawnOptions
)
process.exit(result.status ?? 1)
+1
View File
@@ -98,6 +98,7 @@
"test:e2e:terminal-perf:html-report": "node config/scripts/generate-terminal-perf-html-report.mjs",
"test:e2e:ssh-docker-perf": "node config/scripts/run-ssh-docker-perf-e2e.mjs",
"test:e2e:ssh-docker-watcher-isolation": "node config/scripts/run-ssh-docker-watcher-isolation-e2e.mjs",
"test:e2e:ssh-docker-terminal-parking": "node config/scripts/run-ssh-docker-terminal-parking-e2e.mjs",
"test:e2e:nested-runtime-ssh": "node config/scripts/run-nested-runtime-ssh-e2e.mjs",
"test:e2e:source-control-scale": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/source-control-large-file-count.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
"win-update-e2e": "node tools/win-update-e2e/run.mjs",
+39
View File
@@ -14461,6 +14461,45 @@ describe('registerPtyHandlers', () => {
)
})
it('seeds the headless emulator from an SSH relay reattach replay', async () => {
setLocalPtyProvider({
spawn: vi.fn(async () => ({
id: 'pty-ssh-reattach',
isReattach: true,
replay: 'relay history\r\n'
})),
write: vi.fn(),
resize: vi.fn(),
kill: vi.fn(),
shutdown: vi.fn(),
onData: vi.fn(() => vi.fn()),
onExit: vi.fn(() => vi.fn()),
listProcesses: vi.fn(async () => []),
getForegroundProcess: vi.fn(async () => null)
} as never)
const runtime = {
setPtyController: vi.fn(),
noteTerminalSpawnCommand: vi.fn(),
seedHeadlessTerminal: vi.fn(),
onPtySpawned: vi.fn(),
onPtyData: vi.fn(),
onPtyExit: vi.fn(),
createPreAllocatedTerminalHandle: vi.fn(() => 'handle-ssh-reattach'),
registerPreAllocatedHandleForPty: vi.fn(),
preAllocateHandleForPty: vi.fn()
}
registerPtyHandlers(mainWindow as never, runtime as never)
await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })
// Why: without this seed main's model would be a strict suffix of what the renderer painted, and a later park-reveal would restore the fragment.
expect(runtime.seedHeadlessTerminal).toHaveBeenCalledTimes(1)
expect(runtime.seedHeadlessTerminal).toHaveBeenCalledWith(
'pty-ssh-reattach',
'relay history\r\n'
)
})
it('upgrades legacy numeric pane keys when the spawn metadata proves the stable leaf', async () => {
registerPtyHandlers(mainWindow as never)
const leafId = '11111111-1111-4111-8111-111111111111'
+5
View File
@@ -5069,6 +5069,11 @@ export function registerPtyHandlers(
preferProviderIfExisting: true
}
)
} else if (typeof result.replay === 'string' && result.replay.length > 0) {
// Why: the relay reattach replay is the one restore main never ingests, so without
// this seed its model is a mere suffix of what the renderer painted — and a later
// park-reveal would outrank the fuller relay replay with that fragment.
runtime.seedHeadlessTerminal(result.id, result.replay)
}
}
if (
+2 -1
View File
@@ -23,5 +23,6 @@ export const preloadE2EConfig = createE2EConfig({
userDataDir: process.env.ORCA_E2E_USER_DATA_DIR ?? null,
// Why: Number('') is 0 and Number(undefined) is NaN; both coerce to null so
// only a real positive override reaches the renderer parking policy.
terminalParkingDelayMs: Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || null
terminalParkingDelayMs: Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || null,
terminalRetentionLimit: Number(process.env.ORCA_E2E_TERMINAL_RETENTION_LIMIT) || null
})
+232 -15
View File
@@ -36,7 +36,13 @@ import {
import { isIntentionalAppRestartInProgress } from '@/lib/updater-beforeunload'
import { preventUnloadAndScheduleShutdownCheckpointReset } from '@/lib/shutdown-checkpoint-guard'
import EditorAutosaveController from './editor/EditorAutosaveController'
import type { Tab, TabContentType, TabGroupLayoutNode, TuiAgent } from '../../../shared/types'
import type {
Tab,
TabContentType,
TabGroupLayoutNode,
TerminalTab,
TuiAgent
} from '../../../shared/types'
import { hasFeatureInteraction } from '../../../shared/feature-interactions'
import BrowserPane from './browser-pane/BrowserPane'
import BrowserPaneOverlayLayer from './browser-pane/BrowserPaneOverlayLayer'
@@ -78,13 +84,24 @@ import {
import { buildDuplicatedBrowserTabOptions } from '@/lib/duplicate-browser-tab-options'
import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface'
import { setForegroundTerminalTabIds } from '@/lib/foreground-terminal-tabs'
import { getTerminalWorktreeColdParkRecheckDelayMs } from './terminal-pane/terminal-cold-park-recheck-deadlines'
import {
getTerminalWorktreeColdParkRecheckDelayMs,
TERMINAL_WORKTREE_COLD_PARK_DELAY_MS,
canParkTerminalWorktreeRenderers,
selectColdParkedTerminalWorktrees,
type TerminalWorktreeColdParkCandidate
} from './terminal-pane/terminal-hidden-view-parking'
import {
TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS,
selectForceParkEvictableTabIds,
selectRetentionForceParkedTerminalWorktrees,
type TerminalWorktreeRetentionCandidate
} from './terminal-pane/terminal-hidden-worktree-retention'
import { captureForceParkedWorktreeBuffers } from './terminal-pane/force-park-buffer-capture'
import { warnTerminalLifecycleAnomaly } from './terminal-pane/terminal-lifecycle-diagnostics'
import { getTerminalParkingPolicyOverrides } from './terminal-pane/terminal-parking-e2e-overrides'
import { useColdParkedTerminalPresentation } from './terminal-pane/use-cold-parked-terminal-presentation'
import { selectEvictionExemptTerminalTabIds } from './terminal-pane/terminal-eviction-exempt-tabs'
import {
canWatcherCoverParkedTerminalTab,
disposeAllParkedTerminalWatchers,
@@ -156,7 +173,7 @@ const EDITOR_TAB_CONTENT_TYPES = new Set<TabContentType>([
type TerminalStoreSnapshot = ReturnType<typeof useAppStore.getState>
function haveSameWorktreeIds(left: ReadonlySet<string>, right: ReadonlySet<string>): boolean {
function haveSameIdSet(left: ReadonlySet<string>, right: ReadonlySet<string>): boolean {
if (left.size !== right.size) {
return false
}
@@ -251,6 +268,12 @@ function Terminal(): React.JSX.Element | null {
const mountedWorktreeIdsRef = useRef(new Set<string>())
const measurableBackgroundWorktreeIdsRef = useRef(new Set<string>())
const terminalWorktreeHiddenSinceRef = useRef(new Map<string, number>())
// Why two extra clocks: hiddenSince survives a background-measure window (so
// TTL/ranking stay honest), but re-park must wait a full coldParkDelayMs
// after the measure ends — otherwise every ~3s measure lease on a
// past-deadline worktree thrashes remount/reattach with an immediate re-park.
const measuringTerminalWorktreeIdsRef = useRef(new Set<string>())
const terminalWorktreeParkCooldownUntilRef = useRef(new Map<string, number>())
const terminalWorktreeParkingTimersRef = useRef(new Map<string, number>())
const allWorktrees = useAllWorktrees()
const folderWorkspaces = useAppStore((s) => s.folderWorkspaces)
@@ -273,6 +296,10 @@ function Terminal(): React.JSX.Element | null {
const tabsByWorktree = useAppStore((s) => s.tabsByWorktree)
const pendingStartupByTabId = useAppStore((s) => s.pendingStartupByTabId)
const terminalParkingEnabled = useAppStore((s) => s.settings?.terminalHiddenViewParking !== false)
const terminalSshParkingEnabled = useAppStore((s) => s.settings?.terminalSshViewParking !== false)
const terminalRetentionBudgetEnabled = useAppStore(
(s) => s.settings?.terminalHiddenWorktreeRetentionBudget !== false
)
const terminalTitleSnapshotAuthorityEnabled = useAppStore((s) =>
isMainTerminalSideEffectAuthorityForPty({
settings: s.settings,
@@ -752,6 +779,21 @@ function Terminal(): React.JSX.Element | null {
combineTerminalWorktreeParkIds(parkedTerminalWorktreeIds, manuallyParkedTerminalWorktreeIds),
[manuallyParkedTerminalWorktreeIds, parkedTerminalWorktreeIds]
)
// Why separate from parkedTerminalWorktreeIds: force-parked worktrees keep
// their eviction-exempt tabs' panes mounted (per-tab exclusion), which
// ordinary parks never need — render and watcher sync must tell them apart.
const [forceParkedTerminalWorktreeIds, setForceParkedTerminalWorktreeIds] = useState<
ReadonlySet<string>
>(() => new Set())
// Why state, resolved in the parking pass: each exemption re-reads the store
// and walks the layout/capture candidates, so the render gate and watcher
// sync consume one set per force-park verdict instead of re-asking per tab on
// every unrelated Terminal render.
const [evictionExemptTerminalTabIds, setEvictionExemptTerminalTabIds] = useState<
ReadonlySet<string>
>(() => new Set())
// Why a ref: eviction captures buffers exactly once per force-park episode, before the unmount render.
const forceParkedCaptureDoneRef = useRef(new Set<string>())
// Tab restriction for targeted background mounts (wake/resume); a worktree absent from this map mounts all its tabs.
const backgroundMountTabIdsByWorktreeRef = useRef(new Map<string, ReadonlySet<string>>())
// Why: only cold-activation deferral (not targeted mounts, which share the map above) creates watcher coverage for every unmounted tab.
@@ -849,6 +891,8 @@ function Terminal(): React.JSX.Element | null {
for (const worktreeId of Array.from(terminalWorktreeHiddenSinceRef.current.keys())) {
if (!currentWorktreeIds.has(worktreeId) || !mountedWorktreeIdsRef.current.has(worktreeId)) {
terminalWorktreeHiddenSinceRef.current.delete(worktreeId)
measuringTerminalWorktreeIdsRef.current.delete(worktreeId)
terminalWorktreeParkCooldownUntilRef.current.delete(worktreeId)
}
}
@@ -857,16 +901,42 @@ function Terminal(): React.JSX.Element | null {
const worktreeId = workspace.id
if (!mountedWorktreeIdsRef.current.has(worktreeId)) {
terminalWorktreeHiddenSinceRef.current.delete(worktreeId)
measuringTerminalWorktreeIdsRef.current.delete(worktreeId)
terminalWorktreeParkCooldownUntilRef.current.delete(worktreeId)
continue
}
const isVisible = activeView === 'terminal' && renderedActiveWorktreeId === worktreeId
const shouldMeasureHiddenWorktree =
!isVisible && measurableBackgroundWorktreeIdsRef.current.has(worktreeId)
const hasActivityTerminalPortal = portalWorktreeIds.has(worktreeId)
if (isVisible || shouldMeasureHiddenWorktree || hasActivityTerminalPortal) {
// Why the cool-down: hiddenSince deliberately survives the measure (see
// below), so a past-deadline worktree would otherwise re-park in the
// same pass the measure lease ends — remount/reattach thrash on every
// periodic probe. The cool-down re-grants the coldParkDelayMs hysteresis
// without touching the TTL/ranking clock.
if (shouldMeasureHiddenWorktree) {
measuringTerminalWorktreeIdsRef.current.add(worktreeId)
} else {
if (measuringTerminalWorktreeIdsRef.current.has(worktreeId)) {
terminalWorktreeParkCooldownUntilRef.current.set(
worktreeId,
nowMs + (overrides.coldParkDelayMs ?? TERMINAL_WORKTREE_COLD_PARK_DELAY_MS)
)
}
measuringTerminalWorktreeIdsRef.current.delete(worktreeId)
}
if (isVisible || hasActivityTerminalPortal) {
terminalWorktreeHiddenSinceRef.current.delete(worktreeId)
} else if (!terminalWorktreeHiddenSinceRef.current.has(worktreeId)) {
terminalWorktreeHiddenSinceRef.current.set(worktreeId, nowMs)
terminalWorktreeParkCooldownUntilRef.current.delete(worktreeId)
} else if (!shouldMeasureHiddenWorktree) {
// Why measuring is excluded here but still pauses the verdicts below:
// the ~3s background-measure window (automation lease, mobile mount,
// agent wake) is transient — resetting hiddenSince would restart the
// 30s hysteresis AND the 45min retention TTL on every remount, so a
// periodically re-mounted force-parked worktree would never re-park.
if (!terminalWorktreeHiddenSinceRef.current.has(worktreeId)) {
terminalWorktreeHiddenSinceRef.current.set(worktreeId, nowMs)
}
}
retentionCandidates.push({
@@ -875,29 +945,151 @@ function Terminal(): React.JSX.Element | null {
isVisible,
shouldMeasureHiddenWorktree,
hasActivityTerminalPortal,
hiddenSinceMs: terminalWorktreeHiddenSinceRef.current.get(worktreeId) ?? null
hiddenSinceMs: terminalWorktreeHiddenSinceRef.current.get(worktreeId) ?? null,
parkCooldownUntilMs: terminalWorktreeParkCooldownUntilRef.current.get(worktreeId) ?? null
})
}
const restorePolicy = { sshParkingEnabled: terminalSshParkingEnabled }
const nextParkedTerminalWorktreeIds = selectColdParkedTerminalWorktrees({
worktrees: retentionCandidates,
pendingStartupByTabId,
parkingEnabled: terminalParkingEnabled,
nowMs,
restorePolicy,
...overrides
})
// Why memoized: the retention pass below re-asks coverage for EVERY mounted
// worktree's tabs, not just the parked few — each call re-reads the store and
// can walk the layout tree, so cache per tab for this pass.
const watcherCoverageByTabId = new Map<string, boolean>()
const worktreeTabsAreWatcherCovered = (worktreeId: string, tabs: TerminalTab[]): boolean =>
tabs.every((tab) => {
const cached = watcherCoverageByTabId.get(tab.id)
if (cached !== undefined) {
return cached
}
const covered = canWatcherCoverParkedTerminalTab(worktreeId, tab)
watcherCoverageByTabId.set(tab.id, covered)
return covered
})
// Why: a worktree with any watcher-uncoverable tab must never park, or it goes silent for bells/titles/completions (sank the first parking attempt).
for (const worktreeId of Array.from(nextParkedTerminalWorktreeIds)) {
const tabs = tabsByWorktree[worktreeId] ?? []
if (!tabs.every((tab) => canWatcherCoverParkedTerminalTab(worktreeId, tab))) {
if (!worktreeTabsAreWatcherCovered(worktreeId, tabsByWorktree[worktreeId] ?? [])) {
nextParkedTerminalWorktreeIds.delete(worktreeId)
}
}
// C1 retention budget: worktrees ordinary parking can never evict (SSH off,
// remote-runtime, uncoverable tabs) force-park beyond a count/TTL bound —
// added AFTER the coverage veto because darkness for their uncoverable tabs
// is the accepted cost of bounding retention.
const retentionBudgetCandidates: TerminalWorktreeRetentionCandidate[] = retentionCandidates.map(
(candidate) => {
const tabs = tabsByWorktree[candidate.worktreeId] ?? []
const parkEligible = canParkTerminalWorktreeRenderers({
...candidate,
// Why nulled: the post-measure cool-down is a timing gate, not a
// coverage change — ordinary parking still covers this worktree, it
// just may not re-engage yet. Leaving it set would misclassify the
// worktree as a retention candidate for the cool-down window.
parkCooldownUntilMs: null,
pendingStartupByTabId,
parkingEnabled: terminalParkingEnabled,
nowMs,
restorePolicy,
...(overrides.coldParkDelayMs !== undefined
? { coldParkDelayMs: overrides.coldParkDelayMs }
: {})
})
return {
worktreeId: candidate.worktreeId,
hiddenSinceMs: candidate.hiddenSinceMs,
isVisible: candidate.isVisible,
shouldMeasureHiddenWorktree: candidate.shouldMeasureHiddenWorktree,
hasActivityTerminalPortal: candidate.hasActivityTerminalPortal,
parkCooldownUntilMs: candidate.parkCooldownUntilMs,
ordinaryParkingCovers:
parkEligible && worktreeTabsAreWatcherCovered(candidate.worktreeId, tabs),
hasPendingSpawnWork: tabs.some(
(tab) =>
pendingStartupByTabId[tab.id] !== undefined ||
tab.pendingActivationSpawn === true ||
(typeof tab.pendingActivationSpawn === 'number' && tab.pendingActivationSpawn > 0)
)
}
}
)
const forceParkedWorktreeIds = selectRetentionForceParkedTerminalWorktrees({
worktrees: retentionBudgetCandidates,
parkingEnabled: terminalParkingEnabled,
retentionBudgetEnabled: terminalRetentionBudgetEnabled,
nowMs,
...overrides
})
const capturedForceParked = forceParkedCaptureDoneRef.current
for (const id of Array.from(capturedForceParked)) {
if (!forceParkedWorktreeIds.has(id)) {
capturedForceParked.delete(id)
}
}
// Why getState and not a dep: this read happens in the same pass that
// unmounts the panes, so it is the current catalog; re-running on a later
// repos change could not re-capture buffers whose panes are already gone.
const repos = useAppStore.getState().repos
const nextEvictionExemptTabIds = new Set<string>()
for (const worktreeId of forceParkedWorktreeIds) {
const forceParkedTabs = tabsByWorktree[worktreeId] ?? []
const exemptTabIds = selectEvictionExemptTerminalTabIds(worktreeId, forceParkedTabs)
for (const tabId of exemptTabIds) {
nextEvictionExemptTabIds.add(tabId)
}
if (!capturedForceParked.has(worktreeId)) {
// Why: serialize buffers while the panes still exist (same registry sleep
// uses), so SSH classes whose reveal has no local snapshot still show
// last-known content. includeLocalBuffers:false is required here, not
// optional — a heap fix must not plant 512KB/pane of scrollback strings
// in the store for local worktrees that already have the daemon
// snapshot; a remote-runtime pane in a local repo likewise needs none,
// its reveal repaints from the runtime's own subscribe snapshot.
// Eviction-exempt tabs never unmount (per-tab exclusion), so they need
// no pre-unmount capture — skipping spares a serialize+setTabLayout
// walk on live panes per force-park episode.
const evictableTabIds = selectForceParkEvictableTabIds(forceParkedTabs, (tab) =>
exemptTabIds.has(tab.id)
)
// Why logged: an all-exempt force-park frees no heap at all (daemon
// fail-open makes every local pty exempt), so the budget only holds
// while this stays rare — make the degenerate case observable.
if (evictableTabIds.length === 0 && forceParkedTabs.length > 0) {
warnTerminalLifecycleAnomaly('retention force-park freed no panes', {
worktreeId,
reason: `exemptTabs=${forceParkedTabs.length}`
})
}
// Why conditional: a tab whose pane was mid-remount registered no
// capture callback, and a later episode is this pass's only retry.
if (captureForceParkedWorktreeBuffers({ worktreeId, tabIds: evictableTabIds, repos })) {
capturedForceParked.add(worktreeId)
}
}
nextParkedTerminalWorktreeIds.add(worktreeId)
}
setParkedTerminalWorktreeIds((current) =>
haveSameWorktreeIds(current, nextParkedTerminalWorktreeIds)
haveSameIdSet(current, nextParkedTerminalWorktreeIds)
? current
: nextParkedTerminalWorktreeIds
)
setForceParkedTerminalWorktreeIds((current) =>
haveSameIdSet(current, forceParkedWorktreeIds) ? current : forceParkedWorktreeIds
)
setEvictionExemptTerminalTabIds((current) =>
haveSameIdSet(current, nextEvictionExemptTabIds) ? current : nextEvictionExemptTabIds
)
const retentionTtlEligibleIds = new Set(
retentionBudgetCandidates
.filter((candidate) => !candidate.ordinaryParkingCovers && !candidate.hasPendingSpawnWork)
.map((candidate) => candidate.worktreeId)
)
for (const candidate of retentionCandidates) {
if (
@@ -911,8 +1103,15 @@ function Terminal(): React.JSX.Element | null {
const delayMs = getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: terminalParkingEnabled,
hiddenSinceMs: candidate.hiddenSinceMs,
parkCooldownUntilMs: candidate.parkCooldownUntilMs,
nowMs,
...overrides
...overrides,
// Why: only retention candidates wake at the eviction TTL; everyone else keeps the ordinary deadlines.
...(terminalRetentionBudgetEnabled && retentionTtlEligibleIds.has(candidate.worktreeId)
? {
retentionTtlMs: overrides.retentionTtlMs ?? TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS
}
: {})
})
if (delayMs !== null && delayMs > 0) {
const worktreeId = candidate.worktreeId
@@ -932,6 +1131,8 @@ function Terminal(): React.JSX.Element | null {
tabsByWorktree,
terminalParkingEnabled,
terminalParkingRevision,
terminalRetentionBudgetEnabled,
terminalSshParkingEnabled,
workspaceSurfaces
])
// Why: gate on workspaceSessionReady so TerminalPane doesn't mount and spawn a duplicate PTY before reconnectPersistedTerminals() finishes.
@@ -1111,7 +1312,12 @@ function Terminal(): React.JSX.Element | null {
worktreeId: workspace.id,
tabId: tab.id
})
if (!activityTerminalPortal) {
// Why the exempt exclusion: force-park keeps eviction-exempt tabs'
// panes mounted (a remount would orphan their live pty) — same
// per-tab carve-out as Activity portals, so no watcher owns them.
// The set is resolved in the force-park pass and holds only those
// worktrees' tabs.
if (!activityTerminalPortal && !evictionExemptTerminalTabIds.has(tab.id)) {
parkedTabIds.add(tab.id)
}
}
@@ -1149,6 +1355,7 @@ function Terminal(): React.JSX.Element | null {
activeTabIdByWorktree,
anyMountedWorktreeHasLayout,
backgroundMountRevision,
evictionExemptTerminalTabIds,
getEffectiveLayoutForWorktree,
groupsByWorktree,
effectiveParkedTerminalWorktreeIds,
@@ -1160,7 +1367,7 @@ function Terminal(): React.JSX.Element | null {
workspaceSessionReady,
workspaceSurfaces
])
// Why: on host unmount no reconciliation effect runs again, so dispose every remaining parked watcher here.
// Why: on host unmount no reconciliation effect runs again, so dispose every remaining parked watcher.
useEffect(() => () => disposeAllParkedTerminalWatchers(), [])
// Auto-create first tab when worktree activates
useEffect(() => {
@@ -2146,6 +2353,7 @@ function Terminal(): React.JSX.Element | null {
isPresented={isPresented}
shouldMeasureHiddenWorktree={shouldMeasureHiddenWorktree}
shouldColdParkTerminalPanes={shouldColdParkTerminalPanes}
isForceParked={forceParkedTerminalWorktreeIds.has(workspace.id)}
activityTerminalPortals={activityTerminalPortals}
backgroundMountTabIds={
backgroundMountTabIdsByWorktreeRef.current.get(workspace.id) ?? null
@@ -2219,8 +2427,14 @@ function Terminal(): React.JSX.Element | null {
const isPresentedTerminalTab =
isPresented &&
(isActiveTerminalTab || tab.id === activeTabIdByWorktree[workspace.id])
// Why: parking unmounts the view but keeps the PTY; an Activity portal stays mounted as a visible consumer.
if (shouldColdParkTerminalPanes && !isActivityPortalTab) {
// Why: parking unmounts the view but keeps the PTY; an Activity portal stays
// mounted as a visible consumer, and a force-parked worktree's eviction-exempt
// tabs stay mounted because a remount would orphan their live pty.
if (
shouldColdParkTerminalPanes &&
!isActivityPortalTab &&
!evictionExemptTerminalTabIds.has(tab.id)
) {
return null
}
const terminalPane = (
@@ -2418,6 +2632,7 @@ const WorktreeSplitSurface = React.memo(function WorktreeSplitSurface({
isPresented,
shouldMeasureHiddenWorktree,
shouldColdParkTerminalPanes,
isForceParked,
activityTerminalPortals,
backgroundMountTabIds,
activationDeferredMountTabIds,
@@ -2431,6 +2646,7 @@ const WorktreeSplitSurface = React.memo(function WorktreeSplitSurface({
isPresented: boolean
shouldMeasureHiddenWorktree: boolean
shouldColdParkTerminalPanes: boolean
isForceParked: boolean
activityTerminalPortals: ActivityTerminalPortalTarget[]
backgroundMountTabIds: ReadonlySet<string> | null
activationDeferredMountTabIds: ReadonlySet<string> | null
@@ -2474,6 +2690,7 @@ const WorktreeSplitSurface = React.memo(function WorktreeSplitSurface({
isWorktreeActive={isVisible}
isWorktreePresented={isPresented}
coldParkTerminalPanes={shouldColdParkTerminalPanes}
isForceParked={isForceParked}
shouldMeasureHiddenWorktree={shouldMeasureHiddenWorktree}
activityTerminalPortals={activityTerminalPortals}
backgroundMountTabIds={backgroundMountTabIds}
@@ -0,0 +1,290 @@
import { memo, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useAppStore } from '../../store'
import { SYNC_FIT_PANES_EVENT } from '@/constants/terminal'
import { tabGroupBodyAnchorName } from '../tab-group/tab-group-body-anchor'
import type { ActivityTerminalPortalTarget } from '../activity/activity-terminal-portal'
import TerminalPane from './TerminalPane'
import { closeTerminalTab } from '../terminal/terminal-tab-actions'
import { shouldDeferParkedPtyExitTabClose } from './terminal-parked-tab-watchers'
import {
FALLBACK_RECT_MIN_CHANGE_PX,
MIN_OVERLAY_FIT_HEIGHT_PX,
MIN_OVERLAY_FIT_WIDTH_PX,
shouldUseCssAnchorPositioning
} from './terminal-overlay-positioning'
type MeasuredFallbackRect = {
top: number
left: number
width: number
height: number
}
type TerminalOverlaySlotProps = {
terminalTabId: string
terminalGeneration: number | undefined
worktreeId: string
worktreePath: string
startupCwd: string | undefined
groupId: string | undefined
isWorktreeActive: boolean
isWorktreePresented: boolean
isVisible: boolean
isPresented: boolean
isActive: boolean
activityTerminalPortal: ActivityTerminalPortalTarget | null
onFocusOwningGroup: ((groupId: string) => void) | undefined
consumeSuppressedPtyExit: (ptyId: string) => boolean
leaveWorktreeIfEmpty: () => void
onInitialRenderSettled?: () => void
}
export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({
terminalTabId,
terminalGeneration,
worktreeId,
worktreePath,
startupCwd,
groupId,
isWorktreeActive,
isWorktreePresented,
isVisible,
isPresented,
isActive,
activityTerminalPortal,
onFocusOwningGroup,
consumeSuppressedPtyExit,
leaveWorktreeIfEmpty,
onInitialRenderSettled
}: TerminalOverlaySlotProps): React.JSX.Element {
const anchorName = groupId !== undefined ? tabGroupBodyAnchorName(groupId) : undefined
const overlayRef = useRef<HTMLDivElement | null>(null)
const [measuredFallbackRect, setMeasuredFallbackRect] = useState<MeasuredFallbackRect | null>(
null
)
const [shouldMeasureHiddenStartup, setShouldMeasureHiddenStartup] = useState(
() => useAppStore.getState().pendingStartupByTabId[terminalTabId] !== undefined
)
useLayoutEffect(() => {
if (isVisible && shouldMeasureHiddenStartup) {
setShouldMeasureHiddenStartup(false)
}
}, [isVisible, shouldMeasureHiddenStartup])
useLayoutEffect(() => {
if (!anchorName || shouldUseCssAnchorPositioning() || !groupId) {
return
}
const findBody = (): HTMLElement | null => {
for (const candidate of document.querySelectorAll<HTMLElement>('[data-tab-group-body-id]')) {
if (candidate.dataset.tabGroupBodyId === groupId) {
return candidate
}
}
return null
}
const updateRect = (): void => {
const overlay = overlayRef.current
const parent = overlay?.parentElement
const body = findBody()
if (!parent || !body) {
setMeasuredFallbackRect(null)
return
}
const parentRect = parent.getBoundingClientRect()
const bodyRect = body.getBoundingClientRect()
const next: MeasuredFallbackRect = {
top: bodyRect.top - parentRect.top,
left: bodyRect.left - parentRect.left,
width: bodyRect.width,
height: bodyRect.height
}
// Why: ResizeObserver and xterm fit can otherwise amplify sub-pixel jitter forever.
setMeasuredFallbackRect((prev) =>
prev &&
Math.abs(prev.top - next.top) < FALLBACK_RECT_MIN_CHANGE_PX &&
Math.abs(prev.left - next.left) < FALLBACK_RECT_MIN_CHANGE_PX &&
Math.abs(prev.width - next.width) < FALLBACK_RECT_MIN_CHANGE_PX &&
Math.abs(prev.height - next.height) < FALLBACK_RECT_MIN_CHANGE_PX
? prev
: next
)
}
updateRect()
const body = findBody()
const parent = overlayRef.current?.parentElement
const resizeObserver = new ResizeObserver(updateRect)
if (body) {
resizeObserver.observe(body)
}
if (parent) {
resizeObserver.observe(parent)
}
window.addEventListener('resize', updateRect)
return () => {
resizeObserver.disconnect()
window.removeEventListener('resize', updateRect)
}
}, [anchorName, groupId, isVisible])
useLayoutEffect(() => {
if (!isVisible || !anchorName) {
return
}
const dispatchFitIfMeasurable = (): void => {
const rect = overlayRef.current?.getBoundingClientRect()
if (
!rect ||
rect.width < MIN_OVERLAY_FIT_WIDTH_PX ||
rect.height < MIN_OVERLAY_FIT_HEIGHT_PX
) {
return
}
window.dispatchEvent(new Event(SYNC_FIT_PANES_EVENT))
}
// Why: tab switches can resume visibility before anchor/fallback geometry
// settles. Re-fit only after the overlay has real dimensions so the PTY
// never stays pinned at a stale ~2-col width.
const frameId = requestAnimationFrame(() => {
dispatchFitIfMeasurable()
})
const retryId = window.setTimeout(() => {
dispatchFitIfMeasurable()
}, 50)
const settledRetryId = window.setTimeout(() => {
dispatchFitIfMeasurable()
}, 150)
return () => {
cancelAnimationFrame(frameId)
window.clearTimeout(retryId)
window.clearTimeout(settledRetryId)
}
}, [anchorName, isVisible, measuredFallbackRect])
const showPresentedTerminal = isPresented && (isWorktreeActive || isWorktreePresented)
const isInteractive = isVisible && isPresented && isWorktreePresented
const style: React.CSSProperties = useMemo(
() =>
anchorName && shouldUseCssAnchorPositioning()
? {
position: 'absolute',
positionAnchor: anchorName,
top: `anchor(${anchorName} top)`,
left: `anchor(${anchorName} left)`,
width: `anchor-size(${anchorName} width)`,
height: `anchor-size(${anchorName} height)`,
display:
isVisible || showPresentedTerminal || shouldMeasureHiddenStartup ? 'flex' : 'none',
opacity: showPresentedTerminal ? 1 : 0,
pointerEvents: isInteractive ? 'auto' : 'none'
}
: anchorName
? {
// Why: Chrome builds without CSS anchor positioning otherwise
// mount the terminal into a 0x0 overlay. Measure the tab-group
// body so the fallback does not cover the tab strip.
position: 'absolute',
top: measuredFallbackRect?.top ?? 32,
left: measuredFallbackRect?.left ?? 0,
width: measuredFallbackRect?.width ?? '100%',
height: measuredFallbackRect?.height ?? 'calc(100% - 32px)',
display:
isVisible || showPresentedTerminal || shouldMeasureHiddenStartup ? 'flex' : 'none',
opacity: showPresentedTerminal ? 1 : 0,
pointerEvents: isInteractive ? 'auto' : 'none'
}
: {
position: 'absolute',
top: 0,
left: 0,
width: 0,
height: 0,
display: 'none',
pointerEvents: 'none'
},
[
anchorName,
isInteractive,
isVisible,
measuredFallbackRect,
shouldMeasureHiddenStartup,
showPresentedTerminal
]
)
const focusGroup = useCallback(() => {
if (groupId !== undefined && onFocusOwningGroup) {
onFocusOwningGroup(groupId)
}
}, [groupId, onFocusOwningGroup])
const terminalPane = (
<TerminalPane
key={`${terminalTabId}-${terminalGeneration ?? 0}`}
tabId={terminalTabId}
worktreeId={worktreeId}
cwd={startupCwd ?? worktreePath}
isActive={
(isActive && isPresented && isWorktreePresented) || activityTerminalPortal?.active === true
}
// Why: split-group changes reparent TabGroupPanel subtrees. Keeping the
// TerminalPane mounted here preserves alt-screen TUI state while this
// flag still lets hidden tabs throttle rendering.
isVisible={isVisible || showPresentedTerminal || activityTerminalPortal !== null}
isWorktreeActive={isWorktreeActive || isWorktreePresented || activityTerminalPortal !== null}
isolatedPaneKey={activityTerminalPortal?.paneKey ?? null}
onPtyExit={(ptyId) => {
if (consumeSuppressedPtyExit(ptyId)) {
return
}
// Why: a parked multi-leaf tab has no PaneManager to promote split
// siblings, so closing the tab here would kill them; the reveal
// remount handles dead PTYs per leaf instead.
if (shouldDeferParkedPtyExitTabClose(terminalTabId, ptyId)) {
return
}
closeTerminalTab(terminalTabId, {
reason: 'pty-exit',
lifecyclePtyId: ptyId,
onClosed: leaveWorktreeIfEmpty
})
}}
onCloseTab={() => {
// Why: route through closeTerminalTab (not the raw store closeTab) so a
// pinned tab hits the confirmation guard. The overlay's direct
// store.closeTab was the path that closed pinned terminals silently.
closeTerminalTab(terminalTabId, { onClosed: leaveWorktreeIfEmpty })
}}
onInitialRenderSettled={onInitialRenderSettled}
/>
)
if (activityTerminalPortal) {
return createPortal(
terminalPane,
activityTerminalPortal.target,
`activity-terminal-${terminalTabId}`
)
}
return (
<div
ref={overlayRef}
style={style}
data-terminal-overlay-tab-id={terminalTabId}
data-terminal-overlay-presented={showPresentedTerminal ? 'true' : 'false'}
inert={!isInteractive}
aria-hidden={!isInteractive}
onPointerDown={focusGroup}
onFocusCapture={focusGroup}
>
{terminalPane}
{/* The chat/terminal toggle now lives in the pane header's action cluster
(TerminalPaneHeaderOverlay), beside split/close — not as a separate
floating overlay. */}
</div>
)
})
@@ -19,7 +19,7 @@ vi.mock('../../store', () => ({
})
}))
import { TerminalOverlaySlot } from './TerminalPaneOverlayLayer'
import { TerminalOverlaySlot } from './TerminalOverlaySlot'
const GROUP_ID = 'group-react185'
const TAB_ID = 'tab-react185'
@@ -1,315 +1,30 @@
import { memo, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { memo, useCallback, useMemo } from 'react'
import { useShallow } from 'zustand/react/shallow'
import type { Tab, TabGroup, TerminalTab } from '../../../../shared/types'
import { useAppStore } from '../../store'
import { SYNC_FIT_PANES_EVENT } from '@/constants/terminal'
import { tabGroupBodyAnchorName } from '../tab-group/tab-group-body-anchor'
import {
findActivityTerminalPortal,
type ActivityTerminalPortalTarget
} from '../activity/activity-terminal-portal'
import TerminalPane from './TerminalPane'
import { closeTerminalTab } from '../terminal/terminal-tab-actions'
import { shouldMountBackgroundWorktreeTab } from '../terminal/background-terminal-worktree-mount'
import { useNativeChatToggleShortcut } from '../native-chat/use-native-chat-toggle-shortcut'
import { shouldDeferParkedPtyExitTabClose } from './terminal-parked-tab-watchers'
import { useTerminalTabColdParking } from './use-terminal-tab-cold-parking'
import { useTerminalOverlayPresentation } from './use-terminal-overlay-presentation'
import { buildTerminalOverlayAssignments } from './terminal-overlay-assignments'
import {
FALLBACK_RECT_MIN_CHANGE_PX,
MIN_OVERLAY_FIT_HEIGHT_PX,
MIN_OVERLAY_FIT_WIDTH_PX,
shouldUseCssAnchorPositioning
} from './terminal-overlay-positioning'
import { TerminalOverlaySlot } from './TerminalOverlaySlot'
const EMPTY_TERMINAL_TABS: readonly TerminalTab[] = []
const EMPTY_UNIFIED_TABS: readonly Tab[] = []
const EMPTY_GROUPS: readonly TabGroup[] = []
const EMPTY_ACTIVITY_PORTALS: ActivityTerminalPortalTarget[] = []
type MeasuredFallbackRect = {
top: number
left: number
width: number
height: number
}
type TerminalOverlaySlotProps = {
terminalTabId: string
terminalGeneration: number | undefined
worktreeId: string
worktreePath: string
startupCwd: string | undefined
groupId: string | undefined
isWorktreeActive: boolean
isWorktreePresented: boolean
isVisible: boolean
isPresented: boolean
isActive: boolean
activityTerminalPortal: ActivityTerminalPortalTarget | null
onFocusOwningGroup: ((groupId: string) => void) | undefined
consumeSuppressedPtyExit: (ptyId: string) => boolean
leaveWorktreeIfEmpty: () => void
onInitialRenderSettled?: () => void
}
export const TerminalOverlaySlot = memo(function TerminalOverlaySlot({
terminalTabId,
terminalGeneration,
worktreeId,
worktreePath,
startupCwd,
groupId,
isWorktreeActive,
isWorktreePresented,
isVisible,
isPresented,
isActive,
activityTerminalPortal,
onFocusOwningGroup,
consumeSuppressedPtyExit,
leaveWorktreeIfEmpty,
onInitialRenderSettled
}: TerminalOverlaySlotProps): React.JSX.Element {
const anchorName = groupId !== undefined ? tabGroupBodyAnchorName(groupId) : undefined
const overlayRef = useRef<HTMLDivElement | null>(null)
const [measuredFallbackRect, setMeasuredFallbackRect] = useState<MeasuredFallbackRect | null>(
null
)
const [shouldMeasureHiddenStartup, setShouldMeasureHiddenStartup] = useState(
() => useAppStore.getState().pendingStartupByTabId[terminalTabId] !== undefined
)
useLayoutEffect(() => {
if (isVisible && shouldMeasureHiddenStartup) {
setShouldMeasureHiddenStartup(false)
}
}, [isVisible, shouldMeasureHiddenStartup])
useLayoutEffect(() => {
if (!anchorName || shouldUseCssAnchorPositioning() || !groupId) {
return
}
const findBody = (): HTMLElement | null => {
for (const candidate of document.querySelectorAll<HTMLElement>('[data-tab-group-body-id]')) {
if (candidate.dataset.tabGroupBodyId === groupId) {
return candidate
}
}
return null
}
const updateRect = (): void => {
const overlay = overlayRef.current
const parent = overlay?.parentElement
const body = findBody()
if (!parent || !body) {
setMeasuredFallbackRect(null)
return
}
const parentRect = parent.getBoundingClientRect()
const bodyRect = body.getBoundingClientRect()
const next: MeasuredFallbackRect = {
top: bodyRect.top - parentRect.top,
left: bodyRect.left - parentRect.left,
width: bodyRect.width,
height: bodyRect.height
}
// Why: ResizeObserver and xterm fit can otherwise amplify sub-pixel jitter forever.
setMeasuredFallbackRect((prev) =>
prev &&
Math.abs(prev.top - next.top) < FALLBACK_RECT_MIN_CHANGE_PX &&
Math.abs(prev.left - next.left) < FALLBACK_RECT_MIN_CHANGE_PX &&
Math.abs(prev.width - next.width) < FALLBACK_RECT_MIN_CHANGE_PX &&
Math.abs(prev.height - next.height) < FALLBACK_RECT_MIN_CHANGE_PX
? prev
: next
)
}
updateRect()
const body = findBody()
const parent = overlayRef.current?.parentElement
const resizeObserver = new ResizeObserver(updateRect)
if (body) {
resizeObserver.observe(body)
}
if (parent) {
resizeObserver.observe(parent)
}
window.addEventListener('resize', updateRect)
return () => {
resizeObserver.disconnect()
window.removeEventListener('resize', updateRect)
}
}, [anchorName, groupId, isVisible])
useLayoutEffect(() => {
if (!isVisible || !anchorName) {
return
}
const dispatchFitIfMeasurable = (): void => {
const rect = overlayRef.current?.getBoundingClientRect()
if (
!rect ||
rect.width < MIN_OVERLAY_FIT_WIDTH_PX ||
rect.height < MIN_OVERLAY_FIT_HEIGHT_PX
) {
return
}
window.dispatchEvent(new Event(SYNC_FIT_PANES_EVENT))
}
// Why: tab switches can resume visibility before anchor/fallback geometry
// settles. Re-fit only after the overlay has real dimensions so the PTY
// never stays pinned at a stale ~2-col width.
const frameId = requestAnimationFrame(() => {
dispatchFitIfMeasurable()
})
const retryId = window.setTimeout(() => {
dispatchFitIfMeasurable()
}, 50)
const settledRetryId = window.setTimeout(() => {
dispatchFitIfMeasurable()
}, 150)
return () => {
cancelAnimationFrame(frameId)
window.clearTimeout(retryId)
window.clearTimeout(settledRetryId)
}
}, [anchorName, isVisible, measuredFallbackRect])
const showPresentedTerminal = isPresented && (isWorktreeActive || isWorktreePresented)
const isInteractive = isVisible && isPresented && isWorktreePresented
const style: React.CSSProperties = useMemo(
() =>
anchorName && shouldUseCssAnchorPositioning()
? {
position: 'absolute',
positionAnchor: anchorName,
top: `anchor(${anchorName} top)`,
left: `anchor(${anchorName} left)`,
width: `anchor-size(${anchorName} width)`,
height: `anchor-size(${anchorName} height)`,
display:
isVisible || showPresentedTerminal || shouldMeasureHiddenStartup ? 'flex' : 'none',
opacity: showPresentedTerminal ? 1 : 0,
pointerEvents: isInteractive ? 'auto' : 'none'
}
: anchorName
? {
// Why: Chrome builds without CSS anchor positioning otherwise
// mount the terminal into a 0x0 overlay. Measure the tab-group
// body so the fallback does not cover the tab strip.
position: 'absolute',
top: measuredFallbackRect?.top ?? 32,
left: measuredFallbackRect?.left ?? 0,
width: measuredFallbackRect?.width ?? '100%',
height: measuredFallbackRect?.height ?? 'calc(100% - 32px)',
display:
isVisible || showPresentedTerminal || shouldMeasureHiddenStartup ? 'flex' : 'none',
opacity: showPresentedTerminal ? 1 : 0,
pointerEvents: isInteractive ? 'auto' : 'none'
}
: {
position: 'absolute',
top: 0,
left: 0,
width: 0,
height: 0,
display: 'none',
pointerEvents: 'none'
},
[
anchorName,
isInteractive,
isVisible,
measuredFallbackRect,
shouldMeasureHiddenStartup,
showPresentedTerminal
]
)
const focusGroup = useCallback(() => {
if (groupId !== undefined && onFocusOwningGroup) {
onFocusOwningGroup(groupId)
}
}, [groupId, onFocusOwningGroup])
const terminalPane = (
<TerminalPane
key={`${terminalTabId}-${terminalGeneration ?? 0}`}
tabId={terminalTabId}
worktreeId={worktreeId}
cwd={startupCwd ?? worktreePath}
isActive={
(isActive && isPresented && isWorktreePresented) || activityTerminalPortal?.active === true
}
// Why: split-group changes reparent TabGroupPanel subtrees. Keeping the
// TerminalPane mounted here preserves alt-screen TUI state while this
// flag still lets hidden tabs throttle rendering.
isVisible={isVisible || showPresentedTerminal || activityTerminalPortal !== null}
isWorktreeActive={isWorktreeActive || isWorktreePresented || activityTerminalPortal !== null}
isolatedPaneKey={activityTerminalPortal?.paneKey ?? null}
onPtyExit={(ptyId) => {
if (consumeSuppressedPtyExit(ptyId)) {
return
}
// Why: a parked multi-leaf tab has no PaneManager to promote split
// siblings, so closing the tab here would kill them; the reveal
// remount handles dead PTYs per leaf instead.
if (shouldDeferParkedPtyExitTabClose(terminalTabId, ptyId)) {
return
}
closeTerminalTab(terminalTabId, {
reason: 'pty-exit',
lifecyclePtyId: ptyId,
onClosed: leaveWorktreeIfEmpty
})
}}
onCloseTab={() => {
// Why: route through closeTerminalTab (not the raw store closeTab) so a
// pinned tab hits the confirmation guard. The overlay's direct
// store.closeTab was the path that closed pinned terminals silently.
closeTerminalTab(terminalTabId, { onClosed: leaveWorktreeIfEmpty })
}}
onInitialRenderSettled={onInitialRenderSettled}
/>
)
if (activityTerminalPortal) {
return createPortal(
terminalPane,
activityTerminalPortal.target,
`activity-terminal-${terminalTabId}`
)
}
return (
<div
ref={overlayRef}
style={style}
data-terminal-overlay-tab-id={terminalTabId}
data-terminal-overlay-presented={showPresentedTerminal ? 'true' : 'false'}
inert={!isInteractive}
aria-hidden={!isInteractive}
onPointerDown={focusGroup}
onFocusCapture={focusGroup}
>
{terminalPane}
{/* The chat/terminal toggle now lives in the pane header's action cluster
(TerminalPaneHeaderOverlay), beside split/close — not as a separate
floating overlay. */}
</div>
)
})
const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({
worktreeId,
worktreePath,
isWorktreeActive,
isWorktreePresented = isWorktreeActive,
coldParkTerminalPanes = false,
isForceParked = false,
shouldMeasureHiddenWorktree = false,
activityTerminalPortals = EMPTY_ACTIVITY_PORTALS,
backgroundMountTabIds = null,
@@ -321,6 +36,8 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({
isWorktreeActive: boolean
isWorktreePresented?: boolean
coldParkTerminalPanes?: boolean
/** Retention-budget force-park (C1 slice B): eviction-exempt tabs keep their mounted panes. */
isForceParked?: boolean
shouldMeasureHiddenWorktree?: boolean
activityTerminalPortals?: ActivityTerminalPortalTarget[]
/** Non-null for targeted background mounts: only these terminal tabs get a
@@ -378,6 +95,7 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({
assignments,
isWorktreeActive,
coldParkTerminalPanes,
isForceParked,
shouldMeasureHiddenWorktree,
activityTerminalPortals,
activationDeferredMountTabIds
@@ -0,0 +1,113 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
COMMAND_CODE_OUTPUT_DONE_SETTLE_MS,
_resetCommandCodeDoneSettlesForTest,
cancelCommandCodeDoneSettle,
openCommandCodeDoneSettle,
setCommandCodeDoneSettleExecutor
} from './command-code-done-settle'
const PANE_KEY = 'tab-1:11111111-1111-4111-8111-111111111111'
const OTHER_PANE_KEY = 'tab-2:22222222-2222-4222-8222-222222222222'
describe('command code done settle window', () => {
beforeEach(() => {
vi.useFakeTimers()
_resetCommandCodeDoneSettlesForTest()
})
afterEach(() => {
_resetCommandCodeDoneSettlesForTest()
vi.useRealTimers()
})
it('settles through the registered executor at the deadline', () => {
const settle = vi.fn()
setCommandCodeDoneSettleExecutor(PANE_KEY, settle)
openCommandCodeDoneSettle(PANE_KEY, 'Fix the spinner')
vi.advanceTimersByTime(COMMAND_CODE_OUTPUT_DONE_SETTLE_MS - 1)
expect(settle).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
expect(settle).toHaveBeenCalledExactlyOnceWith('Fix the spinner')
})
// Why: this is the park/reveal contract — the deadline is the turn's, not the owner's.
it('keeps the original deadline when the owner is swapped mid-window', () => {
const parkedWatcherSettle = vi.fn()
const releaseParkedWatcher = setCommandCodeDoneSettleExecutor(PANE_KEY, parkedWatcherSettle)
openCommandCodeDoneSettle(PANE_KEY, 'Fix the spinner')
vi.advanceTimersByTime(COMMAND_CODE_OUTPUT_DONE_SETTLE_MS - 100)
// Reveal: the remounted pane registers before the parked watcher releases.
const revealedPaneSettle = vi.fn()
setCommandCodeDoneSettleExecutor(PANE_KEY, revealedPaneSettle)
releaseParkedWatcher()
vi.advanceTimersByTime(100)
expect(parkedWatcherSettle).not.toHaveBeenCalled()
expect(revealedPaneSettle).toHaveBeenCalledExactlyOnceWith('Fix the spinner')
})
// Why identity-checked: a late release from the previous owner must not unregister the successor.
it('ignores a stale release once a successor has registered', () => {
const releaseFirst = setCommandCodeDoneSettleExecutor(PANE_KEY, vi.fn())
const successorSettle = vi.fn()
setCommandCodeDoneSettleExecutor(PANE_KEY, successorSettle)
releaseFirst()
openCommandCodeDoneSettle(PANE_KEY, 'Fix the spinner')
vi.advanceTimersByTime(COMMAND_CODE_OUTPUT_DONE_SETTLE_MS)
expect(successorSettle).toHaveBeenCalledExactlyOnceWith('Fix the spinner')
})
it('drops the window when a working repaint cancels it', () => {
const settle = vi.fn()
setCommandCodeDoneSettleExecutor(PANE_KEY, settle)
openCommandCodeDoneSettle(PANE_KEY, 'Fix the spinner')
cancelCommandCodeDoneSettle(PANE_KEY)
vi.advanceTimersByTime(COMMAND_CODE_OUTPUT_DONE_SETTLE_MS * 2)
expect(settle).not.toHaveBeenCalled()
})
// Why: a pane torn down with no successor has no row worth completing.
it('fires harmlessly when every owner released before the deadline', () => {
const release = setCommandCodeDoneSettleExecutor(PANE_KEY, vi.fn())
openCommandCodeDoneSettle(PANE_KEY, 'Fix the spinner')
release()
expect(() => vi.advanceTimersByTime(COMMAND_CODE_OUTPUT_DONE_SETTLE_MS)).not.toThrow()
})
it('re-opening replaces the pending window rather than stacking a second one', () => {
const settle = vi.fn()
setCommandCodeDoneSettleExecutor(PANE_KEY, settle)
openCommandCodeDoneSettle(PANE_KEY, 'first turn')
vi.advanceTimersByTime(COMMAND_CODE_OUTPUT_DONE_SETTLE_MS - 100)
openCommandCodeDoneSettle(PANE_KEY, 'second turn')
vi.advanceTimersByTime(COMMAND_CODE_OUTPUT_DONE_SETTLE_MS)
expect(settle).toHaveBeenCalledExactlyOnceWith('second turn')
})
it('scopes windows per pane key', () => {
const settle = vi.fn()
const otherSettle = vi.fn()
setCommandCodeDoneSettleExecutor(PANE_KEY, settle)
setCommandCodeDoneSettleExecutor(OTHER_PANE_KEY, otherSettle)
openCommandCodeDoneSettle(PANE_KEY, 'mine')
openCommandCodeDoneSettle(OTHER_PANE_KEY, 'theirs')
cancelCommandCodeDoneSettle(PANE_KEY)
vi.advanceTimersByTime(COMMAND_CODE_OUTPUT_DONE_SETTLE_MS)
expect(settle).not.toHaveBeenCalled()
expect(otherSettle).toHaveBeenCalledExactlyOnceWith('theirs')
})
})
@@ -0,0 +1,64 @@
/**
* Cross-mount owner of Command Code's done-settle window.
*
* Why: park unmounts the pane and reveal disposes the parked watcher, both
* possibly mid-settle, and neither successor can re-observe the idle composer
* that opened the window. Owning the deadline here means park cannot strand the
* row at 'working' and reveal need not complete the turn early; only the row
* write (routing + title slot) stays with whoever currently owns the pane.
*/
// Mirrors the mounted and parked policies: the settle window must be identical
// whether the pane is mounted or parked, or park/reveal changes completion timing.
export const COMMAND_CODE_OUTPUT_DONE_SETTLE_MS = 1500
type CommandCodeDoneSettleExecutor = (normalizedPrompt: string) => void
const executorByPaneKey = new Map<string, CommandCodeDoneSettleExecutor>()
const timerByPaneKey = new Map<string, ReturnType<typeof setTimeout>>()
/** Registers the current writer for this pane; returns its release.
* Last registrant wins by design: park and reveal each hand the pane to a new
* owner while the predecessor is still registered, so refusing the overwrite
* would leave the row with an owner that can no longer write it. */
export function setCommandCodeDoneSettleExecutor(
paneKey: string,
execute: CommandCodeDoneSettleExecutor
): () => void {
executorByPaneKey.set(paneKey, execute)
return () => {
// Why identity-checked: on reveal the remounted pane registers before the parked watcher releases.
if (executorByPaneKey.get(paneKey) === execute) {
executorByPaneKey.delete(paneKey)
}
}
}
export function openCommandCodeDoneSettle(paneKey: string, normalizedPrompt: string): void {
cancelCommandCodeDoneSettle(paneKey)
timerByPaneKey.set(
paneKey,
setTimeout(() => {
timerByPaneKey.delete(paneKey)
// Why optional: a pane torn down with no successor has no row worth completing.
executorByPaneKey.get(paneKey)?.(normalizedPrompt)
}, COMMAND_CODE_OUTPUT_DONE_SETTLE_MS)
)
}
export function cancelCommandCodeDoneSettle(paneKey: string): void {
const timer = timerByPaneKey.get(paneKey)
if (timer !== undefined) {
clearTimeout(timer)
timerByPaneKey.delete(paneKey)
}
}
/** Test-only: drops every pending window so suites cannot leak timers across cases. */
export function _resetCommandCodeDoneSettlesForTest(): void {
for (const timer of timerByPaneKey.values()) {
clearTimeout(timer)
}
timerByPaneKey.clear()
executorByPaneKey.clear()
}
@@ -0,0 +1,61 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { RepoConnection } from '../../../../shared/workspace-session-terminal-buffers'
import { captureForceParkedWorktreeBuffers } from './force-park-buffer-capture'
import { shutdownBufferCaptures } from './shutdown-buffer-captures'
const LOCAL_REPO: RepoConnection = {
id: 'repo',
connectionId: null,
executionHostId: 'local'
}
const SSH_REPO: RepoConnection = {
id: 'repo',
connectionId: 'conn-1',
executionHostId: null
}
afterEach(() => {
shutdownBufferCaptures.clear()
})
describe('captureForceParkedWorktreeBuffers', () => {
it('skips the capture for a local-repo worktree so a stored buffer survives force-park', () => {
const capture = vi.fn()
shutdownBufferCaptures.set('tab-1', capture)
const captured = captureForceParkedWorktreeBuffers({
worktreeId: 'repo::/repo/worktree',
tabIds: ['tab-1'],
repos: [LOCAL_REPO]
})
expect(captured).toBe(true)
expect(capture).not.toHaveBeenCalled()
})
it('captures remote worktree tabs without local buffers and reports full coverage', () => {
const capture = vi.fn()
shutdownBufferCaptures.set('tab-1', capture)
const captured = captureForceParkedWorktreeBuffers({
worktreeId: 'repo::/repo/worktree',
tabIds: ['tab-1'],
repos: [SSH_REPO]
})
expect(captured).toBe(true)
expect(capture).toHaveBeenCalledWith({ includeLocalBuffers: false })
})
it('reports an incomplete episode when a tab has no registered capture', () => {
shutdownBufferCaptures.set('tab-1', vi.fn())
const captured = captureForceParkedWorktreeBuffers({
worktreeId: 'repo::/repo/worktree',
tabIds: ['tab-1', 'tab-mid-remount'],
repos: [SSH_REPO]
})
expect(captured).toBe(false)
})
})
@@ -0,0 +1,29 @@
import {
shouldPreserveTerminalScrollbackBuffers,
type RepoConnection
} from '../../../../shared/workspace-session-terminal-buffers'
import { captureTerminalShutdownBuffersBestEffort } from './shutdown-buffer-captures'
type ForceParkedWorktreeCaptureArgs = {
worktreeId: string
tabIds: readonly string[]
repos: readonly RepoConnection[]
}
/** Serialize a force-parked worktree's panes before eviction unmounts them.
* Returns whether the episode covered every tab; false leaves it unmarked so a later episode retries. */
export function captureForceParkedWorktreeBuffers({
worktreeId,
tabIds,
repos
}: ForceParkedWorktreeCaptureArgs): boolean {
// Why skip local worktrees: includeLocalBuffers:false serializes nothing for them, so the only
// effect left is setTabLayout replacing away a stored buffer (e.g. an exited setup pane's output).
if (!shouldPreserveTerminalScrollbackBuffers(worktreeId, repos)) {
return true
}
const { requested, captured } = captureTerminalShutdownBuffersBestEffort(tabIds, {
includeLocalBuffers: false
})
return captured === requested
}
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { TerminalSideEffectFact } from '../../../../shared/terminal-side-effect-facts'
import type { ParkedTerminalByteWatcherOptions } from './parked-terminal-byte-watcher'
import type * as ParkedTerminalCommandStatus from './parked-terminal-command-status'
const PTY_ID = 'pty-parked-1'
const TAB_ID = 'tab-1'
@@ -34,6 +35,7 @@ type MockStoreState = {
markTerminalPaneUnread: ReturnType<typeof vi.fn>
setCacheTimerStartedAt: ReturnType<typeof vi.fn>
observeTerminalGitHubPullRequestLink: ReturnType<typeof vi.fn>
agentStatusByPaneKey: Record<string, { state: string; prompt: string; agentType?: string }>
}
const dispatchTerminalNotification = vi.fn()
@@ -43,6 +45,20 @@ vi.mock('./use-notification-dispatch', () => ({
dispatchTerminalNotification
}))
// Why: command-status semantics are covered in parked-terminal-command-status.test.ts;
// these tests only prove the watcher wires bytes/facts into the policy.
const commandStatusPolicy = {
onCommandFinished: vi.fn(),
onCommandCodeWorking: vi.fn(),
onCommandCodeDone: vi.fn(),
dispose: vi.fn()
}
// Partial mock: readInFlightCommandCodeTurn stays real so detector seeding reads the store.
vi.mock('./parked-terminal-command-status', async (importOriginal) => ({
...(await importOriginal<typeof ParkedTerminalCommandStatus>()),
createParkedTerminalCommandStatusPolicy: vi.fn(() => commandStatusPolicy)
}))
vi.mock('@/lib/terminal-theme', () => ({
getSystemPrefersDark: () => true
}))
@@ -72,7 +88,8 @@ function createMockStoreState(): MockStoreState {
markTerminalTabUnread: vi.fn(),
markTerminalPaneUnread: vi.fn(),
setCacheTimerStartedAt: vi.fn(),
observeTerminalGitHubPullRequestLink: vi.fn()
observeTerminalGitHubPullRequestLink: vi.fn(),
agentStatusByPaneKey: {}
}
}
@@ -110,6 +127,10 @@ describe('startParkedTerminalByteWatcher', () => {
vi.resetModules()
vi.useFakeTimers()
dispatchTerminalNotification.mockClear()
commandStatusPolicy.onCommandFinished.mockClear()
commandStatusPolicy.onCommandCodeWorking.mockClear()
commandStatusPolicy.onCommandCodeDone.mockClear()
commandStatusPolicy.dispose.mockClear()
onData = null
mockStoreState = createMockStoreState()
;(globalThis as { window: typeof window }).window = {
@@ -372,6 +393,65 @@ describe('startParkedTerminalByteWatcher', () => {
dispose()
})
it('scans OSC 133;D bytes into the parked command policy and disposes it with the watcher', async () => {
const { dispose } = await startWatcher()
emit('\x1b]133;D;0\x07')
expect(commandStatusPolicy.onCommandFinished).toHaveBeenCalledWith(0)
dispose()
expect(commandStatusPolicy.dispose).toHaveBeenCalledTimes(1)
})
it('feeds Command Code output through the parked byte detector', async () => {
const { dispose } = await startWatcher()
emit('# Command Code v0.27.2')
emit('⌘ Parsing...')
expect(commandStatusPolicy.onCommandCodeWorking).toHaveBeenCalledTimes(1)
dispose()
})
it('feeds a Command Code return to the idle composer through as done', async () => {
const { dispose } = await startWatcher()
emit('# Command Code v0.27.2\r\n')
emit('❯ Fix the spinner\r\n')
emit('\r\n❯ Ask your question...\r\n')
expect(commandStatusPolicy.onCommandCodeDone).toHaveBeenCalledWith('Fix the spinner')
dispose()
})
it('arms the Command Code scrape from a turn already in flight at park time', async () => {
// Why: the banner scrolled away long before the park, so only the live
// status row can tell the fresh detector this is a Command Code TUI.
mockStoreState.agentStatusByPaneKey = {
[PANE_KEY]: { state: 'working', prompt: 'Fix the spinner', agentType: 'command-code' }
}
const { dispose } = await startWatcher()
emit('\r\n❯ Ask your question...\r\n')
expect(commandStatusPolicy.onCommandCodeDone).toHaveBeenCalledWith('Fix the spinner')
dispose()
})
it('leaves the scrape unarmed when the parked pane has no in-flight Command Code turn', async () => {
mockStoreState.agentStatusByPaneKey = {
[PANE_KEY]: { state: 'done', prompt: 'Fix the spinner', agentType: 'command-code' }
}
const { dispose } = await startWatcher()
emit('\r\n❯ Ask your question...\r\n')
emit('⌘ Parsing...')
expect(commandStatusPolicy.onCommandCodeDone).not.toHaveBeenCalled()
expect(commandStatusPolicy.onCommandCodeWorking).not.toHaveBeenCalled()
dispose()
})
it('fires completion when seeded with a working title and the agent goes idle while parked', async () => {
// Why: the pane was working at park time; the watcher's fresh tracker
// must be seeded or this working→idle transition can never fire.
@@ -575,6 +655,32 @@ describe('startParkedTerminalByteWatcher', () => {
dispose()
})
it('routes command lifecycle facts into the parked command policy', async () => {
enableMainAuthority()
const { dispose } = await startWatcher()
await dispatchFacts([
{ kind: 'command-finished', exitCode: 0 },
{ kind: 'command-code-working', prompt: 'Fix the spinner' },
{ kind: 'command-code-done', prompt: 'Fix the spinner' }
])
expect(commandStatusPolicy.onCommandFinished).toHaveBeenCalledWith(0)
expect(commandStatusPolicy.onCommandCodeWorking).toHaveBeenCalledWith('Fix the spinner')
expect(commandStatusPolicy.onCommandCodeDone).toHaveBeenCalledWith('Fix the spinner')
dispose()
})
it('ignores replayed command lifecycle facts (no-attention-replay rule)', async () => {
enableMainAuthority()
const { dispose } = await startWatcher()
await dispatchFacts([{ kind: 'command-finished', exitCode: 0 }], { seq: 5, replay: true })
expect(commandStatusPolicy.onCommandFinished).not.toHaveBeenCalled()
dispose()
})
it('does not request a title snapshot for an ordinary parked watcher', async () => {
enableMainAuthority()
const getSideEffectSnapshot = vi.fn()
@@ -16,6 +16,12 @@ import {
isAgentTaskCompleteOsNotificationEnabledFromState,
isAgentTaskCompleteTrackingEnabledFromState
} from './agent-task-complete-policy'
import { createCommandCodeOutputStatusDetector } from '../../../../shared/command-code-output-status'
import { createOsc133CommandFinishedScanner } from '../../../../shared/terminal-osc133-command-finished'
import {
createParkedTerminalCommandStatusPolicy,
readInFlightCommandCodeTurn
} from './parked-terminal-command-status'
import { startParkedTerminalMode2031Responder } from './parked-terminal-mode2031-responder'
import { subscribeToPtyData } from './pty-data-sidecar-subscriptions'
import { createPtyOutputProcessor } from './pty-transport'
@@ -187,6 +193,16 @@ export function startParkedTerminalByteWatcher(
}
}
// Why: command-lifecycle signals drive store-level policy only (git nudge, SSH same-turn
// status drop, Command Code seed/settle); the pane-coupled parts stay with the mounted pane.
const commandStatusPolicy = createParkedTerminalCommandStatusPolicy({
ptyId,
worktreeId,
tabId,
paneId,
paneKey
})
// Why: with the authority switch on, the fact consumer is the single policy consumer — registering byte parsers too would double-fire bells.
const mainSideEffectAuthority = isMainTerminalSideEffectAuthorityForPty({
settings: useAppStore.getState().settings,
@@ -214,12 +230,30 @@ export function startParkedTerminalByteWatcher(
const observeTerminalGitHubPRLink = mainSideEffectAuthority
? null
: createTerminalGitHubPRLinkDetector()
// Why (byte-parser mode only): mode parity — main's tracker emits these as facts; the byte
// path scans the same shared parsers the mounted kill-switch-off pane uses.
const commandFinishedScanner = mainSideEffectAuthority
? null
: createOsc133CommandFinishedScanner(commandStatusPolicy.onCommandFinished)
// Why the seed: this detector is recreated per park cycle with no startup command
// to fast-arm it, and a Command Code TUI parked mid-turn is long past its banner —
// unseeded it would never scrape the turn's return to the idle composer.
const commandCodeOutputStatusDetector = mainSideEffectAuthority
? null
: createCommandCodeOutputStatusDetector({
inFlightTurn: readInFlightCommandCodeTurn(paneKey),
onWorking: commandStatusPolicy.onCommandCodeWorking,
onDone: commandStatusPolicy.onCommandCodeDone
})
const unregisterFactConsumer = mainSideEffectAuthority
? registerTerminalSideEffectFactConsumer({
ptyId,
// Why: ordinary park already has a pane-owned title; the flag below requests a snapshot only when no pane did.
callbacks: {
...sideEffectCallbacks,
onCommandFinished: commandStatusPolicy.onCommandFinished,
onCommandCodeWorking: commandStatusPolicy.onCommandCodeWorking,
onCommandCodeDone: commandStatusPolicy.onCommandCodeDone,
onPrLink: (link) =>
useAppStore.getState().observeTerminalGitHubPullRequestLink(worktreeId, link),
// Why (gate mode only): the 2031 subscribe arrives as a fact, but the reply stays here — query authority stays with the view/watcher (invariant 6).
@@ -247,6 +281,8 @@ export function startParkedTerminalByteWatcher(
: subscribeToPtyData(ptyId, (data) => {
// Why: empty pane callbacks — no xterm to deliver bytes to, the watcher wants only the parser side effects.
processor.processData(data, {})
commandFinishedScanner?.scan(data)
commandCodeOutputStatusDetector?.observe(data)
if (observeTerminalGitHubPRLink) {
for (const link of observeTerminalGitHubPRLink(data)) {
useAppStore.getState().observeTerminalGitHubPullRequestLink(worktreeId, link)
@@ -266,6 +302,8 @@ export function startParkedTerminalByteWatcher(
unregisterFactConsumer?.()
// Why: clears tracker/timer/detector state so the watcher can't fire after the revealed pane's live parsers take over.
processor?.clearAccumulatedState()
commandFinishedScanner?.reset()
commandStatusPolicy.dispose()
clearBellNotificationTimer()
clearAgentTaskCompleteTimer()
pendingBellNotification = false
@@ -0,0 +1,345 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
const PTY_ID_LOCAL = 'pty-1'
const PTY_ID_SSH = 'ssh:target-1@@pty-9'
const TAB_ID = 'tab-1'
const WORKTREE_ID = 'repo-1::/tmp/wt-1'
const PANE_KEY = `${TAB_ID}:11111111-1111-4111-8111-111111111111`
const PANE_ID = 1
// Mirrors COMMAND_CODE_OUTPUT_DONE_SETTLE_MS.
const DONE_SETTLE_MS = 1500
const ROUTING = { connectionId: null }
type MockStoreState = {
agentStatusByPaneKey: Record<string, AgentStatusEntry | undefined>
runtimePaneTitlesByTabId: Record<string, Record<number, string | undefined>>
setAgentStatus: ReturnType<typeof vi.fn>
dropAgentStatus: ReturnType<typeof vi.fn>
clearAgentLaunchConfig: ReturnType<typeof vi.fn>
}
let mockStoreState: MockStoreState
const dispatchTerminalCommandFinishedEvent = vi.fn()
const resolveLiveAgentStatusConnectionRouting = vi.fn()
const getConnectionIdFromState = vi.fn()
vi.mock('@/store', () => ({
useAppStore: { getState: () => mockStoreState }
}))
vi.mock('@/hooks/terminal-command-finished-event', () => ({
dispatchTerminalCommandFinishedEvent
}))
vi.mock('@/lib/agent-status-connection-ownership', () => ({
resolveLiveAgentStatusConnectionRouting
}))
vi.mock('@/lib/connection-owner-resolution', () => ({
getConnectionIdFromState
}))
function makeMockStoreState(): MockStoreState {
return {
agentStatusByPaneKey: {},
runtimePaneTitlesByTabId: { [TAB_ID]: { [PANE_ID]: '✳ Build feature' } },
setAgentStatus: vi.fn(),
dropAgentStatus: vi.fn(),
clearAgentLaunchConfig: vi.fn()
}
}
function makeStatusEntry(overrides: Partial<AgentStatusEntry> = {}): AgentStatusEntry {
return {
state: 'working',
prompt: 'build the feature',
agentType: 'claude',
updatedAt: 1000,
stateStartedAt: 1000,
...overrides
} as AgentStatusEntry
}
async function createPolicy(ptyId: string) {
const { createParkedTerminalCommandStatusPolicy } =
await import('./parked-terminal-command-status')
return createParkedTerminalCommandStatusPolicy({
ptyId,
worktreeId: WORKTREE_ID,
tabId: TAB_ID,
paneId: PANE_ID,
paneKey: PANE_KEY
})
}
describe('createParkedTerminalCommandStatusPolicy', () => {
beforeEach(() => {
vi.resetModules()
vi.useFakeTimers()
dispatchTerminalCommandFinishedEvent.mockClear()
resolveLiveAgentStatusConnectionRouting.mockReset().mockReturnValue(ROUTING)
getConnectionIdFromState.mockReset().mockReturnValue(null)
mockStoreState = makeMockStoreState()
})
afterEach(() => {
vi.useRealTimers()
})
it('seeds a Command Code working row with the current pane title', async () => {
const policy = await createPolicy(PTY_ID_LOCAL)
policy.onCommandCodeWorking('Fix the spinner')
expect(mockStoreState.setAgentStatus).toHaveBeenCalledWith(
PANE_KEY,
{ state: 'working', prompt: 'Fix the spinner', agentType: 'command-code' },
'✳ Build feature',
undefined,
ROUTING
)
policy.dispose()
})
it('writes nothing when connection routing does not resolve', async () => {
resolveLiveAgentStatusConnectionRouting.mockReturnValue(undefined)
const policy = await createPolicy(PTY_ID_LOCAL)
policy.onCommandCodeWorking('Fix the spinner')
expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled()
policy.dispose()
})
it('leaves a settled done row alone when working repeats the same prompt', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({
state: 'done',
prompt: 'Fix the spinner',
agentType: 'command-code'
})
const policy = await createPolicy(PTY_ID_LOCAL)
policy.onCommandCodeWorking('Fix the spinner')
policy.onCommandCodeWorking('')
expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled()
policy.dispose()
})
it('settles a still-working Command Code row to done after the settle window', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({
state: 'working',
prompt: 'Fix the spinner',
agentType: 'command-code'
})
const policy = await createPolicy(PTY_ID_LOCAL)
policy.onCommandCodeDone('Fix the spinner')
expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled()
vi.advanceTimersByTime(DONE_SETTLE_MS)
expect(mockStoreState.setAgentStatus).toHaveBeenCalledWith(
PANE_KEY,
{ state: 'done', prompt: 'Fix the spinner', agentType: 'command-code' },
'✳ Build feature',
undefined,
ROUTING
)
policy.dispose()
})
it('abandons the done settle when another agent owns the row by then', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({ agentType: 'claude' })
const policy = await createPolicy(PTY_ID_LOCAL)
policy.onCommandCodeDone('Fix the spinner')
vi.advanceTimersByTime(DONE_SETTLE_MS)
expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled()
policy.dispose()
})
it('cancels a pending done settle when a working repaint arrives', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({
state: 'working',
prompt: 'Fix the spinner',
agentType: 'command-code'
})
const policy = await createPolicy(PTY_ID_LOCAL)
policy.onCommandCodeDone('Fix the spinner')
policy.onCommandCodeWorking('Fix the spinner')
vi.advanceTimersByTime(DONE_SETTLE_MS * 2)
const states = mockStoreState.setAgentStatus.mock.calls.map(([, payload]) => payload.state)
expect(states).toEqual(['working'])
policy.dispose()
})
// Why: reveal disposes the watcher mid-settle. Flushing would complete the turn early
// and the same-prompt-done guard then drops the genuine working repaint, so the window
// transfers to the remounted pane instead — the row stays 'working' across the boundary.
it('dispose hands the pending settle to the remounted pane instead of completing it early', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({
state: 'working',
prompt: 'Fix the spinner',
agentType: 'command-code'
})
const policy = await createPolicy(PTY_ID_LOCAL)
const { setCommandCodeDoneSettleExecutor } = await import('./command-code-done-settle')
policy.onCommandCodeDone('Fix the spinner')
vi.advanceTimersByTime(DONE_SETTLE_MS - 1)
const revealedPaneSettle = vi.fn()
setCommandCodeDoneSettleExecutor(PANE_KEY, revealedPaneSettle)
policy.dispose()
expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
expect(revealedPaneSettle).toHaveBeenCalledExactlyOnceWith('Fix the spinner')
})
// Why: the transferred window is still a settle window — a working repaint from the
// revealed pane before the original deadline must cancel it, not race it.
it('lets a working repaint after the handoff cancel the transferred settle', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({
state: 'working',
prompt: 'Fix the spinner',
agentType: 'command-code'
})
const policy = await createPolicy(PTY_ID_LOCAL)
const { cancelCommandCodeDoneSettle, setCommandCodeDoneSettleExecutor } =
await import('./command-code-done-settle')
policy.onCommandCodeDone('Fix the spinner')
const revealedPaneSettle = vi.fn()
setCommandCodeDoneSettleExecutor(PANE_KEY, revealedPaneSettle)
policy.dispose()
cancelCommandCodeDoneSettle(PANE_KEY)
vi.advanceTimersByTime(DONE_SETTLE_MS * 2)
expect(revealedPaneSettle).not.toHaveBeenCalled()
expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled()
})
it('dispose does not flush a settle a working repaint already cancelled', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({
state: 'working',
prompt: 'Fix the spinner',
agentType: 'command-code'
})
const policy = await createPolicy(PTY_ID_LOCAL)
policy.onCommandCodeDone('Fix the spinner')
policy.onCommandCodeWorking('Fix the spinner')
policy.dispose()
const states = mockStoreState.setAgentStatus.mock.calls.map(([, payload]) => payload.state)
expect(states).toEqual(['working'])
})
it('dispose does not flush when another agent owns the row by then', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({ agentType: 'claude' })
const policy = await createPolicy(PTY_ID_LOCAL)
policy.onCommandCodeDone('Fix the spinner')
policy.dispose()
expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled()
})
it('dispose after the settle fired writes done exactly once', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({
state: 'working',
prompt: 'Fix the spinner',
agentType: 'command-code'
})
const policy = await createPolicy(PTY_ID_LOCAL)
policy.onCommandCodeDone('Fix the spinner')
vi.advanceTimersByTime(DONE_SETTLE_MS)
policy.dispose()
expect(mockStoreState.setAgentStatus).toHaveBeenCalledTimes(1)
})
it('nudges git UI on command finished for every PTY class', async () => {
const local = await createPolicy(PTY_ID_LOCAL)
local.onCommandFinished(0)
local.dispose()
const ssh = await createPolicy(PTY_ID_SSH)
ssh.onCommandFinished(0)
ssh.dispose()
expect(dispatchTerminalCommandFinishedEvent).toHaveBeenCalledTimes(2)
expect(dispatchTerminalCommandFinishedEvent).toHaveBeenCalledWith(WORKTREE_ID)
})
it('drops a same-turn status row on command finished for SSH PTYs only', async () => {
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry()
const local = await createPolicy(PTY_ID_LOCAL)
local.onCommandFinished(0)
// Why: local drops need the mounted pane's foreground process-confirm ladder
// (leaked nested-shell 133;D protection), so the watcher must not drop them.
expect(mockStoreState.dropAgentStatus).not.toHaveBeenCalled()
local.dispose()
const ssh = await createPolicy(PTY_ID_SSH)
ssh.onCommandFinished(0)
expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(PANE_KEY)
ssh.dispose()
})
it('clears the launch registry on SSH command finished when no status row exists', async () => {
const ssh = await createPolicy(PTY_ID_SSH)
ssh.onCommandFinished(0)
expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledWith(PANE_KEY)
expect(mockStoreState.dropAgentStatus).not.toHaveBeenCalled()
ssh.dispose()
})
it('does nothing after dispose', async () => {
const ssh = await createPolicy(PTY_ID_SSH)
ssh.dispose()
ssh.onCommandFinished(0)
ssh.onCommandCodeWorking('Fix the spinner')
expect(dispatchTerminalCommandFinishedEvent).not.toHaveBeenCalled()
expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled()
})
})
describe('readInFlightCommandCodeTurn', () => {
beforeEach(() => {
vi.resetModules()
mockStoreState = makeMockStoreState()
})
it('returns only a working command-code turn', async () => {
const { readInFlightCommandCodeTurn } = await import('./parked-terminal-command-status')
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({
state: 'working',
prompt: 'Fix the spinner',
agentType: 'command-code'
})
expect(readInFlightCommandCodeTurn(PANE_KEY)).toEqual({ prompt: 'Fix the spinner' })
// Why 'done' excluded: a stale done row would arm the scrape against whatever
// process replaced the Command Code TUI.
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({
state: 'done',
prompt: 'Fix the spinner',
agentType: 'command-code'
})
expect(readInFlightCommandCodeTurn(PANE_KEY)).toBeNull()
mockStoreState.agentStatusByPaneKey[PANE_KEY] = makeStatusEntry({ agentType: 'claude' })
expect(readInFlightCommandCodeTurn(PANE_KEY)).toBeNull()
delete mockStoreState.agentStatusByPaneKey[PANE_KEY]
expect(readInFlightCommandCodeTurn(PANE_KEY)).toBeNull()
})
})
@@ -0,0 +1,197 @@
/**
* Parked-pane command-lifecycle status policy.
* Why: parking unmounts TerminalPane, so OSC 133;D and Command Code scrape signals went dark.
* This ports the store-level subset of pty-connection's handlers; the pane-coupled parts
* (foreground process-confirm ladder, key-intent interrupt inference) stay with the mounted pane.
*/
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id'
import { dispatchTerminalCommandFinishedEvent } from '@/hooks/terminal-command-finished-event'
import { resolveLiveAgentStatusConnectionRouting } from '@/lib/agent-status-connection-ownership'
import { getConnectionIdFromState } from '@/lib/connection-owner-resolution'
import { useAppStore } from '@/store'
import {
cancelCommandCodeDoneSettle,
openCommandCodeDoneSettle,
setCommandCodeDoneSettleExecutor
} from './command-code-done-settle'
export type ParkedTerminalCommandStatusPolicy = {
onCommandFinished: (bestEffortExitCode: number | null) => void
onCommandCodeWorking: (prompt: string) => void
onCommandCodeDone: (prompt: string) => void
dispose: () => void
}
// Why only 'working': an in-flight turn is the one state a recreated detector can still
// resolve, and it proves the Command Code TUI is live — a stale 'done' row would arm the
// scrape against whatever process replaced it. Shared by parked watchers and the reveal
// remount, which both recreate the detector long past the banner.
export function readInFlightCommandCodeTurn(paneKey: string): { prompt: string } | null {
const entry = useAppStore.getState().agentStatusByPaneKey?.[paneKey]
if (entry?.agentType !== 'command-code' || entry.state !== 'working') {
return null
}
return { prompt: entry.prompt }
}
export function createParkedTerminalCommandStatusPolicy(options: {
ptyId: string
worktreeId: string
tabId: string
/** PaneManager pane id whose runtime-title slot the watcher writes; read for status title pairing. */
paneId: number
paneKey: string
}): ParkedTerminalCommandStatusPolicy {
const { ptyId, worktreeId, tabId, paneId, paneKey } = options
let disposed = false
const clearCommandCodeOutputDoneTimer = (): void => cancelCommandCodeDoneSettle(paneKey)
const resolveRouting = (): ReturnType<typeof resolveLiveAgentStatusConnectionRouting> => {
if (disposed) {
return undefined
}
const state = useAppStore.getState()
return resolveLiveAgentStatusConnectionRouting({
state,
paneKey,
ptyId,
expectedConnectionId: getConnectionIdFromState(state, worktreeId)
})
}
// Port of pty-connection's dropCommandFinishedStatusIfSameTurn, minus the interrupt-inference
// option: parked panes receive no key events, so inference never has evidence here.
const dropCommandFinishedStatusIfSameTurn = (entry: AgentStatusEntry | undefined): void => {
const state = useAppStore.getState()
if (!entry) {
// Why: an Orca-started agent can exit before its first hook status; clear the launch
// registry on command exit like the mounted path does.
state.clearAgentLaunchConfig(paneKey)
return
}
const current = state.agentStatusByPaneKey[paneKey]
if (!current) {
state.clearAgentLaunchConfig(paneKey)
return
}
const unchanged =
current.state === entry.state &&
current.prompt === entry.prompt &&
current.updatedAt === entry.updatedAt &&
current.stateStartedAt === entry.stateStartedAt &&
current.agentType === entry.agentType
if (!unchanged) {
return
}
state.dropAgentStatus(paneKey)
}
// Complete the row only while it is still this turn's command-code/working entry.
const settleCommandCodeDone = (normalizedPrompt: string): void => {
const routing = resolveRouting()
if (!routing) {
return
}
const currentState = useAppStore.getState()
const currentEntry = currentState.agentStatusByPaneKey[paneKey]
if (currentEntry?.agentType !== 'command-code' || currentEntry.state !== 'working') {
return
}
const currentPrompt = currentEntry.prompt.trim()
if (currentPrompt && currentPrompt !== normalizedPrompt) {
return
}
const currentTitle = currentState.runtimePaneTitlesByTabId?.[tabId]?.[paneId]
currentState.setAgentStatus(
paneKey,
{
state: 'done',
prompt: currentPrompt || normalizedPrompt,
agentType: 'command-code'
},
currentTitle,
undefined,
routing
)
}
// Why the shared window: reveal disposes this watcher mid-settle and the remounted pane
// cannot re-observe the already-passed idle composer, so the deadline outlives whichever
// side owns the row — cancelling would strand 'working', flushing would complete the turn
// unrecoverably early (the same-prompt-done guard then drops a genuine working repaint).
const releaseCommandCodeDoneSettleExecutor = setCommandCodeDoneSettleExecutor(
paneKey,
settleCommandCodeDone
)
return {
onCommandFinished: (): void => {
if (disposed) {
return
}
// Why: the finished command may have moved HEAD or the index (an agent running
// `git checkout` in a parked worktree); nudge git UI now instead of waiting for a poll.
dispatchTerminalCommandFinishedEvent(worktreeId)
// Why: drop the same-turn status row only for SSH PTYs — exact parity with the mounted
// path, whose foreground tracker refuses SSH ids and drops un-probed. Local PTYs need
// pty-connection's process-confirm ladder to tell a leaked nested-shell 133;D from a
// real agent exit, so their drop stays with the mounted pane.
if (parseAppSshPtyId(ptyId) === null) {
return
}
dropCommandFinishedStatusIfSameTurn(useAppStore.getState().agentStatusByPaneKey[paneKey])
},
// Port of pty-connection's seedCommandCodeOutputWorkingStatus (store-level only).
onCommandCodeWorking: (prompt: string): void => {
clearCommandCodeOutputDoneTimer()
const routing = resolveRouting()
if (!routing) {
return
}
const currentState = useAppStore.getState()
const currentEntry = currentState.agentStatusByPaneKey[paneKey]
const currentTitle = currentState.runtimePaneTitlesByTabId?.[tabId]?.[paneId]
const normalizedPrompt = prompt.trim()
if (
currentEntry?.agentType === 'command-code' &&
currentEntry.state === 'done' &&
(!normalizedPrompt || normalizedPrompt === currentEntry.prompt.trim())
) {
return
}
currentState.setAgentStatus(
paneKey,
{
state: 'working',
prompt:
normalizedPrompt || (currentEntry?.state === 'working' ? currentEntry.prompt : ''),
agentType: 'command-code'
},
currentTitle,
undefined,
routing
)
},
// Port of pty-connection's scheduleCommandCodeOutputDoneStatus: Command Code keeps rendering
// the composer while tools run, so only complete the row if no active repaint arrives.
onCommandCodeDone: (prompt: string): void => {
const normalizedPrompt = prompt.trim()
if (!normalizedPrompt) {
cancelCommandCodeDoneSettle(paneKey)
return
}
openCommandCodeDoneSettle(paneKey, normalizedPrompt)
},
dispose: (): void => {
// Why release, not flush: the settle window belongs to the turn and outlives this
// watcher, so the remounted pane inherits the remaining deadline and a working
// repaint arriving before it still cancels the completion.
releaseCommandCodeDoneSettleExecutor()
disposed = true
}
}
}
@@ -53,6 +53,18 @@ async function drainFakeTimerWork(limit = 20): Promise<void> {
vi.clearAllTimers()
}
// Why: a reveal remount reads the still-live park watcher entry at connect time to
// tell itself apart from an in-place reattach; the host disposes it a beat later.
async function parkTabForReveal(tabId: string, ptyId: string): Promise<void> {
const { parkedWatchersByTabId } = await import('./terminal-parked-watcher-registry')
parkedWatchersByTabId.set(tabId, {
worktreeId: 'wt-1',
tabPtyId: ptyId,
paneIdByPtyId: new Map([[ptyId, 1]]),
disposersByPtyId: new Map([[ptyId, () => {}]])
})
}
async function drainPendingTimeouts(pendingTimeouts: (() => void)[], limit = 100): Promise<void> {
let iterations = 0
while (pendingTimeouts.length > 0) {
@@ -19859,6 +19871,89 @@ describe('connectPanePty', () => {
expect(api.pty.signal).toHaveBeenCalledWith('leaf-session', 'SIGWINCH')
})
it('falls back to relay replay when the SSH model snapshot stalls', async () => {
const { connectPanePty } = await import('./pty-connection')
const { SSH_REATTACH_MODEL_SNAPSHOT_TIMEOUT_MS } = await import('./ssh-reattach-model-restore')
const sshPtyId = toAppSshPtyId('conn-1', 'relay-pty-1')
const transport = createMockTransport(sshPtyId)
transport.connect.mockImplementation(async () => {
transport.getPtyId.mockReturnValue(sshPtyId)
return { id: sshPtyId, isReattach: true, replay: 'relay-fallback-output' }
})
transportFactoryQueue.push(transport)
vi.mocked(window.api.pty.getMainBufferSnapshot).mockReturnValue(new Promise(() => {}))
// Why parked: only a reveal remount probes main's model — the pane reads the
// still-live park watcher entry at connect time to tell the two apart.
await parkTabForReveal('tab-1', sshPtyId)
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'conn-1' }],
deferredSshReconnectTargets: ['conn-1'],
deferredSshSessionIdsByTabId: { 'tab-1': sshPtyId }
}
const pane = createPane(1)
const { writes } = captureCallbackTerminalWrites(pane)
const deps = createDeps({
restoredLeafId: LEAF_1,
restoredPtyIdByLeafId: { [LEAF_1]: sshPtyId }
})
connectPanePty(pane as never, createManager(1) as never, deps as never)
await flushAsyncTicks(20)
expect(window.api.pty.getMainBufferSnapshot).toHaveBeenCalledWith(sshPtyId, {
scrollbackRows: 5000
})
expect(writes).not.toContain('relay-fallback-output')
await new Promise((resolve) => setTimeout(resolve, SSH_REATTACH_MODEL_SNAPSHOT_TIMEOUT_MS + 25))
await flushAsyncTicks(20)
expect(writes).toContain('relay-fallback-output')
// Why: a stalled reveal must cost exactly one bounded probe — a re-probe
// would buy a second timeout window before the relay paint.
expect(window.api.pty.getMainBufferSnapshot).toHaveBeenCalledTimes(1)
})
// Why: the model probe exists to beat the relay's 100KiB tail on a park-reveal.
// An ordinary reattach (network reconnect, wake, reload) already holds that
// replay, so probing would only delay its paint by the timeout.
it('paints the relay replay without probing main when the reattach did not follow a park', async () => {
const { connectPanePty } = await import('./pty-connection')
const sshPtyId = toAppSshPtyId('conn-1', 'relay-pty-1')
const transport = createMockTransport(sshPtyId)
transport.connect.mockImplementation(async () => {
transport.getPtyId.mockReturnValue(sshPtyId)
return { id: sshPtyId, isReattach: true, replay: 'relay-reconnect-output' }
})
transportFactoryQueue.push(transport)
vi.mocked(window.api.pty.getMainBufferSnapshot).mockReturnValue(new Promise(() => {}))
mockStoreState = {
...mockStoreState,
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
repos: [{ id: 'repo1', connectionId: 'conn-1' }],
deferredSshReconnectTargets: ['conn-1'],
deferredSshSessionIdsByTabId: { 'tab-1': sshPtyId }
}
const pane = createPane(1)
const { writes } = captureCallbackTerminalWrites(pane)
const deps = createDeps({
restoredLeafId: LEAF_1,
restoredPtyIdByLeafId: { [LEAF_1]: sshPtyId }
})
connectPanePty(pane as never, createManager(1) as never, deps as never)
await flushAsyncTicks(20)
expect(window.api.pty.getMainBufferSnapshot).not.toHaveBeenCalled()
expect(writes).toContain('relay-reconnect-output')
})
it('does not auto-reconnect after a user cancels deferred SSH passphrase auth', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
@@ -243,6 +243,24 @@ import {
scheduleHiddenOutputRestore
} from './hidden-output-restore-scheduler'
import { resolveHiddenRestoreScrollbackRows } from './terminal-hidden-restore-scrollback'
import {
buildMainModelSnapshotReplayWrites,
hasPositiveTerminalDimensions,
resolvePositiveTerminalDimensions
} from './terminal-snapshot-replay-paint'
import {
decideSshReattachPaintSource,
memoizeSshReattachModelSnapshotProbe,
resolveSshReattachModelSnapshotWithTimeout,
shouldFetchSshReattachModelSnapshot
} from './ssh-reattach-model-restore'
import { readInFlightCommandCodeTurn } from './parked-terminal-command-status'
import {
cancelCommandCodeDoneSettle,
openCommandCodeDoneSettle,
setCommandCodeDoneSettleExecutor
} from './command-code-done-settle'
import { isTerminalTabParked } from './terminal-parked-watcher-registry'
import {
getExecutionHostIdForWorktree,
getSettingsForWorktreeRuntimeOwner
@@ -303,7 +321,6 @@ const SSH_SESSION_EXPIRED_ERROR = 'SSH_SESSION_EXPIRED'
const DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS = 31_000
const REMOTE_PTY_ID_PREFIX = 'remote:'
const PTY_CONNECT_DIAG_LIMIT = 200
const COMMAND_CODE_OUTPUT_DONE_SETTLE_MS = 1500
const SSH_SHELL_READY_STARTUP_FALLBACK_MS = 1500
const MANUAL_AGENT_COMMAND_MAX_CHARS = 4096
const STARTUP_DRAFT_PASTE_QUIET_MS = 1500
@@ -1014,6 +1031,10 @@ export function connectPanePty(
// settles after remount must not remount its already-replaced successor.
const terminalRecoveryGeneration = captureTerminalPaneRecoveryGeneration(deps.tabId)
const terminalRecoveryInstance = registerTerminalPaneRecoveryInstance(deps.tabId)
// Why sampled here: the host disposes this tab's park watcher in the effect
// that follows this mount, so connect time is the only moment a pane can tell
// a reveal remount from an in-place reattach.
let mountFollowsTerminalPark = isTerminalTabParked(deps.tabId)
exposeE2eTerminalPtyOutputDebug()
let disposed = false
const structuralReplayCoordinator = createTerminalStructuralReplayCoordinator(pane.terminal)
@@ -2762,31 +2783,19 @@ export function connectPanePty(
)
}
let commandCodeOutputDoneTimer: ReturnType<typeof setTimeout> | null = null
const clearCommandCodeOutputDoneTimer = (): void => {
if (commandCodeOutputDoneTimer !== null) {
clearTimeout(commandCodeOutputDoneTimer)
commandCodeOutputDoneTimer = null
}
}
const scheduleCommandCodeOutputDoneStatus = (prompt: string): void => {
clearCommandCodeOutputDoneTimer()
const normalizedPrompt = prompt.trim()
if (!normalizedPrompt) {
return
}
// Why: Command Code keeps rendering the composer while tools run. Only
// complete the row if no active status repaint arrives during this window.
commandCodeOutputDoneTimer = setTimeout(() => {
commandCodeOutputDoneTimer = null
if (disposed) {
return
}
const currentState = useAppStore.getState()
// Why the settle window lives outside this binding: park unmounts the pane
// mid-settle, so a pane-owned timer would be cancelled with nothing left to
// complete the turn — the row would stick at 'working'. Only the row write
// (routing + title slot) is pane-local; the deadline transfers to whichever
// owner (parked watcher or remounted pane) holds the pane next.
const releaseCommandCodeDoneSettleExecutor = setCommandCodeDoneSettleExecutor(
cacheKey,
(normalizedPrompt) => {
const routing = resolveCurrentAgentStatusRouting()
if (!routing) {
return
}
const currentState = useAppStore.getState()
const currentEntry = currentState.agentStatusByPaneKey[cacheKey]
if (currentEntry?.agentType !== 'command-code' || currentEntry.state !== 'working') {
return
@@ -2807,7 +2816,18 @@ export function connectPanePty(
undefined,
routing
)
}, COMMAND_CODE_OUTPUT_DONE_SETTLE_MS)
}
)
const clearCommandCodeOutputDoneTimer = (): void => cancelCommandCodeDoneSettle(cacheKey)
const scheduleCommandCodeOutputDoneStatus = (prompt: string): void => {
const normalizedPrompt = prompt.trim()
if (!normalizedPrompt) {
cancelCommandCodeDoneSettle(cacheKey)
return
}
// Why: Command Code keeps rendering the composer while tools run. Only
// complete the row if no active status repaint arrives during this window.
openCommandCodeDoneSettle(cacheKey, normalizedPrompt)
}
const observeTerminalGitHubPRLink = createTerminalGitHubPRLinkDetector()
@@ -3517,6 +3537,10 @@ export function connectPanePty(
? null
: createCommandCodeOutputStatusDetector({
startupCommand: paneStartup?.command,
// Why the seed: a reveal remount recreates this detector long past the banner
// (and with no startup command); a turn parked mid-flight must still arm the
// scrape so its return to the idle composer completes the row.
inFlightTurn: readInFlightCommandCodeTurn(cacheKey),
onWorking: seedCommandCodeOutputWorkingStatus,
onDone: scheduleCommandCodeOutputDoneStatus
})
@@ -6845,11 +6869,7 @@ export function connectPanePty(
hiddenOutputSnapshotScrollRestore = scrollRestore
const colsBeforeReplay = pane.terminal.cols
const rowsBeforeReplay = pane.terminal.rows
const hasSnapshotDimensions =
Number.isFinite(snapshot.cols) &&
Number.isFinite(snapshot.rows) &&
snapshot.cols > 0 &&
snapshot.rows > 0
const hasSnapshotDimensions = hasPositiveTerminalDimensions(snapshot.cols, snapshot.rows)
try {
await structuralReplayCoordinator.run(
async () => {
@@ -6883,19 +6903,12 @@ export function connectPanePty(
suppressStructuralReplayPtyResize = false
}
}
if (!snapshot.alternateScreen) {
// Why: \x1b[3J wipes xterm scrollback; alt-screen TUIs keep it in xterm, so clear only the normal buffer (mirrors pty-transport.ts).
writeReplayData('\x1b[2J\x1b[3J\x1b[H')
} else if (snapshot.scrollbackAnsi !== undefined) {
// Why: SerializeAddon captures normal + alt buffers together; rebuild normal while active, then return to a clean alt frame.
writeReplayData('\x1b[?1049l\x1b[2J\x1b[3J\x1b[H')
writeReplayData(snapshot.scrollbackAnsi)
writeReplayData('\x1b[0m\x1b[?1049h\x1b[2J\x1b[H')
} else {
// Why: the snapshot's ?1049h no-ops when already on alt screen and skips blank cells; clear the alt buffer so the pre-hide frame can't bleed through blank cells (spares normal-buffer scrollback).
writeReplayData('\x1b[0m\x1b[?1049h\x1b[2J\x1b[H')
// Why shared: the SSH reattach model paint inlines the same
// choreography (coordinator nesting would deadlock there); one
// builder keeps the alt-screen branches from drifting.
for (const replayChunk of buildMainModelSnapshotReplayWrites(snapshot)) {
writeReplayData(replayChunk)
}
writeReplayData(snapshot.data)
// Why: live agents own ?25l/?1004h; a forced ?1004l here would silence focus events until restart (agents enable focus reporting only at startup).
writeReplayData(
hasLiveAgentReattachStatusOrTitleSignal()
@@ -7613,7 +7626,55 @@ export function connectPanePty(
// Why: mobile streaming needs xterm's exact screen state; install the serializer + lastTitle source for main-process hydration parity.
registerPaneSerializerFor(ptyId)
let reattachPayloadApplied = !hasStructuralReplay
// Why (C1 SSH parking): main's headless model holds ~5k rows for SSH ptys
// while the relay replay is a 100KiB raw-byte tail; prefer the model on
// reveal. Only a non-empty 'headless'-sourced snapshot qualifies — the
// renderer-serializer fallback has no mounted xterm after a park. The
// paint happens inline in the snapshot-branch style: applyMainBufferSnapshot
// would nest structuralReplayCoordinator.run inside the reattach task and
// deadlock on the coordinator's tail chain.
// Memoized: the prefetch and the payload task share one probe result, so a
// null prefetch can never buy a second timeout before the relay paint.
const fetchSshMainModelReattachSnapshot = memoizeSshReattachModelSnapshotProbe(
async (): Promise<PtyBufferSnapshot | null> => {
const sshParkingEnabled =
useAppStore.getState().settings?.terminalSshViewParking !== false
if (!shouldFetchSshReattachModelSnapshot({ ptyId, sshParkingEnabled })) {
return null
}
const snapshot = await resolveSshReattachModelSnapshotWithTimeout(
window.api.pty.getMainBufferSnapshot(ptyId, {
scrollbackRows: resolveHiddenRestoreScrollbackRows(pane.terminal.options.scrollback)
})
)
if (
!snapshot ||
decideSshReattachPaintSource({ ptyId, sshParkingEnabled, snapshot }) !==
'main-model-snapshot'
) {
return null
}
return snapshot
}
)
// Why consume-once: only the first reattach of a reveal remount may pay
// the probe; a later in-place reconnect on this same mount must not buy a
// second timeout before the relay paint.
const revealFollowsTerminalPark =
mountFollowsTerminalPark && connectResult?.isReattach === true
mountFollowsTerminalPark = false
// Why: a relay restart empties the replay buffer, but main's model may
// still hold the session — a park-reveal probes it even with no replay
// so the reveal is never blank when main has content. Prefetched (before
// the payload task) so the coordinator route covers the paint.
let prefetchedSshModelSnapshot: PtyBufferSnapshot | null = null
if (revealFollowsTerminalPark && !hasStructuralReplay) {
prefetchedSshModelSnapshot = await fetchSshMainModelReattachSnapshot()
if (!isCurrentReattachPayload()) {
return false
}
}
let reattachPayloadApplied = !hasStructuralReplay && prefetchedSshModelSnapshot === null
const applyReattachPayload = async (): Promise<void> => {
if (!isCurrentReattachPayload()) {
return
@@ -7621,22 +7682,18 @@ export function connectPanePty(
if (connectResult?.snapshot) {
rememberReattachPayloadAgentSignal(connectResult.snapshot, { fullScreenReplay: true })
// Why: replay at the snapshot's own dimensions to avoid rewrapping soft-wrapped rows at a different column count (#7279); suppress the PTY forward so this layout-only resize doesn't SIGWINCH the remote TUI.
const snapshotCols = connectResult.snapshotCols
const snapshotRows = connectResult.snapshotRows
const hasSnapshotDimensions =
typeof snapshotCols === 'number' &&
typeof snapshotRows === 'number' &&
Number.isFinite(snapshotCols) &&
Number.isFinite(snapshotRows) &&
snapshotCols > 0 &&
snapshotRows > 0
const snapshotDimensions = resolvePositiveTerminalDimensions(
connectResult.snapshotCols,
connectResult.snapshotRows
)
if (
hasSnapshotDimensions &&
(pane.terminal.cols !== snapshotCols || pane.terminal.rows !== snapshotRows)
snapshotDimensions &&
(pane.terminal.cols !== snapshotDimensions.cols ||
pane.terminal.rows !== snapshotDimensions.rows)
) {
suppressStructuralReplayPtyResize = true
try {
pane.terminal.resize(snapshotCols, snapshotRows)
pane.terminal.resize(snapshotDimensions.cols, snapshotDimensions.rows)
} finally {
suppressStructuralReplayPtyResize = false
}
@@ -7658,19 +7715,72 @@ export function connectPanePty(
window.api.pty.ackColdRestore(ptyId)
}
}
} else if (connectResult?.replay) {
rememberReattachPayloadAgentSignal(connectResult.replay, { fullScreenReplay: true })
// Relay replay may overlap xterm's pre-disconnect content; clear first to avoid duplication.
writeReplayData('\x1b[2J\x1b[3J\x1b[H')
// Why: raw relay replay may contain the app's own kitty pushes; re-arm with set semantics so redelivery can't grow the stack.
kittyKeyboardModes.scanReplay(connectResult.replay)
writeReplayData(connectResult.replay)
writeReplayData(reattachReplayResetSequence(connectResult.replay))
sendFocusedReattachFocusInAfterReplay(ptyId, attemptGeneration)
if (connectResult.coldRestore) {
if (!isRemoteRuntimePtyId(ptyId)) {
} else if (connectResult?.replay || prefetchedSshModelSnapshot) {
// Why scoped to a park-reveal: the 100KiB relay tail loses scrollback the
// model still holds, but an in-place reattach (network reconnect, wake,
// reload) already has that replay in hand, so probing would only delay its
// paint by the timeout. Memoized, so this is never a second probe.
const modelSnapshot = revealFollowsTerminalPark
? (prefetchedSshModelSnapshot ?? (await fetchSshMainModelReattachSnapshot()))
: null
if (!isCurrentReattachPayload()) {
return
}
if (modelSnapshot) {
// Why composed for scan/reset only: kitty + reset heuristics need
// the full byte stream; the actual writes go through the shared
// alt-screen choreography below (scrollbackAnsi is '' for
// normal-buffer snapshots, so composition matches data there).
const modelData = `${modelSnapshot.scrollbackAnsi ?? ''}${modelSnapshot.data}`
rememberReattachPayloadAgentSignal(modelData, { fullScreenReplay: true })
const modelCols = modelSnapshot.cols
const modelRows = modelSnapshot.rows
if (
hasPositiveTerminalDimensions(modelCols, modelRows) &&
(pane.terminal.cols !== modelCols || pane.terminal.rows !== modelRows)
) {
// Why: replay at the snapshot's own dimensions (see the daemon-snapshot branch, #7279).
suppressStructuralReplayPtyResize = true
try {
pane.terminal.resize(modelCols, modelRows)
} finally {
suppressStructuralReplayPtyResize = false
}
}
kittyKeyboardModes.scanReplay(modelData)
// Why shared: park+reveal of an alt-screen TUI needs the same
// ?1049l/?1049h rebuild as applyMainBufferSnapshot (main strips
// the ?1049h marker when splitting scrollbackAnsi) — inlined here
// because nesting structuralReplayCoordinator would deadlock.
for (const replayChunk of buildMainModelSnapshotReplayWrites(modelSnapshot)) {
writeReplayData(replayChunk)
}
writeReplayData(reattachReplayResetSequence(modelData))
if (modelSnapshot.pendingEscapeTailAnsi) {
// Why last: re-arm the dangling mid-escape after the reset so the live continuation completes it (#7329).
writeReplayData(modelSnapshot.pendingEscapeTailAnsi)
}
// Why: main sampled its delivery backlog with the snapshot; the baseline drops/slices deferred and live chunks the snapshot already covers.
setRestoredSnapshotBaseline(ptyId, modelSnapshot)
recordRendererOrderedSeq(modelSnapshot)
sendFocusedReattachFocusInAfterReplay(ptyId, attemptGeneration)
if (connectResult?.coldRestore && !isRemoteRuntimePtyId(ptyId)) {
window.api.pty.ackColdRestore(ptyId)
}
} else if (connectResult?.replay) {
rememberReattachPayloadAgentSignal(connectResult.replay, { fullScreenReplay: true })
// Relay replay may overlap xterm's pre-disconnect content; clear first to avoid duplication.
writeReplayData('\x1b[2J\x1b[3J\x1b[H')
// Why: raw relay replay may contain the app's own kitty pushes; re-arm with set semantics so redelivery can't grow the stack.
kittyKeyboardModes.scanReplay(connectResult.replay)
writeReplayData(connectResult.replay)
writeReplayData(reattachReplayResetSequence(connectResult.replay))
sendFocusedReattachFocusInAfterReplay(ptyId, attemptGeneration)
if (connectResult.coldRestore) {
if (!isRemoteRuntimePtyId(ptyId)) {
window.api.pty.ackColdRestore(ptyId)
}
}
}
} else if (connectResult?.coldRestore) {
let destinationRows = pane.terminal.rows
@@ -7692,23 +7802,19 @@ export function connectPanePty(
if (!isCurrentReattachPayload()) {
return
}
const coldRestoreCols = connectResult.coldRestore.cols
const coldRestoreRows = connectResult.coldRestore.rows
const hasColdRestoreDimensions =
typeof coldRestoreCols === 'number' &&
typeof coldRestoreRows === 'number' &&
Number.isFinite(coldRestoreCols) &&
Number.isFinite(coldRestoreRows) &&
coldRestoreCols > 0 &&
coldRestoreRows > 0
const coldRestoreDimensions = resolvePositiveTerminalDimensions(
connectResult.coldRestore.cols,
connectResult.coldRestore.rows
)
if (
hasColdRestoreDimensions &&
(pane.terminal.cols !== coldRestoreCols || pane.terminal.rows !== coldRestoreRows)
coldRestoreDimensions &&
(pane.terminal.cols !== coldRestoreDimensions.cols ||
pane.terminal.rows !== coldRestoreDimensions.rows)
) {
// Why: recovered ANSI cursor positions belong to the checkpoint's grid; keep this layout-only resize from reaching the fresh PTY.
suppressStructuralReplayPtyResize = true
try {
pane.terminal.resize(coldRestoreCols, coldRestoreRows)
pane.terminal.resize(coldRestoreDimensions.cols, coldRestoreDimensions.rows)
} finally {
suppressStructuralReplayPtyResize = false
}
@@ -7741,7 +7847,7 @@ export function connectPanePty(
schedulePendingStartupCommandDelivery()
}
}
if (hasStructuralReplay) {
if (hasStructuralReplay || prefetchedSshModelSnapshot) {
await waitForTerminalReplayWritesParsed(pane.terminal)
if (!isCurrentReattachPayload()) {
return
@@ -7795,7 +7901,7 @@ export function connectPanePty(
window.api.pty.signal(reattachPtyId, 'SIGWINCH')
}
}
if (hasStructuralReplay) {
if (hasStructuralReplay || prefetchedSshModelSnapshot) {
await structuralReplayCoordinator.run(applyReattachPayload, {
shouldRestore: isCurrentReattachPayload,
afterRestore: fitAfterReattachRestore
@@ -8614,7 +8720,9 @@ export function connectPanePty(
pendingTerminalInputWrite = null
interruptInference.dispose()
clearTitleOnlyInterruptTimer()
clearCommandCodeOutputDoneTimer()
// Why release, not cancel: the pending settle belongs to the turn, not to
// this pane — a park mid-settle hands it to the parked watcher instead.
releaseCommandCodeDoneSettleExecutor()
if (shiftEnterReconfirmTimer !== null) {
clearTimeout(shiftEnterReconfirmTimer)
shiftEnterReconfirmTimer = null
@@ -892,6 +892,104 @@ describe('createIpcPtyTransport', () => {
}
})
it('bounds the deferred side-effect queue under a stalled drain, keeping the newest title and a pending bell', async () => {
vi.useFakeTimers()
try {
const { createPtyOutputProcessor, MAX_PENDING_PTY_SIDE_EFFECTS } =
await import('./pty-transport')
const onTitleChange = vi.fn()
const onBell = vi.fn()
const processor = createPtyOutputProcessor({ onTitleChange, onBell })
const callbacks = { onData: vi.fn() }
const total = MAX_PENDING_PTY_SIDE_EFFECTS * 4
// Why: the bell is queued first so the cap must evict it — the latch has to survive onto a newer entry.
processor.processData('\x07', callbacks)
for (let i = 0; i < total / 2; i++) {
processor.processData(`\x1b]0;cap-title-${i}\x07`, callbacks)
}
// Why: a paused drain (background shutdown window) must not disable the bound either.
processor.pausePendingSideEffects()
for (let i = total / 2; i < total; i++) {
processor.processData(`\x1b]0;cap-title-${i}\x07`, callbacks)
}
expect(onTitleChange).not.toHaveBeenCalled()
processor.flushPendingSideEffects()
// Why: exactly the cap survives — every older title was evicted, never applied.
expect(onTitleChange).toHaveBeenCalledTimes(MAX_PENDING_PTY_SIDE_EFFECTS)
expect(onTitleChange).toHaveBeenLastCalledWith(
`cap-title-${total - 1}`,
`cap-title-${total - 1}`
)
expect(onBell).toHaveBeenCalledTimes(1)
} finally {
vi.useRealTimers()
}
})
it('collapses evicted agent-status payloads onto the survivor, keeping the newest', async () => {
vi.useFakeTimers()
try {
const {
createPtyOutputProcessor,
MAX_PENDING_PTY_SIDE_EFFECTS,
MAX_EVICTED_AGENT_STATUS_PAYLOAD_CARRY
} = await import('./pty-transport')
const onAgentStatus = vi.fn()
const processor = createPtyOutputProcessor({ onAgentStatus })
const callbacks = { onData: vi.fn() }
const total = MAX_PENDING_PTY_SIDE_EFFECTS * 2
for (let i = 0; i < total; i++) {
processor.processData(
`\x1b]9999;{"state":"working","prompt":"cap-status-${i}"}\x07`,
callbacks
)
}
processor.flushPendingSideEffects()
const delivered = onAgentStatus.mock.calls.map(([payload]) => payload.prompt)
expect(delivered.length).toBeLessThanOrEqual(
MAX_PENDING_PTY_SIDE_EFFECTS + MAX_EVICTED_AGENT_STATUS_PAYLOAD_CARRY
)
expect(delivered.at(-1)).toBe(`cap-status-${total - 1}`)
// Why: eviction collapse must preserve chronological delivery order.
expect(delivered).toEqual(
[...delivered].sort((a, b) => Number(a.slice(11)) - Number(b.slice(11)))
)
} finally {
vi.useRealTimers()
}
})
it('delivers every side effect in order when the queue stays below the cap', async () => {
vi.useFakeTimers()
try {
const { createPtyOutputProcessor } = await import('./pty-transport')
const onTitleChange = vi.fn()
const onBell = vi.fn()
const onAgentStatus = vi.fn()
const processor = createPtyOutputProcessor({ onTitleChange, onBell, onAgentStatus })
const callbacks = { onData: vi.fn() }
processor.processData('\x07', callbacks)
for (let i = 0; i < 100; i++) {
processor.processData(`\x1b]0;under-cap-${i}\x07`, callbacks)
}
processor.processData('\x1b]9999;{"state":"done","prompt":"done"}\x07', callbacks)
await vi.runAllTimersAsync()
expect(onBell).toHaveBeenCalledTimes(1)
expect(onTitleChange).toHaveBeenCalledTimes(100)
expect(onTitleChange).toHaveBeenLastCalledWith('under-cap-99', 'under-cap-99')
expect(onAgentStatus).toHaveBeenCalledWith({ state: 'done', prompt: 'done' })
} finally {
vi.useRealTimers()
}
})
it('still runs stale-title detection when an OSC status chunk has no title', async () => {
vi.useFakeTimers()
try {
@@ -69,6 +69,13 @@ const SSH_SESSION_EXPIRED_ERROR = 'SSH_SESSION_EXPIRED'
const SSH_PTY_CONNECTION_MISMATCH_MARKER = 'belongs to SSH connection'
const STALE_TITLE_TIMEOUT = 3000 // ms before stale working title is cleared
const MAX_PTY_SIDE_EFFECTS_PER_DRAIN = 64
// Why: background timer throttling clamps the drain to ~64 effects/s while an agent CLI can queue
// hundreds/s, so an overnight minimized window otherwise grows this queue without bound (C1/H2).
// 512 ≈ 8 drain ticks of catch-up latency once visible; entries are compact facts (≤1 title/payload).
export const MAX_PENDING_PTY_SIDE_EFFECTS = 512
// Why: agent status is last-wins store state, but payloads can carry KB-scale prompt/tool strings;
// carry only the newest few through eviction so a status flood cannot re-grow what it evicted.
export const MAX_EVICTED_AGENT_STATUS_PAYLOAD_CARRY = 16
type PtyOutputCallbacks = Parameters<PtyTransport['connect']>[0]['callbacks']
@@ -207,6 +214,38 @@ export function createPtyOutputProcessor({
sideEffectDrainTimer = setTimeout(drainPtySideEffects, 0)
}
// Why: oldest-first eviction at the cap. Evicted titles are safe to drop (titles are last-wins);
// bells and agent-status payloads collapse onto the next-oldest survivor so a pending bell latch
// and the newest statuses still apply on drain instead of vanishing.
function evictOldestPendingSideEffectsIfFull(): void {
while (pendingSideEffects.length - pendingSideEffectIndex >= MAX_PENDING_PTY_SIDE_EFFECTS) {
const evicted = pendingSideEffects[pendingSideEffectIndex]
if (!evicted) {
return
}
pendingSideEffectIndex += 1
// Why: mirror applyPtySideEffect's accounting so stale-probe arming doesn't stick past eviction.
pendingWorkingTitleSideEffects -= countWorkingTitles(evicted.titles)
if (pendingWorkingTitleSideEffects < 0) {
pendingWorkingTitleSideEffects = 0
}
const survivor = pendingSideEffects[pendingSideEffectIndex]
if (survivor) {
if (evicted.containsBell) {
survivor.containsBell = true
}
if (evicted.payloads.length > 0) {
const merged = evicted.payloads.concat(survivor.payloads)
survivor.payloads =
merged.length > MAX_EVICTED_AGENT_STATUS_PAYLOAD_CARRY
? merged.slice(-MAX_EVICTED_AGENT_STATUS_PAYLOAD_CARRY)
: merged
}
}
compactPendingSideEffectsIfNeeded()
}
}
function enqueuePtySideEffect(next: PendingPtySideEffect): void {
const workingTitleCount = countWorkingTitles(next.titles)
const prior = pendingSideEffects.at(-1)
@@ -225,6 +264,7 @@ export function createPtyOutputProcessor({
pendingWorkingTitleSideEffects += workingTitleCount
return
}
evictOldestPendingSideEffectsIfFull()
pendingSideEffects.push(next)
pendingWorkingTitleSideEffects += workingTitleCount
}
@@ -0,0 +1,63 @@
import { describe, expect, it } from 'vitest'
import type { RepoConnection } from '../../../../shared/workspace-session-terminal-buffers'
import { canReleaseReplayedScrollbackFromStore } from './replayed-scrollback-store-release'
const LOCAL_REPO: RepoConnection = {
id: 'local-repo',
connectionId: null,
executionHostId: 'local'
}
const SSH_REPO: RepoConnection = {
id: 'ssh-repo',
connectionId: 'conn-1',
executionHostId: null
}
const RUNTIME_REPO: RepoConnection = {
id: 'runtime-repo',
connectionId: null,
executionHostId: 'runtime:env-1'
}
const REPOS = [LOCAL_REPO, SSH_REPO, RUNTIME_REPO]
describe('canReleaseReplayedScrollbackFromStore', () => {
it("releases ref-backed and remote-repo replays but keeps a local worktree's only copy", () => {
expect(
canReleaseReplayedScrollbackFromStore({
hasScrollbackRefs: true,
worktreeId: 'local-repo::/local/worktree',
repos: REPOS
})
).toBe(true)
expect(
canReleaseReplayedScrollbackFromStore({
hasScrollbackRefs: false,
worktreeId: 'ssh-repo::/ssh/worktree',
repos: REPOS
})
).toBe(true)
expect(
canReleaseReplayedScrollbackFromStore({
hasScrollbackRefs: false,
worktreeId: 'runtime-repo::/runtime/worktree',
repos: REPOS
})
).toBe(true)
expect(
canReleaseReplayedScrollbackFromStore({
hasScrollbackRefs: false,
worktreeId: 'local-repo::/local/worktree',
repos: REPOS
})
).toBe(false)
})
it('releases for an unhydrated repo catalog, matching the capture guard that re-mints it', () => {
expect(
canReleaseReplayedScrollbackFromStore({
hasScrollbackRefs: false,
worktreeId: 'unknown-repo::/maybe-remote/worktree',
repos: REPOS
})
).toBe(true)
})
})
@@ -0,0 +1,22 @@
import {
shouldPreserveTerminalScrollbackBuffers,
type RepoConnection
} from '../../../../shared/workspace-session-terminal-buffers'
type ReplayedScrollbackReleaseArgs = {
hasScrollbackRefs: boolean
worktreeId: string | undefined
repos: readonly RepoConnection[]
}
/** Whether a replayed pane may drop its store-held scrollback copy now that xterm owns the bytes.
* Inverse of the force-park capture guard: keep the copy only where nothing can re-create it. */
export function canReleaseReplayedScrollbackFromStore({
hasScrollbackRefs,
worktreeId,
repos
}: ReplayedScrollbackReleaseArgs): boolean {
// Refs re-hydrate from disk and remote/SSH worktrees re-serialize at the next park; a local
// worktree never re-mints its copy (includeLocalBuffers:false), so releasing it would lose it.
return hasScrollbackRefs || shouldPreserveTerminalScrollbackBuffers(worktreeId, repos)
}
@@ -0,0 +1,39 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
captureTerminalShutdownBuffersBestEffort,
shutdownBufferCaptures
} from './shutdown-buffer-captures'
afterEach(() => {
shutdownBufferCaptures.clear()
})
describe('captureTerminalShutdownBuffersBestEffort', () => {
it('continues after one tab capture throws', () => {
const failed = vi.fn(() => {
throw new Error('layout capture failed')
})
const succeeded = vi.fn()
shutdownBufferCaptures.set('tab-failed', failed)
shutdownBufferCaptures.set('tab-succeeded', succeeded)
expect(() =>
captureTerminalShutdownBuffersBestEffort(['tab-failed', 'tab-succeeded'], {
includeLocalBuffers: false
})
).not.toThrow()
expect(failed).toHaveBeenCalledWith({ includeLocalBuffers: false })
expect(succeeded).toHaveBeenCalledWith({ includeLocalBuffers: false })
})
it('reports incomplete coverage when a tab throws or has no registered capture', () => {
shutdownBufferCaptures.set('registered', vi.fn())
shutdownBufferCaptures.set('throwing', () => {
throw new Error('layout capture failed')
})
expect(
captureTerminalShutdownBuffersBestEffort(['registered', 'throwing', 'unregistered'])
).toEqual({ requested: 3, captured: 1 })
})
})
@@ -20,3 +20,25 @@ export const shutdownBufferCaptures = new Map<
string,
(options?: ShutdownBufferCaptureOptions) => void
>()
/** Capture every mounted tab without letting one layout failure abort retention.
* Reports coverage so a caller can decide whether the episode is retryable. */
export function captureTerminalShutdownBuffersBestEffort(
tabIds: readonly string[],
options?: ShutdownBufferCaptureOptions
): { requested: number; captured: number } {
let captured = 0
for (const tabId of tabIds) {
const capture = shutdownBufferCaptures.get(tabId)
if (!capture) {
continue
}
try {
capture(options)
captured += 1
} catch {
// Buffer capture is optional recovery evidence; parking must still commit.
}
}
return { requested: tabIds.length, captured }
}
@@ -0,0 +1,157 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { toAppSshPtyId } from '../../../../shared/ssh-pty-id'
import {
decideSshReattachPaintSource,
memoizeSshReattachModelSnapshotProbe,
resolveSshReattachModelSnapshotWithTimeout,
shouldFetchSshReattachModelSnapshot
} from './ssh-reattach-model-restore'
// Why built, not literal: a hardcoded id would silently stop parsing as SSH if the
// prefix/separator changed, turning these positive cases into fallback expectations.
const SSH_PTY_ID = toAppSshPtyId('conn-1', 'relay-pty-1')
const LOCAL_PTY_ID = 'repo::/worktree@@session-1'
afterEach(() => {
vi.useRealTimers()
})
describe('resolveSshReattachModelSnapshotWithTimeout', () => {
it('degrades a stalled snapshot probe to null', async () => {
vi.useFakeTimers()
const pending = new Promise<string>(() => {})
const resolved = resolveSshReattachModelSnapshotWithTimeout(pending, 25)
await vi.advanceTimersByTimeAsync(25)
await expect(resolved).resolves.toBeNull()
})
it('passes through a prompt snapshot and degrades rejection to null', async () => {
await expect(
resolveSshReattachModelSnapshotWithTimeout(Promise.resolve('snapshot'), 25)
).resolves.toBe('snapshot')
await expect(
resolveSshReattachModelSnapshotWithTimeout(Promise.reject(new Error('unavailable')), 25)
).resolves.toBeNull()
})
})
describe('shouldFetchSshReattachModelSnapshot', () => {
it('fetches only for SSH ptys with SSH parking enabled', () => {
expect(
shouldFetchSshReattachModelSnapshot({ ptyId: SSH_PTY_ID, sshParkingEnabled: true })
).toBe(true)
expect(
shouldFetchSshReattachModelSnapshot({ ptyId: SSH_PTY_ID, sshParkingEnabled: false })
).toBe(false)
expect(
shouldFetchSshReattachModelSnapshot({ ptyId: LOCAL_PTY_ID, sshParkingEnabled: true })
).toBe(false)
})
})
describe('memoizeSshReattachModelSnapshotProbe', () => {
it('remembers a null prefetch so the payload task never probes twice', async () => {
const probe = vi.fn().mockResolvedValue(null)
const fetchSnapshot = memoizeSshReattachModelSnapshotProbe(probe)
await expect(fetchSnapshot()).resolves.toBeNull()
await expect(fetchSnapshot()).resolves.toBeNull()
expect(probe).toHaveBeenCalledTimes(1)
})
it('returns the same resolved snapshot without re-probing', async () => {
const probe = vi.fn().mockResolvedValue({ data: 'screen' })
const fetchSnapshot = memoizeSshReattachModelSnapshotProbe(probe)
const first = await fetchSnapshot()
const second = await fetchSnapshot()
expect(first).toBe(second)
expect(probe).toHaveBeenCalledTimes(1)
})
it('single-flights concurrent callers onto one probe', async () => {
let resolveProbe: (value: string | null) => void = () => {}
const probe = vi.fn(() => new Promise<string | null>((resolve) => (resolveProbe = resolve)))
const fetchSnapshot = memoizeSshReattachModelSnapshotProbe(probe)
const first = fetchSnapshot()
const second = fetchSnapshot()
resolveProbe(null)
await expect(first).resolves.toBeNull()
await expect(second).resolves.toBeNull()
expect(probe).toHaveBeenCalledTimes(1)
})
})
describe('decideSshReattachPaintSource', () => {
const headless = { data: 'screen', source: 'headless' as const }
it('paints from the main model only for a non-empty headless snapshot', () => {
expect(
decideSshReattachPaintSource({
ptyId: SSH_PTY_ID,
sshParkingEnabled: true,
snapshot: headless
})
).toBe('main-model-snapshot')
})
it('degrades to relay replay on null, renderer-sourced, sourceless, or empty snapshots', () => {
for (const snapshot of [
null,
{ data: 'screen', source: 'renderer' as const },
{ data: 'screen' },
{ data: '', source: 'headless' as const },
{ data: '', scrollbackAnsi: '', pendingEscapeTailAnsi: '', source: 'headless' as const }
]) {
expect(
decideSshReattachPaintSource({ ptyId: SSH_PTY_ID, sshParkingEnabled: true, snapshot })
).toBe('relay-replay')
}
})
it('judges emptiness on the composed content, not the screen frame alone', () => {
// Why: an alt-screen model snapshot can hold all content in scrollbackAnsi
// with an empty screen.
expect(
decideSshReattachPaintSource({
ptyId: SSH_PTY_ID,
sshParkingEnabled: true,
snapshot: { data: '', scrollbackAnsi: 'history', source: 'headless' as const }
})
).toBe('main-model-snapshot')
})
it('treats a dangling escape tail alone as unpaintable content', () => {
// Why: an incomplete escape sequence renders nothing, so painting it would
// blank the pane over a relay replay that still holds the session.
expect(
decideSshReattachPaintSource({
ptyId: SSH_PTY_ID,
sshParkingEnabled: true,
snapshot: { data: '', pendingEscapeTailAnsi: '\x1b[', source: 'headless' as const }
})
).toBe('relay-replay')
})
it('never upgrades when the kill switch is off or the pty is not SSH', () => {
expect(
decideSshReattachPaintSource({
ptyId: SSH_PTY_ID,
sshParkingEnabled: false,
snapshot: headless
})
).toBe('relay-replay')
expect(
decideSshReattachPaintSource({
ptyId: LOCAL_PTY_ID,
sshParkingEnabled: true,
snapshot: headless
})
).toBe('relay-replay')
})
})
@@ -0,0 +1,85 @@
import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id'
export type SshReattachPaintSource = 'main-model-snapshot' | 'relay-replay'
export type SshReattachModelSnapshot = {
data: string
source?: 'headless' | 'renderer'
scrollbackAnsi?: string
pendingEscapeTailAnsi?: string
}
// Why: relay replay is already available during reattach; a stalled model
// probe must not strand that fallback or hold live PTY bytes indefinitely.
export const SSH_REATTACH_MODEL_SNAPSHOT_TIMEOUT_MS = 750
export async function resolveSshReattachModelSnapshotWithTimeout<T>(
snapshot: Promise<T>,
timeoutMs = SSH_REATTACH_MODEL_SNAPSHOT_TIMEOUT_MS
): Promise<T | null> {
let timer: ReturnType<typeof setTimeout> | null = null
try {
return await Promise.race([
snapshot.catch(() => null),
new Promise<null>((resolve) => {
timer = setTimeout(() => resolve(null), timeoutMs)
})
])
} finally {
if (timer !== null) {
clearTimeout(timer)
}
}
}
/**
* Which payload paints an SSH reattach (C1 SSH-parking design gate). Only
* main's headless model is trusted: a 'renderer'-sourced snapshot serializes a
* mounted xterm, which no longer exists once the pane parked — anything but a
* non-empty headless snapshot degrades to the relay replay, never a blank paint.
* Emptiness is judged on the composed CONTENT (scrollback + screen): an
* alt-screen snapshot can carry all content in scrollbackAnsi with an empty
* screen frame.
*/
export function decideSshReattachPaintSource(args: {
ptyId: string
sshParkingEnabled: boolean
snapshot: SshReattachModelSnapshot | null
}): SshReattachPaintSource {
if (!args.sshParkingEnabled || parseAppSshPtyId(args.ptyId) === null) {
return 'relay-replay'
}
if (!args.snapshot || args.snapshot.source !== 'headless') {
return 'relay-replay'
}
// Why the escape tail is excluded: a dangling mid-escape is not content — a
// model holding only one paints a blank pane, which this gate forbids.
// Accepted cost: a session that wrote only control-sequence preamble before
// parking always falls back to relay; the gate cannot tell it apart from a
// model that never received content, and relay replays that preamble anyway.
const contentLength = (args.snapshot.scrollbackAnsi?.length ?? 0) + args.snapshot.data.length
return contentLength === 0 ? 'relay-replay' : 'main-model-snapshot'
}
/** Skip the snapshot fetch entirely when the paint could never use it. */
export function shouldFetchSshReattachModelSnapshot(args: {
ptyId: string
sshParkingEnabled: boolean
}): boolean {
return args.sshParkingEnabled && parseAppSshPtyId(args.ptyId) !== null
}
/**
* Single-flight memo for the reattach model probe: at most one
* getMainBufferSnapshot per reattach attempt. A null prefetch is remembered so
* the payload task never buys a second probe timeout — it paints relay instead.
*/
export function memoizeSshReattachModelSnapshotProbe<T>(
probe: () => Promise<T | null>
): () => Promise<T | null> {
let inFlight: Promise<T | null> | null = null
return () => {
inFlight ??= probe()
return inFlight
}
}
@@ -0,0 +1,172 @@
import { describe, expect, it } from 'vitest'
import {
getTerminalTabColdParkRecheckDelayMs,
getTerminalWorktreeColdParkRecheckDelayMs
} from './terminal-cold-park-recheck-deadlines'
describe('getTerminalWorktreeColdParkRecheckDelayMs', () => {
it('returns the next cold-park policy deadline', () => {
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: null,
nowMs: 1_000,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 1_050,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBe(50)
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 1_100,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBe(900)
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 2_000,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
})
it('schedules no recheck when the settings kill switch disables parking', () => {
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: false,
hiddenSinceMs: 1_000,
nowMs: 1_050,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
})
it('wakes at the retention TTL for budget candidates past the ordinary deadlines', () => {
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 2_500,
coldParkDelayMs: 100,
hotRetainMs: 1_000,
retentionTtlMs: 5_000
})
).toBe(3_500)
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 2_500,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
})
// Why: past the ordinary deadlines nothing else would wake the verdict
// effect, and the cool-down is what keeps the candidate out of the parked
// set — without this wakeup a measured worktree never re-parks.
it('wakes at the measure cool-down deadline when all ordinary deadlines have passed', () => {
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 2_500,
coldParkDelayMs: 100,
hotRetainMs: 1_000,
parkCooldownUntilMs: 2_600
})
).toBe(100)
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 2_500,
coldParkDelayMs: 100,
hotRetainMs: 1_000,
parkCooldownUntilMs: 2_500
})
).toBeNull()
})
})
describe('getTerminalTabColdParkRecheckDelayMs', () => {
it('returns the next terminal-tab cold-park policy deadline', () => {
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: null,
nowMs: 1_000,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 1_050,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBe(50)
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 1_100,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBe(900)
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 2_000,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
})
it('schedules no recheck when the settings kill switch disables parking', () => {
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: false,
hiddenSinceMs: 1_000,
nowMs: 1_050,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
})
it('wakes at the measure cool-down deadline when all ordinary deadlines have passed', () => {
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 2_500,
coldParkDelayMs: 100,
hotRetainMs: 1_000,
parkCooldownUntilMs: 2_750
})
).toBe(250)
})
})
@@ -0,0 +1,72 @@
/**
* Why: parking decisions change only at the cold-park, hot-retain, retention
* TTL, and post-measure cool-down deadlines, so the verdict effects schedule
* one recheck at the next deadline instead of polling.
*/
import {
TERMINAL_TAB_COLD_PARK_DELAY_MS,
TERMINAL_TAB_HOT_RETAIN_MS,
TERMINAL_WORKTREE_COLD_PARK_DELAY_MS,
TERMINAL_WORKTREE_HOT_RETAIN_MS
} from './terminal-hidden-view-parking'
function nextColdParkDeadlineDelayMs(args: {
parkingEnabled: boolean
hiddenSinceMs: number | null
nowMs: number
coldParkDelayMs: number
hotRetainMs: number
retentionTtlMs?: number
parkCooldownUntilMs?: number | null
}): number | null {
if (!args.parkingEnabled || args.hiddenSinceMs === null) {
return null
}
const pendingDeadlines = [
args.hiddenSinceMs + args.coldParkDelayMs,
args.hiddenSinceMs + args.hotRetainMs,
...(args.retentionTtlMs !== undefined ? [args.hiddenSinceMs + args.retentionTtlMs] : []),
// Why: the cool-down holds past-deadline candidates out of the parked set; without this wakeup nothing re-parks them.
...(args.parkCooldownUntilMs != null ? [args.parkCooldownUntilMs] : [])
].filter((deadlineMs) => deadlineMs > args.nowMs)
return pendingDeadlines.length === 0 ? null : Math.min(...pendingDeadlines) - args.nowMs
}
export function getTerminalWorktreeColdParkRecheckDelayMs(args: {
parkingEnabled: boolean
hiddenSinceMs: number | null
nowMs: number
coldParkDelayMs?: number
hotRetainMs?: number
/** Provided only for retention-budget candidates so their TTL wakes the verdict effect. */
retentionTtlMs?: number
parkCooldownUntilMs?: number | null
}): number | null {
return nextColdParkDeadlineDelayMs({
parkingEnabled: args.parkingEnabled,
hiddenSinceMs: args.hiddenSinceMs,
nowMs: args.nowMs,
coldParkDelayMs: args.coldParkDelayMs ?? TERMINAL_WORKTREE_COLD_PARK_DELAY_MS,
hotRetainMs: args.hotRetainMs ?? TERMINAL_WORKTREE_HOT_RETAIN_MS,
...(args.retentionTtlMs !== undefined ? { retentionTtlMs: args.retentionTtlMs } : {}),
parkCooldownUntilMs: args.parkCooldownUntilMs
})
}
export function getTerminalTabColdParkRecheckDelayMs(args: {
parkingEnabled: boolean
hiddenSinceMs: number | null
nowMs: number
coldParkDelayMs?: number
hotRetainMs?: number
parkCooldownUntilMs?: number | null
}): number | null {
return nextColdParkDeadlineDelayMs({
parkingEnabled: args.parkingEnabled,
hiddenSinceMs: args.hiddenSinceMs,
nowMs: args.nowMs,
coldParkDelayMs: args.coldParkDelayMs ?? TERMINAL_TAB_COLD_PARK_DELAY_MS,
hotRetainMs: args.hotRetainMs ?? TERMINAL_TAB_HOT_RETAIN_MS,
parkCooldownUntilMs: args.parkCooldownUntilMs
})
}
@@ -0,0 +1,49 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('@/store', () => ({
useAppStore: { getState: () => ({ terminalLayoutsByTabId: {}, runtimePaneTitlesByTabId: {} }) }
}))
import { selectEvictionExemptTerminalTabLayoutKey } from './terminal-eviction-exempt-tabs'
const TAB_ID = 'tab-1'
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
const SECOND_LEAF_ID = '22222222-2222-4222-8222-222222222222'
const PTY_ID = 'repo::/worktree@@session-1'
const TABS = [{ id: TAB_ID, ptyId: PTY_ID }]
function layoutState(ptyIdsByLeafId: Record<string, string>) {
return { terminalLayoutsByTabId: { [TAB_ID]: { ptyIdsByLeafId } } }
}
describe('selectEvictionExemptTerminalTabLayoutKey', () => {
// Why: the exempt memo is keyed on the tabs array, which a split leaves
// untouched — a key blind to layout PTYs would unmount the new live pane.
it('changes when a split adds a leaf pty', () => {
const single = layoutState({ [LEAF_ID]: PTY_ID })
expect(selectEvictionExemptTerminalTabLayoutKey(single, TABS)).toBe(
selectEvictionExemptTerminalTabLayoutKey(single, TABS)
)
expect(
selectEvictionExemptTerminalTabLayoutKey(
layoutState({ [LEAF_ID]: PTY_ID, [SECOND_LEAF_ID]: 'pty-local-detached' }),
TABS
)
).not.toBe(selectEvictionExemptTerminalTabLayoutKey(single, TABS))
})
it('changes when a leaf pty is re-minted under the same layout', () => {
expect(
selectEvictionExemptTerminalTabLayoutKey(
layoutState({ [LEAF_ID]: 'pty-local-detached' }),
TABS
)
).not.toBe(selectEvictionExemptTerminalTabLayoutKey(layoutState({ [LEAF_ID]: PTY_ID }), TABS))
})
it('tolerates tabs with no persisted layout', () => {
expect(selectEvictionExemptTerminalTabLayoutKey({ terminalLayoutsByTabId: {} }, TABS)).toBe(
`${TAB_ID}=`
)
})
})
@@ -0,0 +1,87 @@
/**
* Eviction-exempt parked terminal tabs.
*
* Why: force-park unmounts restorable tabs under the hidden-worktree retention
* budget, but some live local PTYs cannot reattach on remount. Those tabs must
* keep their panes mounted so eviction does not orphan a live shell.
*/
import { useAppStore } from '@/store'
import { isEvictionExemptTerminalPty } from './terminal-hidden-worktree-retention'
import {
resolveParkedTerminalPaneCandidates,
type ParkableTerminalTabModel
} from './terminal-parked-tab-watchers'
/**
* Whether force-park must keep this tab's panes mounted: ANY of its pane PTYs is
* one a remount could not reattach. Resolved from the same pane candidates as
* canWatcherCoverParkedTerminalTab — tab.ptyId is only the first leaf's PTY, so
* a split tab whose SECOND leaf holds the unrestorable PTY fails coverage (and
* so becomes a retention candidate) yet would otherwise look exempt-free and
* unmount, orphaning that live shell. tab.ptyId stays in the union in case pane
* resolution misses it (no layout, no capture).
*
* Accepted residual: detection is per pane but retention is per TAB — the whole
* PaneManager stays mounted, so one exempt leaf also pins its restorable split
* siblings, and the retention budget cannot bound exempt tabs. Capping them is
* not an option (eviction orphans the live shell); the real fix is making those
* pty classes reattachable. Sibling TABS are unaffected — the worktree-level
* veto was removed (selectRetentionForceParkedTerminalWorktrees never consults
* tab exemptions).
*/
export function isEvictionExemptTerminalTab(
tab: ParkableTerminalTabModel,
worktreeId: string
): boolean {
if (isEvictionExemptTerminalPty(tab.ptyId, worktreeId)) {
return true
}
return resolveParkedTerminalPaneCandidates(tab, useAppStore.getState()).some((pane) =>
isEvictionExemptTerminalPty(pane.ptyId, worktreeId)
)
}
/**
* Eviction-exempt tab ids for one worktree's tabs, resolved in a single pass.
*
* Why: each isEvictionExemptTerminalTab call re-reads the store and can walk the
* layout tree, so render and watcher-sync consume a memoized set instead of
* re-asking per tab on every unrelated re-render.
*/
export function selectEvictionExemptTerminalTabIds(
worktreeId: string,
tabs: readonly ParkableTerminalTabModel[]
): ReadonlySet<string> {
const exemptTabIds = new Set<string>()
for (const tab of tabs) {
if (isEvictionExemptTerminalTab(tab, worktreeId)) {
exemptTabIds.add(tab.id)
}
}
return exemptTabIds
}
type EvictionExemptTabLayoutState = {
terminalLayoutsByTabId: Record<string, { ptyIdsByLeafId?: Record<string, string> } | undefined>
}
/**
* Memo key over the store half of an exemption verdict: a split add or a
* re-minted leaf pty changes the layout's pane PTYs without changing the tabs
* array, and a memo keyed on tabs alone would keep serving an exempt set that
* misses the new pane — force-park would unmount it and orphan a live shell.
*/
export function selectEvictionExemptTerminalTabLayoutKey(
state: EvictionExemptTabLayoutState,
tabs: readonly ParkableTerminalTabModel[]
): string {
return tabs
.map((tab) => {
const ptyIdsByLeafId = state.terminalLayoutsByTabId[tab.id]?.ptyIdsByLeafId ?? {}
const leafPtys = Object.entries(ptyIdsByLeafId)
.map(([leafId, ptyId]) => `${leafId}:${ptyId}`)
.join(',')
return `${tab.id}=${leafPtys}`
})
.join('|')
}
@@ -9,8 +9,7 @@ import {
TERMINAL_WORKTREE_PARK_DELAY_MS,
canParkTerminalTabRenderer,
canParkTerminalWorktreeRenderers,
getTerminalTabColdParkRecheckDelayMs,
getTerminalWorktreeColdParkRecheckDelayMs,
isParkRestorableTerminalPty,
isSnapshotBackedTerminalPty,
selectColdParkedTerminalTabs,
selectColdParkedTerminalWorktrees
@@ -22,6 +21,18 @@ describe('isSnapshotBackedTerminalPty', () => {
expect(isSnapshotBackedTerminalPty('wt-1@@session-1', 'wt-1')).toBe(true)
})
// Why: folder workspaces mint worktree-shaped ids; parking must treat them identically (project rule).
it('allows folder-workspace sessions owned by the workspace', () => {
const folderWorkspaceId =
'repo-1::/Users/dev/proj::workspace:6f9619ff-8b86-4d01-b42d-00cf4fc964ff'
expect(isSnapshotBackedTerminalPty(`${folderWorkspaceId}@@session-1`, folderWorkspaceId)).toBe(
true
)
expect(isSnapshotBackedTerminalPty(`${folderWorkspaceId}@@session-1`, 'repo-1::/other')).toBe(
false
)
})
// Why: separator-less ids ('1', '2', 'pty-local-detached') come from the
// daemon-fail-open LocalPtyProvider and have no daemon session model —
// revealing a parked pane would silently respawn a fresh shell, so they
@@ -46,6 +57,32 @@ describe('isSnapshotBackedTerminalPty', () => {
})
})
describe('isParkRestorableTerminalPty', () => {
const worktreeId = 'repo::/worktree'
const sshPolicy = { sshParkingEnabled: true }
it('accepts every snapshot-backed pty regardless of policy', () => {
expect(isParkRestorableTerminalPty(`${worktreeId}@@session-1`, worktreeId)).toBe(true)
expect(isParkRestorableTerminalPty(`${worktreeId}@@session-1`, worktreeId, sshPolicy)).toBe(
true
)
})
it('accepts SSH ptys only when the SSH-parking policy is enabled', () => {
expect(isParkRestorableTerminalPty('ssh:ssh-1@@pty-1', worktreeId, sshPolicy)).toBe(true)
expect(isParkRestorableTerminalPty('ssh:ssh-1@@pty-1', worktreeId)).toBe(false)
expect(
isParkRestorableTerminalPty('ssh:ssh-1@@pty-1', worktreeId, { sshParkingEnabled: false })
).toBe(false)
})
it('rejects remote-runtime, fail-open, foreign, and null ptys under every policy', () => {
for (const ptyId of ['remote:env-1@@terminal-1', 'pty-local-detached', 'other@@s-1', null]) {
expect(isParkRestorableTerminalPty(ptyId, worktreeId, sshPolicy)).toBe(false)
}
})
})
describe('canParkTerminalWorktreeRenderers', () => {
const hiddenSinceMs = 1_000
const nowMs = hiddenSinceMs + TERMINAL_WORKTREE_PARK_DELAY_MS
@@ -65,6 +102,24 @@ describe('canParkTerminalWorktreeRenderers', () => {
expect(canParkTerminalWorktreeRenderers(base)).toBe(true)
})
it('parks a hidden SSH worktree only under the SSH restore policy', () => {
const sshArgs = {
...base,
terminalTabs: [{ id: 'tab-1', ptyId: 'ssh:conn-1@@pty-1' }]
}
expect(canParkTerminalWorktreeRenderers(sshArgs)).toBe(false)
expect(
canParkTerminalWorktreeRenderers({ ...sshArgs, restorePolicy: { sshParkingEnabled: true } })
).toBe(true)
expect(
canParkTerminalWorktreeRenderers({
...sshArgs,
terminalTabs: [...sshArgs.terminalTabs, { id: 'tab-2', ptyId: 'remote:env-1@@t-1' }],
restorePolicy: { sshParkingEnabled: true }
})
).toBe(false)
})
it('keeps a previously mounted v19 terminal eligible for ordinary parking', () => {
const legacyPtyId = 'repo::/worktree@@session-1'
clearTerminalProviderSnapshotCapabilities()
@@ -112,6 +167,17 @@ describe('canParkTerminalWorktreeRenderers', () => {
).toBe(true)
})
// Why: hiddenSince survives a background-measure window, so a past-deadline
// worktree would otherwise re-park the instant the measure lease ends —
// remount/reattach thrash on every ~3s periodic probe.
it('holds an otherwise past-deadline candidate out of park until the measure cool-down ends', () => {
expect(canParkTerminalWorktreeRenderers({ ...base, parkCooldownUntilMs: nowMs + 1 })).toBe(
false
)
expect(canParkTerminalWorktreeRenderers({ ...base, parkCooldownUntilMs: nowMs })).toBe(true)
expect(canParkTerminalWorktreeRenderers({ ...base, parkCooldownUntilMs: null })).toBe(true)
})
it('keeps the renderer mounted when any terminal lacks snapshot-backed restore', () => {
expect(
canParkTerminalWorktreeRenderers({
@@ -179,6 +245,11 @@ describe('canParkTerminalTabRenderer', () => {
canParkTerminalTabRenderer({ ...base, coldParkDelayMs: 100, nowMs: hiddenSinceMs + 100 })
).toBe(true)
})
it('holds an otherwise past-deadline tab out of park until the measure cool-down ends', () => {
expect(canParkTerminalTabRenderer({ ...base, parkCooldownUntilMs: base.nowMs + 1 })).toBe(false)
expect(canParkTerminalTabRenderer({ ...base, parkCooldownUntilMs: base.nowMs })).toBe(true)
})
})
describe('selectColdParkedTerminalWorktrees', () => {
@@ -399,6 +470,29 @@ describe('selectColdParkedTerminalTabs', () => {
expect(selected).toEqual(new Set(['tab-3']))
})
// Why worktree-scoped: measure windows mount every tab of the worktree, so
// one cool-down (not per-tab clocks) delays re-park after the lease ends.
it('selects nothing while the post-measure cool-down is active', () => {
const args = {
worktreeId: 'wt-1',
terminalTabs: [
localTab('tab-1', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS),
localTab('tab-2', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS - 1),
localTab('tab-3', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS - 2)
],
pendingStartupByTabId: {},
parkingEnabled: true,
nowMs,
hotRetainLimit: 2
}
expect(selectColdParkedTerminalTabs({ ...args, parkCooldownUntilMs: nowMs + 1 })).toEqual(
new Set()
)
expect(selectColdParkedTerminalTabs({ ...args, parkCooldownUntilMs: nowMs })).toEqual(
new Set(['tab-3'])
)
})
it('cold-parks aged inactive local tabs even when under the retain limit', () => {
const selected = selectColdParkedTerminalTabs({
worktreeId: 'wt-1',
@@ -495,109 +589,3 @@ describe('selectColdParkedTerminalTabs', () => {
expect(selected).toEqual(new Set())
})
})
describe('getTerminalWorktreeColdParkRecheckDelayMs', () => {
it('returns the next cold-park policy deadline', () => {
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: null,
nowMs: 1_000,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 1_050,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBe(50)
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 1_100,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBe(900)
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 2_000,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
})
it('schedules no recheck when the settings kill switch disables parking', () => {
expect(
getTerminalWorktreeColdParkRecheckDelayMs({
parkingEnabled: false,
hiddenSinceMs: 1_000,
nowMs: 1_050,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
})
})
describe('getTerminalTabColdParkRecheckDelayMs', () => {
it('returns the next terminal-tab cold-park policy deadline', () => {
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: null,
nowMs: 1_000,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 1_050,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBe(50)
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 1_100,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBe(900)
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: true,
hiddenSinceMs: 1_000,
nowMs: 2_000,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
})
it('schedules no recheck when the settings kill switch disables parking', () => {
expect(
getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: false,
hiddenSinceMs: 1_000,
nowMs: 1_050,
coldParkDelayMs: 100,
hotRetainMs: 1_000
})
).toBeNull()
})
})
@@ -24,6 +24,8 @@ export type TerminalColdParkPolicyOverrides = {
coldParkDelayMs?: number
hotRetainMs?: number
hotRetainLimit?: number
retentionTtlMs?: number
retentionLimit?: number
}
export type ColdParkableTerminalTab = Pick<TerminalTab, 'id' | 'ptyId' | 'pendingActivationSpawn'>
@@ -35,6 +37,10 @@ export type TerminalWorktreeColdParkCandidate = {
shouldMeasureHiddenWorktree: boolean
hasActivityTerminalPortal: boolean
hiddenSinceMs: number | null
/** Post-measure cool-down: hiddenSince survives a measure window (TTL/rank
* clock stays honest), but re-park waits for this deadline — else every ~3s
* measure lease on a past-deadline worktree thrashes remount → re-park. */
parkCooldownUntilMs?: number | null
}
export type TerminalTabColdParkCandidate = ColdParkableTerminalTab & {
@@ -50,9 +56,10 @@ function getPendingActivationSpawnCount(value: boolean | number | undefined): nu
return typeof value === 'number' && value > 0 ? value : 0
}
// Why: parking relies on the daemon model snapshot to re-hydrate. Remote
// runtime and SSH PTYs have no local snapshot in this phase, and a session id
// minted for another worktree reattaches through a path parking cannot replay.
// Why: snapshot-backed = local daemon session owned by this worktree (foreign
// ids reattach through a path parking cannot replay). SSH is restorable too,
// via isParkRestorableTerminalPty + main's headless model; only remote-runtime
// ptys, which never transit main, stay unrestorable.
export function isSnapshotBackedTerminalPty(ptyId: string | null, worktreeId: string): boolean {
if (!ptyId) {
return false
@@ -67,6 +74,26 @@ export function isSnapshotBackedTerminalPty(ptyId: string | null, worktreeId: st
return separatorIdx !== -1 && ptyId.slice(0, separatorIdx) === worktreeId
}
export type TerminalParkRestorePolicy = {
/** settings.terminalSshViewParking !== false — the C1 SSH-parking kill switch. */
sshParkingEnabled?: boolean
}
// Why: SSH bytes transit local main, so main's headless model (served over
// pty:getMainBufferSnapshot) can re-hydrate a parked SSH reveal, with the
// relay's replay buffer as fallback — fact-mode watchers cover side effects
// either way. Remote-runtime ptys never transit main; they stay un-parkable.
export function isParkRestorableTerminalPty(
ptyId: string | null,
worktreeId: string,
policy?: TerminalParkRestorePolicy
): boolean {
if (isSnapshotBackedTerminalPty(ptyId, worktreeId)) {
return true
}
return policy?.sshParkingEnabled === true && ptyId !== null && parseAppSshPtyId(ptyId) !== null
}
export function canParkTerminalWorktreeRenderers(args: {
worktreeId: string
terminalTabs: readonly ColdParkableTerminalTab[]
@@ -78,15 +105,18 @@ export function canParkTerminalWorktreeRenderers(args: {
shouldMeasureHiddenWorktree: boolean
hasActivityTerminalPortal: boolean
hiddenSinceMs: number | null
parkCooldownUntilMs?: number | null
nowMs: number
coldParkDelayMs?: number
restorePolicy?: TerminalParkRestorePolicy
}): boolean {
if (
!args.parkingEnabled ||
args.isVisible ||
args.shouldMeasureHiddenWorktree ||
args.hasActivityTerminalPortal ||
args.hiddenSinceMs === null
args.hiddenSinceMs === null ||
(args.parkCooldownUntilMs != null && args.nowMs < args.parkCooldownUntilMs)
) {
return false
}
@@ -103,7 +133,7 @@ export function canParkTerminalWorktreeRenderers(args: {
if (getPendingActivationSpawnCount(tab.pendingActivationSpawn) > 0) {
return false
}
return isSnapshotBackedTerminalPty(tab.ptyId, args.worktreeId)
return isParkRestorableTerminalPty(tab.ptyId, args.worktreeId, args.restorePolicy)
})
}
@@ -114,13 +144,17 @@ export function canParkTerminalTabRenderer(args: {
parkingEnabled: boolean
nowMs: number
coldParkDelayMs?: number
/** Worktree-scoped post-measure cool-down (measure windows are per-worktree). */
parkCooldownUntilMs?: number | null
restorePolicy?: TerminalParkRestorePolicy
}): boolean {
const tab = args.terminalTab
if (
!args.parkingEnabled ||
tab.isVisible ||
tab.hasActivityTerminalPortal ||
tab.hiddenSinceMs === null
tab.hiddenSinceMs === null ||
(args.parkCooldownUntilMs != null && args.nowMs < args.parkCooldownUntilMs)
) {
return false
}
@@ -133,10 +167,10 @@ export function canParkTerminalTabRenderer(args: {
if (getPendingActivationSpawnCount(tab.pendingActivationSpawn) > 0) {
return false
}
return isSnapshotBackedTerminalPty(tab.ptyId, args.worktreeId)
return isParkRestorableTerminalPty(tab.ptyId, args.worktreeId, args.restorePolicy)
}
type ColdParkRetainCandidate = { id: string; hiddenSinceMs: number }
export type ColdParkRetainCandidate = { id: string; hiddenSinceMs: number }
// Why: the single most-recently-hidden candidate is the view the user just
// switched away from; keeping it warm regardless of the TTL or cap means
@@ -161,7 +195,7 @@ function selectLastActiveRetainedId(candidates: ColdParkRetainCandidate[]): stri
// ids hidden past hotRetainMs or beyond the limit cold-park. The last-active
// id is exempt from both so returning to it never pays a remount. Ties sort by
// id so the selection is deterministic.
function selectIdsBeyondHotRetain(
export function selectIdsBeyondHotRetain(
candidates: ColdParkRetainCandidate[],
args: { nowMs: number; hotRetainMs: number; hotRetainLimit: number }
): Set<string> {
@@ -197,6 +231,7 @@ export function selectColdParkedTerminalWorktrees(
pendingStartupByTabId: Readonly<Record<string, unknown>>
parkingEnabled: boolean
nowMs: number
restorePolicy?: TerminalParkRestorePolicy
} & TerminalColdParkPolicyOverrides
): Set<string> {
if (!args.parkingEnabled) {
@@ -212,7 +247,8 @@ export function selectColdParkedTerminalWorktrees(
pendingStartupByTabId: args.pendingStartupByTabId,
parkingEnabled: args.parkingEnabled,
nowMs: args.nowMs,
coldParkDelayMs
coldParkDelayMs,
...(args.restorePolicy ? { restorePolicy: args.restorePolicy } : {})
})
) {
continue
@@ -233,6 +269,8 @@ export function selectColdParkedTerminalTabs(
pendingStartupByTabId: Readonly<Record<string, unknown>>
parkingEnabled: boolean
nowMs: number
parkCooldownUntilMs?: number | null
restorePolicy?: TerminalParkRestorePolicy
} & TerminalColdParkPolicyOverrides
): Set<string> {
if (!args.parkingEnabled) {
@@ -249,7 +287,9 @@ export function selectColdParkedTerminalTabs(
pendingStartupByTabId: args.pendingStartupByTabId,
parkingEnabled: args.parkingEnabled,
nowMs: args.nowMs,
coldParkDelayMs
coldParkDelayMs,
parkCooldownUntilMs: args.parkCooldownUntilMs,
...(args.restorePolicy ? { restorePolicy: args.restorePolicy } : {})
})
) {
continue
@@ -262,55 +302,3 @@ export function selectColdParkedTerminalTabs(
hotRetainLimit: args.hotRetainLimit ?? TERMINAL_TAB_HOT_RETAIN_LIMIT
})
}
// Why: parking decisions change only at the cold-park and hot-retain
// deadlines, so callers schedule one recheck at the next deadline instead of
// polling.
function nextColdParkDeadlineDelayMs(args: {
parkingEnabled: boolean
hiddenSinceMs: number | null
nowMs: number
coldParkDelayMs: number
hotRetainMs: number
}): number | null {
if (!args.parkingEnabled || args.hiddenSinceMs === null) {
return null
}
const pendingDeadlines = [
args.hiddenSinceMs + args.coldParkDelayMs,
args.hiddenSinceMs + args.hotRetainMs
].filter((deadlineMs) => deadlineMs > args.nowMs)
return pendingDeadlines.length === 0 ? null : Math.min(...pendingDeadlines) - args.nowMs
}
export function getTerminalWorktreeColdParkRecheckDelayMs(args: {
parkingEnabled: boolean
hiddenSinceMs: number | null
nowMs: number
coldParkDelayMs?: number
hotRetainMs?: number
}): number | null {
return nextColdParkDeadlineDelayMs({
parkingEnabled: args.parkingEnabled,
hiddenSinceMs: args.hiddenSinceMs,
nowMs: args.nowMs,
coldParkDelayMs: args.coldParkDelayMs ?? TERMINAL_WORKTREE_COLD_PARK_DELAY_MS,
hotRetainMs: args.hotRetainMs ?? TERMINAL_WORKTREE_HOT_RETAIN_MS
})
}
export function getTerminalTabColdParkRecheckDelayMs(args: {
parkingEnabled: boolean
hiddenSinceMs: number | null
nowMs: number
coldParkDelayMs?: number
hotRetainMs?: number
}): number | null {
return nextColdParkDeadlineDelayMs({
parkingEnabled: args.parkingEnabled,
hiddenSinceMs: args.hiddenSinceMs,
nowMs: args.nowMs,
coldParkDelayMs: args.coldParkDelayMs ?? TERMINAL_TAB_COLD_PARK_DELAY_MS,
hotRetainMs: args.hotRetainMs ?? TERMINAL_TAB_HOT_RETAIN_MS
})
}
@@ -0,0 +1,195 @@
import { describe, expect, it } from 'vitest'
import { TERMINAL_WORKTREE_PARK_DELAY_MS } from './terminal-hidden-view-parking'
import {
TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS,
isEvictionExemptTerminalPty,
selectForceParkEvictableTabIds,
selectRetentionForceParkedTerminalWorktrees,
type TerminalWorktreeRetentionCandidate
} from './terminal-hidden-worktree-retention'
describe('isEvictionExemptTerminalPty', () => {
const worktreeId = 'repo::/worktree'
it('exempts only live local ptys a remount could not reattach', () => {
expect(isEvictionExemptTerminalPty('pty-local-detached', worktreeId)).toBe(true)
expect(isEvictionExemptTerminalPty('other::wt@@session-1', worktreeId)).toBe(true)
})
it('never exempts snapshot-backed, SSH, remote-runtime, or unbound ptys', () => {
expect(isEvictionExemptTerminalPty(`${worktreeId}@@session-1`, worktreeId)).toBe(false)
expect(isEvictionExemptTerminalPty('ssh:conn-1@@pty-1', worktreeId)).toBe(false)
expect(isEvictionExemptTerminalPty('remote:env-1@@t-1', worktreeId)).toBe(false)
expect(isEvictionExemptTerminalPty(null, worktreeId)).toBe(false)
})
})
describe('selectRetentionForceParkedTerminalWorktrees', () => {
const nowMs = 5_000_000
function retentionCandidate(
worktreeId: string,
hiddenSinceMs: number | null,
partial: Partial<TerminalWorktreeRetentionCandidate> = {}
): TerminalWorktreeRetentionCandidate {
return {
worktreeId,
hiddenSinceMs,
isVisible: false,
shouldMeasureHiddenWorktree: false,
hasActivityTerminalPortal: false,
ordinaryParkingCovers: false,
hasPendingSpawnWork: false,
...partial
}
}
const base = {
parkingEnabled: true,
retentionBudgetEnabled: true,
nowMs
}
it('returns empty when either kill switch is off', () => {
const worktrees = [
retentionCandidate('wt-1', nowMs - TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS)
]
expect(
selectRetentionForceParkedTerminalWorktrees({ ...base, worktrees, parkingEnabled: false })
).toEqual(new Set())
expect(
selectRetentionForceParkedTerminalWorktrees({
...base,
worktrees,
retentionBudgetEnabled: false
})
).toEqual(new Set())
})
it('force-parks the least-recently-hidden candidates beyond the retention limit', () => {
const worktrees = [
retentionCandidate('wt-1', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS - 3),
retentionCandidate('wt-2', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS - 2),
retentionCandidate('wt-3', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS - 1),
retentionCandidate('wt-4', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS)
]
// Why limit 2: wt-4 is last-active exempt, wt-3 fills the remaining slot; the two oldest evict.
expect(
selectRetentionForceParkedTerminalWorktrees({ ...base, worktrees, retentionLimit: 2 })
).toEqual(new Set(['wt-1', 'wt-2']))
})
it('force-parks past the TTL even under the limit, sparing a last-active candidate inside it', () => {
const worktrees = [
retentionCandidate('wt-old', nowMs - TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS),
retentionCandidate('wt-recent', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS)
]
expect(selectRetentionForceParkedTerminalWorktrees({ ...base, worktrees })).toEqual(
new Set(['wt-old'])
)
})
// Why: the last-active exemption keeps the warm cap's "return is always instant"
// promise, but carrying it into the eviction clock made "none past 45 minutes"
// false — a lone hidden un-parkable worktree stayed mounted for the whole session.
it('force-parks the last-active candidate once it passes the TTL (the exemption bounds the cap, not the clock)', () => {
const lone = [retentionCandidate('wt-lone', nowMs - TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS)]
expect(selectRetentionForceParkedTerminalWorktrees({ ...base, worktrees: lone })).toEqual(
new Set(['wt-lone'])
)
const insideTtl = [
retentionCandidate('wt-lone', nowMs - TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS + 1)
]
expect(selectRetentionForceParkedTerminalWorktrees({ ...base, worktrees: insideTtl })).toEqual(
new Set()
)
})
it('never force-parks visible, measuring, portaled, covered, pending, or fresh candidates', () => {
const aged = nowMs - TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS
const worktrees = [
retentionCandidate('wt-visible', aged, { isVisible: true }),
retentionCandidate('wt-measure', aged, { shouldMeasureHiddenWorktree: true }),
retentionCandidate('wt-portal', aged, { hasActivityTerminalPortal: true }),
retentionCandidate('wt-covered', aged, { ordinaryParkingCovers: true }),
retentionCandidate('wt-pending', aged, { hasPendingSpawnWork: true }),
retentionCandidate('wt-fresh', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS + 1),
retentionCandidate('wt-unhidden', null)
]
expect(selectRetentionForceParkedTerminalWorktrees({ ...base, worktrees })).toEqual(new Set())
})
// Why: hiddenSince (and with it TTL ranking) survives a measure window, so
// without the cool-down veto a measured past-TTL worktree would force-park
// again the instant the lease ends — the remount/reattach thrash Bug #2.
it('holds a candidate out of force-park until its post-measure cool-down ends', () => {
const aged = nowMs - TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS
// Why the recent sibling: it takes the last-active exemption, so the aged
// candidate's verdict is decided by the cool-down alone.
const recent = retentionCandidate('wt-recent', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS)
expect(
selectRetentionForceParkedTerminalWorktrees({
...base,
worktrees: [
retentionCandidate('wt-measured', aged, { parkCooldownUntilMs: nowMs + 1 }),
recent
]
})
).toEqual(new Set())
expect(
selectRetentionForceParkedTerminalWorktrees({
...base,
worktrees: [retentionCandidate('wt-measured', aged, { parkCooldownUntilMs: nowMs }), recent]
})
).toEqual(new Set(['wt-measured']))
})
it('is idempotent and only grows as time advances (flip-loop dwell)', () => {
const worktrees = [
retentionCandidate('wt-1', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS - 3),
retentionCandidate('wt-2', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS - 2),
retentionCandidate('wt-3', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS - 1),
retentionCandidate('wt-4', nowMs - TERMINAL_WORKTREE_PARK_DELAY_MS)
]
const first = selectRetentionForceParkedTerminalWorktrees({
...base,
worktrees,
retentionLimit: 2
})
const second = selectRetentionForceParkedTerminalWorktrees({
...base,
worktrees,
retentionLimit: 2
})
expect(second).toEqual(first)
// Why: with unchanged inputs, a later evaluation may only ADD members —
// a verdict that oscillates with time is the React-#185 ingredient.
for (const laterMs of [nowMs + 1_000, nowMs + TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS]) {
const later = selectRetentionForceParkedTerminalWorktrees({
...base,
worktrees,
retentionLimit: 2,
nowMs: laterMs
})
for (const id of first) {
expect(later.has(id)).toBe(true)
}
}
})
})
describe('selectForceParkEvictableTabIds', () => {
const tabs = [{ id: 'tab-exempt' }, { id: 'tab-evictable' }]
it('drops eviction-exempt tabs from the capture and unmount set', () => {
expect(selectForceParkEvictableTabIds(tabs, (tab) => tab.id === 'tab-exempt')).toEqual([
'tab-evictable'
])
})
// Why: an all-exempt worktree still reports as force-parked while freeing nothing —
// the degenerate case a fleet-wide daemon fail-open produces, which the host logs.
it('yields nothing when every tab is exempt', () => {
expect(selectForceParkEvictableTabIds(tabs, () => true)).toEqual([])
})
})
@@ -0,0 +1,130 @@
import { isRemoteRuntimePtyId } from '@/runtime/runtime-terminal-inspection'
import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id'
import {
TERMINAL_WORKTREE_COLD_PARK_DELAY_MS,
isSnapshotBackedTerminalPty,
selectIdsBeyondHotRetain,
type ColdParkRetainCandidate,
type TerminalColdParkPolicyOverrides
} from './terminal-hidden-view-parking'
// Why these sizes: a retained hidden pane costs a measured ~2.5MB of V8 heap
// at the 5k-row default scrollback and ~19MB at 50k (plus per-pane queues),
// not the ~4-5MB per WORKTREE the warm cap assumed — so un-parkable worktrees
// (pty classes parking can't restore) get a retention budget: at most 12 stay
// mounted while hidden and none past 45 minutes, evicted least-recently-hidden
// first via force-park. The TTL is absolute: the last-active exemption bounds
// the cap, never the clock.
// NOT covered by this bound: eviction-exempt TABS (isEvictionExemptTerminalPty
// — live local ptys a remount would respawn, orphaning the shell). Their panes
// stay mounted through a force-park at any age, so a fleet-wide daemon
// fail-open can leave the budget freeing nothing; Terminal.tsx logs that
// degenerate case rather than pretending the bound held.
// Also NOT covered: per-pane scrollback size. Hidden-pane scrollback demotion
// was intentionally removed — the bound is worktree count + TTL only, so a
// spared worktree (last-active, exempt tabs) can hold full 50k-row scrollback
// indefinitely. Accepted tradeoff: high-scrollback users rely on unmount
// eviction, not demotion.
export const TERMINAL_HIDDEN_WORKTREE_RETENTION_LIMIT = 12
export const TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS = 45 * 60_000
// Why: an eviction-exempt pty is a live local one a remount could not reattach
// (daemon-fail-open separator-less ids, ptys minted under another worktree) — a
// fresh spawn would orphan the live shell. Its TAB keeps its mounted pane when
// the worktree force-parks (per-tab exclusion, mirroring Activity portals).
// Per-PTY, not per-tab: the coverage veto that makes a worktree a retention
// candidate walks every split pane, so the exemption must too (see
// isEvictionExemptTerminalTab).
export function isEvictionExemptTerminalPty(
ptyId: string | null | undefined,
worktreeId: string
): boolean {
if (!ptyId || isRemoteRuntimePtyId(ptyId) || parseAppSshPtyId(ptyId)) {
return false
}
return !isSnapshotBackedTerminalPty(ptyId, worktreeId)
}
export type TerminalWorktreeRetentionCandidate = {
worktreeId: string
hiddenSinceMs: number | null
isVisible: boolean
shouldMeasureHiddenWorktree: boolean
hasActivityTerminalPortal: boolean
/** Post-measure cool-down (see TerminalWorktreeColdParkCandidate): force-park
* must not re-engage right after a measure window ends, but hiddenSince —
* and with it the TTL/ranking clock — stays untouched. */
parkCooldownUntilMs?: number | null
/** Ordinary cold parking can evict this worktree (park-eligible AND watcher-coverable) — the warm cap bounds it already. */
ordinaryParkingCovers: boolean
/** Pending startup or activation spawn — a mount is imminent; never evict. */
hasPendingSpawnWork: boolean
}
/**
* Retention budget over the worktrees ordinary parking can never evict: any
* hidden un-parkable worktree beyond the retention limit or TTL force-parks —
* panes unmount, watchers cover the tabs whose transport exists, and reveal
* restores per pty class (the app-restart experience). Eviction-exempt tabs
* do NOT veto the worktree: they keep their mounted panes via the per-tab
* exclusion (Activity-portal pattern) while sibling tabs unmount, so one
* exempt tab can no longer pin co-located remote-runtime tabs forever.
* Ranking reuses the hot-retain machinery, so deterministic ties hold here too,
* and the verdict changes only at deadlines or on real state transitions (no
* new flip-loop inputs). The last-active exemption it carries spares one
* worktree from the CAP only — the TTL below overrides it, else a lone hidden
* un-parkable worktree would stay mounted for the whole session.
*/
export function selectRetentionForceParkedTerminalWorktrees(
args: {
worktrees: readonly TerminalWorktreeRetentionCandidate[]
parkingEnabled: boolean
retentionBudgetEnabled: boolean
nowMs: number
} & TerminalColdParkPolicyOverrides
): Set<string> {
if (!args.parkingEnabled || !args.retentionBudgetEnabled) {
return new Set()
}
const coldParkDelayMs = args.coldParkDelayMs ?? TERMINAL_WORKTREE_COLD_PARK_DELAY_MS
const candidates: ColdParkRetainCandidate[] = []
for (const worktree of args.worktrees) {
if (
worktree.hiddenSinceMs === null ||
worktree.isVisible ||
worktree.shouldMeasureHiddenWorktree ||
worktree.hasActivityTerminalPortal ||
worktree.ordinaryParkingCovers ||
worktree.hasPendingSpawnWork ||
(worktree.parkCooldownUntilMs != null && args.nowMs < worktree.parkCooldownUntilMs) ||
args.nowMs - worktree.hiddenSinceMs < coldParkDelayMs
) {
continue
}
candidates.push({ id: worktree.worktreeId, hiddenSinceMs: worktree.hiddenSinceMs })
}
const retentionTtlMs = args.retentionTtlMs ?? TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS
const forceParkedIds = selectIdsBeyondHotRetain(candidates, {
nowMs: args.nowMs,
hotRetainMs: retentionTtlMs,
hotRetainLimit: args.retentionLimit ?? TERMINAL_HIDDEN_WORKTREE_RETENTION_LIMIT
})
// Why re-applied here: selectIdsBeyondHotRetain spares the last-active id from
// its clock too, which is right for the warm cap (instant return after a
// meeting) but makes "none past 45 minutes" false for a lone hidden worktree.
for (const candidate of candidates) {
if (args.nowMs - candidate.hiddenSinceMs >= retentionTtlMs) {
forceParkedIds.add(candidate.id)
}
}
return forceParkedIds
}
// Why exported: an all-exempt force-park frees nothing, and that degenerate
// case is only observable if the empty selection is a value the host can test.
export function selectForceParkEvictableTabIds<T extends { id: string }>(
tabs: readonly T[],
isExempt: (tab: T) => boolean
): string[] {
return tabs.filter((tab) => !isExempt(tab)).map((tab) => tab.id)
}
@@ -79,6 +79,7 @@ type MockStoreState = {
}
>
runtimePaneTitlesByTabId: Record<string, Record<number, string>>
settings: { terminalSshViewParking?: boolean } | null
clearTabLaunchAgent: ReturnType<typeof vi.fn>
clearRuntimePaneTitle: ReturnType<typeof vi.fn>
setTabLayout: ReturnType<typeof vi.fn>
@@ -91,6 +92,10 @@ vi.mock('@/store', () => ({
useAppStore: { getState: () => mockStoreState }
}))
import {
isEvictionExemptTerminalTab,
selectEvictionExemptTerminalTabIds
} from './terminal-eviction-exempt-tabs'
import {
canWatcherCoverParkedTerminalTab,
captureParkedTerminalPaneCandidates,
@@ -135,6 +140,7 @@ describe('terminal-parked-tab-watchers', () => {
tabsByWorktree: {},
terminalLayoutsByTabId: {},
runtimePaneTitlesByTabId: {},
settings: null,
clearTabLaunchAgent: vi.fn(),
clearRuntimePaneTitle: vi.fn(),
setTabLayout: vi.fn(),
@@ -204,10 +210,9 @@ describe('terminal-parked-tab-watchers', () => {
expect(startedWatchers[0].options).toMatchObject({ ptyId: SECOND_PTY_ID })
})
it('never starts watchers for remote-runtime or SSH PTYs', () => {
it('never starts watchers for remote-runtime PTYs', () => {
capturePanes([
{ ptyId: 'remote:env-1@@terminal-1', paneId: 1, leafId: LEAF_ID, drivesTabTitle: true },
{ ptyId: 'ssh:conn-1@@pty-1', paneId: 2, leafId: SECOND_LEAF_ID, drivesTabTitle: false }
{ ptyId: 'remote:env-1@@terminal-1', paneId: 1, leafId: LEAF_ID, drivesTabTitle: true }
])
syncParked({ tabs: [{ id: TAB_ID, ptyId: null }] })
@@ -217,6 +222,22 @@ describe('terminal-parked-tab-watchers', () => {
expect(getParkedTerminalWatcherTabIds()).toEqual([TAB_ID])
})
it('starts watchers for SSH PTYs (C1 SSH parking, default on)', () => {
capturePanes([{ ptyId: 'ssh:conn-1@@pty-1', paneId: 1, leafId: LEAF_ID, drivesTabTitle: true }])
syncParked({ tabs: [{ id: TAB_ID, ptyId: 'ssh:conn-1@@pty-1' }] })
expect(startParkedTerminalByteWatcher).toHaveBeenCalledTimes(1)
expect(startedWatchers[0].options).toMatchObject({ ptyId: 'ssh:conn-1@@pty-1' })
})
it('never starts watchers for SSH PTYs when terminalSshViewParking is off', () => {
mockStoreState.settings = { terminalSshViewParking: false }
capturePanes([{ ptyId: 'ssh:conn-1@@pty-1', paneId: 1, leafId: LEAF_ID, drivesTabTitle: true }])
syncParked({ tabs: [{ id: TAB_ID, ptyId: null }] })
expect(startParkedTerminalByteWatcher).not.toHaveBeenCalled()
})
it('keeps existing watchers across repeated syncs of the same parked state', () => {
capturePanes([{ ptyId: PTY_ID, paneId: 1, leafId: LEAF_ID, drivesTabTitle: true }])
syncParked()
@@ -702,6 +723,28 @@ describe('terminal-parked-tab-watchers', () => {
})
it('rejects a capture containing a PTY without snapshot backing', () => {
capturePanes([
{ ptyId: PTY_ID, paneId: 1, leafId: LEAF_ID, drivesTabTitle: true },
// Why foreign-worktree id: minted under another worktree, never restorable.
{ ptyId: 'other::wt@@session-9', paneId: 2, leafId: SECOND_LEAF_ID, drivesTabTitle: false }
])
expect(canWatcherCoverParkedTerminalTab(WORKTREE_ID, { id: TAB_ID, ptyId: PTY_ID })).toBe(
false
)
})
it('accepts an SSH PTY under the default C1 SSH-parking policy', () => {
capturePanes([
{ ptyId: PTY_ID, paneId: 1, leafId: LEAF_ID, drivesTabTitle: true },
{ ptyId: 'ssh:conn-1@@pty-1', paneId: 2, leafId: SECOND_LEAF_ID, drivesTabTitle: false }
])
expect(canWatcherCoverParkedTerminalTab(WORKTREE_ID, { id: TAB_ID, ptyId: PTY_ID })).toBe(
true
)
})
it('rejects an SSH PTY when terminalSshViewParking is off', () => {
mockStoreState.settings = { terminalSshViewParking: false }
capturePanes([
{ ptyId: PTY_ID, paneId: 1, leafId: LEAF_ID, drivesTabTitle: true },
{ ptyId: 'ssh:conn-1@@pty-1', paneId: 2, leafId: SECOND_LEAF_ID, drivesTabTitle: false }
@@ -741,6 +784,81 @@ describe('terminal-parked-tab-watchers', () => {
)
})
})
describe('isEvictionExemptTerminalTab', () => {
// Why these pair with coverage: the same split tab that fails coverage (so
// force-park targets its worktree) must be exempt, or force-park unmounts
// the very live pty the exemption exists to protect.
it('exempts a split tab whose SECOND pane holds the unrestorable pty', () => {
capturePanes([
{ ptyId: PTY_ID, paneId: 1, leafId: LEAF_ID, drivesTabTitle: true },
{ ptyId: 'other::wt@@session-9', paneId: 2, leafId: SECOND_LEAF_ID, drivesTabTitle: false }
])
const tab = { id: TAB_ID, ptyId: PTY_ID }
expect(canWatcherCoverParkedTerminalTab(WORKTREE_ID, tab)).toBe(false)
expect(isEvictionExemptTerminalTab(tab, WORKTREE_ID)).toBe(true)
})
// Why: locks the documented residual — detection is per pane, retention is
// per tab, so the snapshot-backed first leaf is pinned by its fail-open
// sibling instead of parking on its own.
it('exempts a split tab even when its other leaf is snapshot-backed', () => {
capturePanes([
{ ptyId: PTY_ID, paneId: 1, leafId: LEAF_ID, drivesTabTitle: true },
// Why separator-less: the daemon-fail-open class, restorable by nothing.
{ ptyId: 'pty-local-detached', paneId: 2, leafId: SECOND_LEAF_ID, drivesTabTitle: false }
])
expect(isEvictionExemptTerminalTab({ id: TAB_ID, ptyId: PTY_ID }, WORKTREE_ID)).toBe(true)
})
it('exempts a split tab whose second leaf pty comes from the layout fallback', () => {
mockStoreState.terminalLayoutsByTabId[TAB_ID] = {
root: {
type: 'split',
direction: 'row',
first: { type: 'leaf', leafId: LEAF_ID },
second: { type: 'leaf', leafId: SECOND_LEAF_ID }
},
activeLeafId: LEAF_ID,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_ID]: PTY_ID, [SECOND_LEAF_ID]: 'pty-local-detached' }
}
expect(isEvictionExemptTerminalTab({ id: TAB_ID, ptyId: PTY_ID }, WORKTREE_ID)).toBe(true)
})
it('does not exempt a split tab whose panes are all snapshot-backed', () => {
capturePanes([
{ ptyId: PTY_ID, paneId: 1, leafId: LEAF_ID, drivesTabTitle: true },
{ ptyId: SECOND_PTY_ID, paneId: 2, leafId: SECOND_LEAF_ID, drivesTabTitle: false }
])
expect(isEvictionExemptTerminalTab({ id: TAB_ID, ptyId: PTY_ID }, WORKTREE_ID)).toBe(false)
})
it('exempts on tab.ptyId alone when no panes resolve', () => {
expect(
isEvictionExemptTerminalTab({ id: TAB_ID, ptyId: 'pty-local-detached' }, WORKTREE_ID)
).toBe(true)
})
it('never exempts remote-runtime or SSH panes', () => {
capturePanes([
{ ptyId: 'remote:env-1@@t-1', paneId: 1, leafId: LEAF_ID, drivesTabTitle: true },
{ ptyId: 'ssh:conn-1@@pty-1', paneId: 2, leafId: SECOND_LEAF_ID, drivesTabTitle: false }
])
expect(isEvictionExemptTerminalTab({ id: TAB_ID, ptyId: null }, WORKTREE_ID)).toBe(false)
})
})
describe('selectEvictionExemptTerminalTabIds', () => {
it('collects only the exempt tabs of one worktree in a single pass', () => {
expect(
selectEvictionExemptTerminalTabIds(WORKTREE_ID, [
{ id: TAB_ID, ptyId: 'pty-local-detached' },
{ id: 'tab-restorable', ptyId: PTY_ID }
])
).toEqual(new Set([TAB_ID]))
})
})
})
describe('fallbackParkedPaneCandidates', () => {
@@ -17,7 +17,10 @@ import { detachTerminalLayoutLeaf } from './terminal-layout-leaf-detach'
import { subscribeToPtyExit } from './pty-dispatcher'
import { discardPreHandlerPtyState } from './pty-pre-handler-buffer'
import { startParkedTerminalByteWatcher } from './parked-terminal-byte-watcher'
import { isSnapshotBackedTerminalPty } from './terminal-hidden-view-parking'
import {
isParkRestorableTerminalPty,
type TerminalParkRestorePolicy
} from './terminal-hidden-view-parking'
import {
resolveTabTitleAfterPaneClose,
shouldClearLaunchAgentForClosedPane
@@ -81,7 +84,7 @@ export function fallbackParkedPaneCandidates(
}
// Why: start path and eligibility check must resolve identical candidates, or a tab passes the check then starts uncoverable.
function resolveParkedTerminalPaneCandidates(
export function resolveParkedTerminalPaneCandidates(
tab: ParkableTerminalTabModel,
state: ParkedPaneFallbackState
): ParkedTerminalPaneCapture[] {
@@ -94,9 +97,18 @@ function resolveParkedTerminalPaneCandidates(
return capturedIsCurrent ? captured.panes : fallbackParkedPaneCandidates(tab, state)
}
// Why: fact-mode watchers work for any pty whose bytes transit local main —
// SSH included — so watcher coverage follows the park-restore policy, not the
// stricter daemon-snapshot predicate.
function parkRestorePolicyFromState(state: {
settings: { terminalSshViewParking?: boolean } | null
}): TerminalParkRestorePolicy {
return { sshParkingEnabled: state.settings?.terminalSshViewParking !== false }
}
/**
* Whether parked byte watchers can fully cover this tab's PTYs (every candidate
* has a snapshot-backed PTY on a valid leaf). Hosts must refuse to park a tab
* has a park-restorable PTY on a valid leaf). Hosts must refuse to park a tab
* that fails this check, or bell/title/completion side effects silently drop.
*/
export function canWatcherCoverParkedTerminalTab(
@@ -105,14 +117,16 @@ export function canWatcherCoverParkedTerminalTab(
// Why: cold activation needs stronger snapshot support (view never mounted); ordinary parking can reattach a mounted view.
isPtyEligible: ParkedTerminalPtyEligibility = allowSnapshotBackedPty
): boolean {
const panes = resolveParkedTerminalPaneCandidates(tab, useAppStore.getState())
const state = useAppStore.getState()
const panes = resolveParkedTerminalPaneCandidates(tab, state)
const restorePolicy = parkRestorePolicyFromState(state)
return (
panes.length > 0 &&
panes.every(
(pane) =>
pane.ptyId !== null &&
isTerminalLeafId(pane.leafId) &&
isSnapshotBackedTerminalPty(pane.ptyId, worktreeId) &&
isParkRestorableTerminalPty(pane.ptyId, worktreeId, restorePolicy) &&
isPtyEligible(pane.ptyId)
)
)
@@ -125,6 +139,7 @@ function startParkedTabWatchers(
): void {
const state = useAppStore.getState()
const panes = resolveParkedTerminalPaneCandidates(tab, state)
const restorePolicy = parkRestorePolicyFromState(state)
const disposersByPtyId = new Map<string, () => void>()
const paneIdByPtyId = new Map<string, number>()
for (const pane of panes) {
@@ -134,7 +149,7 @@ function startParkedTabWatchers(
!ptyId ||
disposersByPtyId.has(ptyId) ||
!isTerminalLeafId(pane.leafId) ||
!isSnapshotBackedTerminalPty(ptyId, worktreeId)
!isParkRestorableTerminalPty(ptyId, worktreeId, restorePolicy)
) {
continue
}
@@ -51,6 +51,16 @@ export function getParkedTerminalWatcherTabIds(): string[] {
return Array.from(parkedWatchersByTabId.keys())
}
/**
* Whether this tab is parked right now — the reveal remount's own mount effect
* runs before the host effect that disposes the watcher (child effects first),
* so a pane reading this at connect time can tell a park-reveal from an
* in-place reattach. Empty entries are pinned-close tombstones, not live parks.
*/
export function isTerminalTabParked(tabId: string): boolean {
return (parkedWatchersByTabId.get(tabId)?.disposersByPtyId.size ?? 0) > 0
}
export function disposeParkedTabWatchers(tabId: string): void {
const entry = parkedWatchersByTabId.get(tabId)
if (!entry) {
@@ -1,6 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
type MockE2EConfig = { exposeStore: boolean; terminalParkingDelayMs: number | null }
type MockE2EConfig = {
exposeStore: boolean
terminalParkingDelayMs: number | null
terminalRetentionLimit: number | null
}
let mockE2EConfig: MockE2EConfig
@@ -21,6 +25,8 @@ type TerminalParkingE2EOverridesModule = {
coldParkDelayMs?: number
hotRetainMs?: number
hotRetainLimit?: number
retentionTtlMs?: number
retentionLimit?: number
}
registerTerminalParkingDebugHandle: () => void
}
@@ -32,7 +38,11 @@ async function importOverridesModule(): Promise<TerminalParkingE2EOverridesModul
describe('getTerminalParkingPolicyOverrides', () => {
beforeEach(() => {
mockE2EConfig = { exposeStore: false, terminalParkingDelayMs: null }
mockE2EConfig = {
exposeStore: false,
terminalParkingDelayMs: null,
terminalRetentionLimit: null
}
delete (globalThis as { window?: unknown }).window
})
@@ -41,13 +51,17 @@ describe('getTerminalParkingPolicyOverrides', () => {
})
it('ignores the delay override outside e2e (exposeStore off)', async () => {
mockE2EConfig = { exposeStore: false, terminalParkingDelayMs: 500 }
mockE2EConfig = {
exposeStore: false,
terminalParkingDelayMs: 500,
terminalRetentionLimit: null
}
const { getTerminalParkingPolicyOverrides } = await importOverridesModule()
expect(getTerminalParkingPolicyOverrides()).toEqual({})
})
it('maps the e2e delay to BOTH coldParkDelayMs and hotRetainMs', async () => {
mockE2EConfig = { exposeStore: true, terminalParkingDelayMs: 500 }
it('maps the e2e delay to coldParkDelayMs and hotRetainMs but never the absolute retention TTL', async () => {
mockE2EConfig = { exposeStore: true, terminalParkingDelayMs: 500, terminalRetentionLimit: null }
const { getTerminalParkingPolicyOverrides } = await importOverridesModule()
expect(getTerminalParkingPolicyOverrides()).toEqual({
coldParkDelayMs: 500,
@@ -56,13 +70,47 @@ describe('getTerminalParkingPolicyOverrides', () => {
})
it('returns no overrides when no delay is configured', async () => {
mockE2EConfig = { exposeStore: true, terminalParkingDelayMs: null }
mockE2EConfig = {
exposeStore: true,
terminalParkingDelayMs: null,
terminalRetentionLimit: null
}
const { getTerminalParkingPolicyOverrides } = await importOverridesModule()
expect(getTerminalParkingPolicyOverrides()).toEqual({})
})
it('maps the e2e retention limit independently of the delay', async () => {
mockE2EConfig = { exposeStore: true, terminalParkingDelayMs: null, terminalRetentionLimit: 1 }
const { getTerminalParkingPolicyOverrides } = await importOverridesModule()
expect(getTerminalParkingPolicyOverrides()).toEqual({ retentionLimit: 1 })
})
it('combines the delay overrides with the retention limit when both are set', async () => {
mockE2EConfig = { exposeStore: true, terminalParkingDelayMs: 500, terminalRetentionLimit: 1 }
const { getTerminalParkingPolicyOverrides } = await importOverridesModule()
expect(getTerminalParkingPolicyOverrides()).toEqual({
coldParkDelayMs: 500,
hotRetainMs: 500,
retentionLimit: 1
})
})
it('ignores the retention limit outside e2e (exposeStore off)', async () => {
mockE2EConfig = { exposeStore: false, terminalParkingDelayMs: null, terminalRetentionLimit: 1 }
const { getTerminalParkingPolicyOverrides } = await importOverridesModule()
expect(getTerminalParkingPolicyOverrides()).toEqual({})
})
it('rejects non-integer or non-positive retention limits', async () => {
mockE2EConfig = { exposeStore: true, terminalParkingDelayMs: null, terminalRetentionLimit: 1.5 }
const overridesModule = await importOverridesModule()
expect(overridesModule.getTerminalParkingPolicyOverrides()).toEqual({})
mockE2EConfig = { exposeStore: true, terminalParkingDelayMs: null, terminalRetentionLimit: 0 }
expect(overridesModule.getTerminalParkingPolicyOverrides()).toEqual({})
})
it('registers window.__terminalParkingDebug on import under exposeStore', async () => {
mockE2EConfig = { exposeStore: true, terminalParkingDelayMs: 500 }
mockE2EConfig = { exposeStore: true, terminalParkingDelayMs: 500, terminalRetentionLimit: null }
const testWindow: {
__terminalParkingDebug?: { parkDelayMs: number; parkedTabIds: () => string[] }
} = {}
@@ -73,7 +121,11 @@ describe('getTerminalParkingPolicyOverrides', () => {
})
it('does not register the debug handle outside e2e', async () => {
mockE2EConfig = { exposeStore: false, terminalParkingDelayMs: null }
mockE2EConfig = {
exposeStore: false,
terminalParkingDelayMs: null,
terminalRetentionLimit: null
}
const testWindow: { __terminalParkingDebug?: unknown } = {}
;(globalThis as { window?: unknown }).window = testWindow
await importOverridesModule()
@@ -10,10 +10,23 @@ import { getParkedTerminalWatcherTabIds } from './terminal-parked-tab-watchers'
// in the hot-retain working set for 5 minutes and never park within a test
// run. Gated on exposeStore so packaged builds ignore stray env vars.
export function getTerminalParkingPolicyOverrides(): TerminalColdParkPolicyOverrides {
const delayMs = e2eConfig.exposeStore ? e2eConfig.terminalParkingDelayMs : null
return typeof delayMs === 'number' && Number.isFinite(delayMs) && delayMs > 0
? { coldParkDelayMs: delayMs, hotRetainMs: delayMs }
: {}
if (!e2eConfig.exposeStore) {
return {}
}
const delayMs = e2eConfig.terminalParkingDelayMs
const retentionLimit = e2eConfig.terminalRetentionLimit
return {
// Why the retention TTL keeps production timing: it is absolute (the
// last-active exemption does not spare it), so shrinking it here would
// evict the newest hidden worktree the cap specs assert stays mounted.
...(typeof delayMs === 'number' && Number.isFinite(delayMs) && delayMs > 0
? { coldParkDelayMs: delayMs, hotRetainMs: delayMs }
: {}),
// Why: limit=1 lets a spec force-park with only two hidden un-parkable worktrees (production floor is 12).
...(typeof retentionLimit === 'number' && Number.isInteger(retentionLimit) && retentionLimit > 0
? { retentionLimit }
: {})
}
}
export function registerTerminalParkingDebugHandle(): void {
@@ -219,6 +219,78 @@ describe('captureTerminalShutdownLayout', () => {
expect(buffer).toHaveLength(fittingRows * 1024 + CURSOR_HOME.length)
})
it('bounds serialize probes while capping an oversized buffer by UTF-8 bytes', async () => {
const { captureTerminalShutdownLayout } = await import('./terminal-shutdown-layout-capture')
const multibyteRow = 'é'.repeat(1024)
const serialize = vi.fn((options?: { scrollback?: number }) =>
multibyteRow.repeat(options?.scrollback ?? 0)
)
const pane = {
id: 1,
leafId: LEAF_ID,
stablePaneId: LEAF_ID,
terminal: mockTerminal(512),
serializeAddon: { serialize }
}
const manager = {
getPanes: vi.fn(() => [pane]),
getActivePane: vi.fn(() => pane)
}
const layout = captureTerminalShutdownLayout({
manager: manager as never,
container: mockRootForPane(1),
expandedPaneId: null,
paneTransports: new Map([[1, { getPtyId: vi.fn(() => 'pty-1') }]]),
paneTitlesByPaneId: { 1: 'ssh shell' },
existingLayout: undefined
})
// Full pass plus at most MAX_SCROLLBACK_FIT_PROBES fit probes; a bisection took 10+.
expect(serialize.mock.calls.length).toBeLessThanOrEqual(5)
expect(getUtf8ByteLength(layout.buffersByLeafId?.[LEAF_ID] ?? '')).toBeLessThanOrEqual(
TERMINAL_SCROLLBACK_SESSION_BUFFER_BYTE_LIMIT
)
})
it('keeps most of the byte budget when dense recent rows sit above sparse scrollback', async () => {
const { captureTerminalShutdownLayout } = await import('./terminal-shutdown-layout-capture')
// Why this shape: the common terminal profile (a long quiet prompt history under a dense
// build/agent run) makes bytes-per-row wildly non-uniform, which a pure secant step creeps on.
const DENSE_ROWS = 1_000
const DENSE_ROW = 'x'.repeat(600)
const serialize = vi.fn((options?: { scrollback?: number }) => {
const rows = options?.scrollback ?? 0
const dense = Math.min(rows, DENSE_ROWS)
return '.'.repeat(Math.max(rows - DENSE_ROWS, 0)) + DENSE_ROW.repeat(dense)
})
const pane = {
id: 1,
leafId: LEAF_ID,
stablePaneId: LEAF_ID,
terminal: mockTerminal(5_000),
serializeAddon: { serialize }
}
const manager = {
getPanes: vi.fn(() => [pane]),
getActivePane: vi.fn(() => pane)
}
const layout = captureTerminalShutdownLayout({
manager: manager as never,
container: mockRootForPane(1),
expandedPaneId: null,
paneTransports: new Map([[1, { getPtyId: vi.fn(() => 'pty-1') }]]),
paneTitlesByPaneId: { 1: 'ssh shell' },
existingLayout: undefined
})
const bytes = getUtf8ByteLength(layout.buffersByLeafId?.[LEAF_ID] ?? '')
expect(bytes).toBeLessThanOrEqual(TERMINAL_SCROLLBACK_SESSION_BUFFER_BYTE_LIMIT)
expect(bytes).toBeGreaterThan(TERMINAL_SCROLLBACK_SESSION_BUFFER_BYTE_LIMIT * 0.9)
expect(serialize.mock.calls.length).toBeLessThanOrEqual(5)
})
it('does not preserve prior scrollback buffers or refs for a cleared leaf', async () => {
const { captureTerminalShutdownLayout } = await import('./terminal-shutdown-layout-capture')
const pane = {
@@ -7,7 +7,7 @@ import { mergeCapturedLeafState } from './merge-captured-leaf-state'
import { resolveTerminalLayoutActiveLeafId } from './terminal-layout-leaf-ids'
import { TERMINAL_SCROLLBACK_SESSION_BUFFER_BYTE_LIMIT } from '../../../../shared/terminal-scrollback-limits'
import { serializeWithAbsoluteCursor } from '../../../../shared/terminal-serialize-absolute-cursor'
import { measureUtf8ByteLength } from '../../../../shared/utf8-byte-limits'
import { getUtf8ByteLength, measureUtf8ByteLength } from '../../../../shared/utf8-byte-limits'
const MAX_BUFFER_BYTES = TERMINAL_SCROLLBACK_SESSION_BUFFER_BYTE_LIMIT
@@ -46,6 +46,49 @@ function fitsSessionScrollbackByteLimit(serialized: string): boolean {
return !measureUtf8ByteLength(serialized, { stopAfterBytes: MAX_BUFFER_BYTES }).exceededLimit
}
// Why bounded: a plain row bisection costs ~13 full serializes per over-limit pane (~250ms at the
// 5k scrollback default, ~700ms at 50k), and force-park pays it synchronously per evicted pane.
const MAX_SCROLLBACK_FIT_PROBES = 4
/** Largest tail of `pane` that fits the session byte cap, found in a few interpolation probes. */
function serializeWithinSessionScrollbackByteLimit(
pane: ShutdownPane,
oversized: string,
scrollback: number
): string {
let overRows = scrollback
let overBytes = getUtf8ByteLength(oversized)
let fitRows = 0
let fitBytes = 0
let best: string | null = null
// Why the extra probes before the first fit: returning '' would drop the whole pane, and those
// probes shrink geometrically, so they cost less in total than a bisection's upper-half passes.
for (let probe = 0; probe < MAX_SCROLLBACK_FIT_PROBES || best === null; probe += 1) {
const anchorRows = best === null ? overRows : fitRows
const anchorBytes = best === null ? overBytes : fitBytes
// Bytes grow ~linearly with rows, so a secant step lands on the exact fit for uniform
// scrollback; the midpoint floor stops it creeping when dense recent rows sit above sparse old ones.
const estimate = Math.floor((anchorRows * MAX_BUFFER_BYTES) / Math.max(anchorBytes, 1))
const midpoint = Math.floor((fitRows + overRows) / 2)
const rows = Math.min(Math.max(Math.min(estimate, midpoint), fitRows + 1), overRows - 1)
if (rows <= fitRows || rows >= overRows) {
break
}
const attempt = serializeWithAbsoluteCursor(pane.serializeAddon, pane.terminal, {
scrollback: rows
})
if (fitsSessionScrollbackByteLimit(attempt)) {
best = attempt
fitRows = rows
fitBytes = getUtf8ByteLength(attempt)
} else {
overRows = rows
overBytes = getUtf8ByteLength(attempt)
}
}
return best ?? ''
}
export function captureTerminalShutdownLayout({
manager,
container,
@@ -76,22 +119,7 @@ export function captureTerminalShutdownLayout({
// Why: SSH sleep keeps this string in session JSON; cap by UTF-8
// bytes so non-ASCII scrollback cannot bypass the intended bound.
if (!fitsSessionScrollbackByteLimit(serialized) && scrollback > 1) {
let lo = 1
let hi = scrollback
let best = ''
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2)
const attempt = serializeWithAbsoluteCursor(pane.serializeAddon, pane.terminal, {
scrollback: mid
})
if (fitsSessionScrollbackByteLimit(attempt)) {
best = attempt
lo = mid + 1
} else {
hi = mid - 1
}
}
serialized = best
serialized = serializeWithinSessionScrollbackByteLimit(pane, serialized, scrollback)
}
if (serialized.length > 0) {
buffers[leafId] = serialized
@@ -429,6 +429,136 @@ describe('registerTerminalSideEffectFactConsumer', () => {
expect(events).toEqual([])
})
it('hands off facts emitted between the parked watcher unregistering and the pane registering', () => {
// Why: the reveal window — the watcher unregisters synchronously in the
// effect flush, the pane registers only after its async reattach resolves,
// and replay is title-only, so an unbuffered bell/command-code-done is lost.
const watcher = createCallbackRecorder()
const disposeWatcher = registerTerminalSideEffectFactConsumer({
ptyId: PTY_ID,
callbacks: watcher.callbacks
})
disposeWatcher()
const events: unknown[][] = []
_dispatchTerminalSideEffectBatchForTest(
batch([{ kind: 'bell' }, { kind: 'command-code-done', prompt: 'Fix the spinner' }], {
seq: 7
})
)
// A PTY that never had a consumer stays dropped — no buffer was opened.
_dispatchTerminalSideEffectBatchForTest(batch([{ kind: 'bell' }], { ptyId: 'never-consumed' }))
expect(events).toEqual([])
expect(watcher.events).toEqual([])
const neverConsumed = createCallbackRecorder()
registerTerminalSideEffectFactConsumer({
ptyId: 'never-consumed',
callbacks: neverConsumed.callbacks
})
expect(neverConsumed.events).toEqual([])
const dispose = registerTerminalSideEffectFactConsumer({
ptyId: PTY_ID,
callbacks: {
onBell: () => events.push(['bell']),
onCommandCodeDone: (prompt) => events.push(['cc-done', prompt])
}
})
expect(events).toEqual([['bell'], ['cc-done', 'Fix the spinner']])
expect(watcher.events).toEqual([])
// Drained exactly once: a later registration gets nothing.
dispose()
const later: unknown[][] = []
registerTerminalSideEffectFactConsumer({
ptyId: PTY_ID,
callbacks: {
onBell: () => later.push(['bell']),
onCommandCodeDone: (prompt) => later.push(['cc-done', prompt])
}
})
expect(later).toEqual([])
})
it('does not buffer replay batches across a handoff', () => {
// Why: the next consumer requests its own snapshot; a held replay would
// regress the title it just restored.
const dispose = registerTerminalSideEffectFactConsumer({
ptyId: PTY_ID,
callbacks: createCallbackRecorder().callbacks
})
dispose()
_dispatchTerminalSideEffectBatchForTest(
batch([{ kind: 'title', normalizedTitle: 'stale', rawTitle: 'stale' }], {
replay: true,
seq: 5
})
)
const { callbacks, events } = createCallbackRecorder()
registerTerminalSideEffectFactConsumer({ ptyId: PTY_ID, callbacks })
expect(events).toEqual([])
})
it('drains the handoff buffer before the register snapshot, so the replay is stale', async () => {
// Why: the drained live title sets lastLiveTitleSeq, which is what makes
// the async snapshot's older title lose to the fact the pane already got.
const snapshot = batch([{ kind: 'title', normalizedTitle: 'snapshot', rawTitle: 'snapshot' }], {
replay: true,
seq: 20
})
;(globalThis as { window: unknown }).window = {
api: { pty: { getSideEffectSnapshot: vi.fn(async () => snapshot) } }
}
const dispose = registerTerminalSideEffectFactConsumer({
ptyId: PTY_ID,
callbacks: createCallbackRecorder().callbacks
})
dispose()
_dispatchTerminalSideEffectBatchForTest(
batch([{ kind: 'title', normalizedTitle: 'live', rawTitle: 'live' }], { seq: 20 })
)
const { callbacks, events } = createCallbackRecorder()
registerTerminalSideEffectFactConsumer({
ptyId: PTY_ID,
callbacks,
restoreTitleOnRegister: true
})
await Promise.resolve()
await Promise.resolve()
expect(events).toEqual([['title', 'live', 'live']])
})
it('drops a handoff-buffered batch once the buffer TTL expires', () => {
vi.useFakeTimers()
try {
const dispose = registerTerminalSideEffectFactConsumer({
ptyId: PTY_ID,
callbacks: createCallbackRecorder().callbacks
})
dispose()
_dispatchTerminalSideEffectBatchForTest(batch([{ kind: 'bell' }]))
vi.advanceTimersByTime(15_001)
const { callbacks, events } = createCallbackRecorder()
registerTerminalSideEffectFactConsumer({ ptyId: PTY_ID, callbacks })
expect(events).toEqual([])
} finally {
vi.useRealTimers()
}
})
it('subscribes to the channel once and routes IPC batches', () => {
let channelCallback: ((batch: TerminalSideEffectBatch) => void) | null = null
const onSideEffect = vi.fn((callback: (batch: TerminalSideEffectBatch) => void) => {
@@ -9,7 +9,8 @@
* callbacks), so every fact has exactly one policy consumer regardless of
* whether the tab is mounted, hidden, or parked. Facts for PTYs without a
* registered consumer are dropped — mirroring today's eager-buffer behavior
* where pre-mount output produces no attention side effects.
* where pre-mount output produces no attention side effects. The one exception
* is a PTY whose consumer just unregistered: see the handoff buffer below.
*/
import type { GlobalSettings } from '../../../../shared/types'
import type { TerminalGitHubPRLink } from '../../../../shared/terminal-github-pr-link-detector'
@@ -166,9 +167,78 @@ function applyBatchToConsumer(entry: ConsumerEntry, batch: TerminalSideEffectBat
}
}
// Why: a reveal remount unregisters the parked watcher synchronously, but the
// replacement pane registers only after its deferred rAF + async reattach
// resolves — and replay is title-only, so a bell or a command-code 'done'
// dropped in that window is lost for good. Only a PTY that just lost its
// consumer buffers (never-consumed PTYs still drop, per the module contract),
// bounded in time, batches, and PTYs so an abandoned handoff retains nothing.
const HANDOFF_FACT_BUFFER_TTL_MS = 15_000
const MAX_HANDOFF_FACT_BATCHES = 64
const MAX_HANDOFF_FACT_PTYS = 32
type HandoffFactBuffer = { batches: TerminalSideEffectBatch[]; expiresAtMs: number }
const handoffFactBuffersByPtyId = new Map<string, HandoffFactBuffer>()
function openHandoffFactBuffer(ptyId: string): void {
const nowMs = Date.now()
for (const [bufferedPtyId, buffer] of handoffFactBuffersByPtyId) {
if (buffer.expiresAtMs <= nowMs) {
handoffFactBuffersByPtyId.delete(bufferedPtyId)
}
}
if (
!handoffFactBuffersByPtyId.has(ptyId) &&
handoffFactBuffersByPtyId.size >= MAX_HANDOFF_FACT_PTYS
) {
const oldestPtyId = handoffFactBuffersByPtyId.keys().next().value
if (typeof oldestPtyId === 'string') {
handoffFactBuffersByPtyId.delete(oldestPtyId)
}
}
handoffFactBuffersByPtyId.set(ptyId, {
batches: [],
expiresAtMs: nowMs + HANDOFF_FACT_BUFFER_TTL_MS
})
}
function bufferHandoffFactBatch(batch: TerminalSideEffectBatch): void {
const buffer = handoffFactBuffersByPtyId.get(batch.ptyId)
if (!buffer) {
return
}
if (buffer.expiresAtMs <= Date.now()) {
handoffFactBuffersByPtyId.delete(batch.ptyId)
return
}
// Why: replay batches are snapshots the next consumer requests for itself.
if (batch.replay) {
return
}
if (buffer.batches.length >= MAX_HANDOFF_FACT_BATCHES) {
buffer.batches.shift()
}
buffer.batches.push(batch)
}
function drainHandoffFactBuffer(ptyId: string, entry: ConsumerEntry): void {
const buffer = handoffFactBuffersByPtyId.get(ptyId)
if (!buffer) {
return
}
handoffFactBuffersByPtyId.delete(ptyId)
if (buffer.expiresAtMs <= Date.now()) {
return
}
for (const batch of buffer.batches) {
applyBatchToConsumer(entry, batch)
}
}
function handleSideEffectBatch(batch: TerminalSideEffectBatch): void {
const entry = consumersByPtyId.get(batch.ptyId)
if (!entry) {
bufferHandoffFactBatch(batch)
return
}
applyBatchToConsumer(entry, batch)
@@ -211,6 +281,8 @@ export function registerTerminalSideEffectFactConsumer(
lastLiveTitleSeq: null
}
consumersByPtyId.set(options.ptyId, entry)
// Why before the snapshot request: draining live facts sets lastLiveTitleSeq, so the async title replay is correctly dropped as stale.
drainHandoffFactBuffer(options.ptyId, entry)
if (options.restoreTitleOnRegister) {
const getSnapshot = (globalThis as { window?: Window }).window?.api?.pty?.getSideEffectSnapshot
@@ -230,6 +302,8 @@ export function registerTerminalSideEffectFactConsumer(
return () => {
if (consumersByPtyId.get(options.ptyId) === entry) {
consumersByPtyId.delete(options.ptyId)
// Why: the pane that replaces this consumer registers only after its async reattach resolves; hold facts across that handoff.
openHandoffFactBuffer(options.ptyId)
}
}
}
@@ -242,6 +316,7 @@ export function _dispatchTerminalSideEffectBatchForTest(batch: TerminalSideEffec
/** Test seam: reset module state between tests. */
export function _resetTerminalSideEffectFactConsumersForTest(): void {
consumersByPtyId.clear()
handoffFactBuffersByPtyId.clear()
channelUnsubscribe?.()
channelUnsubscribe = null
persistedAuthorityFlagCache = undefined
@@ -0,0 +1,68 @@
import { describe, expect, it } from 'vitest'
import {
buildMainModelSnapshotReplayWrites,
hasPositiveTerminalDimensions,
resolvePositiveTerminalDimensions
} from './terminal-snapshot-replay-paint'
describe('hasPositiveTerminalDimensions', () => {
it('accepts only finite positive numeric pairs', () => {
expect(hasPositiveTerminalDimensions(80, 24)).toBe(true)
expect(hasPositiveTerminalDimensions(1, 1)).toBe(true)
})
// Why: Infinity passes `> 0` — the exact drift that let a malformed SSH
// model snapshot reach terminal.resize(Infinity, …).
it('rejects non-finite, non-positive, and non-numeric values', () => {
expect(hasPositiveTerminalDimensions(Infinity, 24)).toBe(false)
expect(hasPositiveTerminalDimensions(80, Infinity)).toBe(false)
expect(hasPositiveTerminalDimensions(Number.NaN, 24)).toBe(false)
expect(hasPositiveTerminalDimensions(0, 24)).toBe(false)
expect(hasPositiveTerminalDimensions(80, -1)).toBe(false)
expect(hasPositiveTerminalDimensions(undefined, 24)).toBe(false)
expect(hasPositiveTerminalDimensions('80', 24)).toBe(false)
expect(hasPositiveTerminalDimensions(null, null)).toBe(false)
})
})
describe('resolvePositiveTerminalDimensions', () => {
it('returns the numeric pair only when valid', () => {
expect(resolvePositiveTerminalDimensions(80, 24)).toEqual({ cols: 80, rows: 24 })
expect(resolvePositiveTerminalDimensions(Infinity, 24)).toBeNull()
expect(resolvePositiveTerminalDimensions(undefined, undefined)).toBeNull()
})
})
describe('buildMainModelSnapshotReplayWrites', () => {
it('clears normal buffer + scrollback before a normal-buffer snapshot', () => {
expect(buildMainModelSnapshotReplayWrites({ data: 'shell-output' })).toEqual([
'\x1b[2J\x1b[3J\x1b[H',
'shell-output'
])
})
// Why: main strips the ?1049h marker when splitting scrollbackAnsi from an
// alt frame, so the restorer must own the ?1049l rebuild + ?1049h return —
// painting the composed bytes after a plain clear leaves the TUI frame on
// the normal buffer.
it('rebuilds normal buffer then paints a clean alt frame for alt-screen snapshots', () => {
expect(
buildMainModelSnapshotReplayWrites({
data: 'alt-frame',
alternateScreen: true,
scrollbackAnsi: 'normal-history'
})
).toEqual([
'\x1b[?1049l\x1b[2J\x1b[3J\x1b[H',
'normal-history',
'\x1b[0m\x1b[?1049h\x1b[2J\x1b[H',
'alt-frame'
])
})
it('enters a cleared alt screen when no split scrollback is available', () => {
expect(
buildMainModelSnapshotReplayWrites({ data: 'alt-frame', alternateScreen: true })
).toEqual(['\x1b[0m\x1b[?1049h\x1b[2J\x1b[H', 'alt-frame'])
})
})
@@ -0,0 +1,62 @@
/**
* Shared guards and write choreography for painting a main-model snapshot into
* a (possibly fresh) xterm. One source for the reattach/hidden-restore paint
* paths so their dimension guards and alt-screen branches cannot drift.
*/
/** True only for finite positive numeric cols/rows — Infinity/NaN/undefined
* from a malformed snapshot must degrade to "no resize", never reach
* terminal.resize(). */
export function hasPositiveTerminalDimensions(cols: unknown, rows: unknown): boolean {
return (
typeof cols === 'number' &&
typeof rows === 'number' &&
Number.isFinite(cols) &&
Number.isFinite(rows) &&
cols > 0 &&
rows > 0
)
}
/** Narrowing form of hasPositiveTerminalDimensions for optional-typed payloads. */
export function resolvePositiveTerminalDimensions(
cols: unknown,
rows: unknown
): { cols: number; rows: number } | null {
return hasPositiveTerminalDimensions(cols, rows)
? { cols: cols as number, rows: rows as number }
: null
}
/**
* Ordered replay writes for a main-model snapshot, including the alt-screen
* choreography: main strips the `?1049h` marker when splitting scrollbackAnsi
* from an alt frame, so the restorer owns the transition — rebuild the normal
* buffer while on it, then paint the alt frame clean. Callers write these
* before their post-replay reset/escape-tail sequences.
*/
export function buildMainModelSnapshotReplayWrites(snapshot: {
data: string
alternateScreen?: boolean
scrollbackAnsi?: string
}): string[] {
if (!snapshot.alternateScreen) {
// Why: \x1b[3J wipes xterm scrollback; safe here because a normal-buffer
// snapshot carries its own history in data (mirrors pty-transport.ts).
return ['\x1b[2J\x1b[3J\x1b[H', snapshot.data]
}
if (snapshot.scrollbackAnsi !== undefined) {
// Why: main serializes normal + alt buffers separately; rebuild normal
// while active, then return to a clean alt frame.
return [
'\x1b[?1049l\x1b[2J\x1b[3J\x1b[H',
snapshot.scrollbackAnsi,
'\x1b[0m\x1b[?1049h\x1b[2J\x1b[H',
snapshot.data
]
}
// Why: the snapshot's ?1049h no-ops when already on alt screen and skips
// blank cells; clear the alt buffer so the pre-hide frame can't bleed
// through blank cells (spares normal-buffer scrollback).
return ['\x1b[0m\x1b[?1049h\x1b[2J\x1b[H', snapshot.data]
}
@@ -109,6 +109,7 @@ import { getRemoteRuntimePtyEnvironmentId } from '@/runtime/runtime-terminal-str
import { getConnectionId } from '@/lib/connection-context'
import { getExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner'
import { isPaneReplaying, type ReplayingPanesRef } from './replay-guard'
import { canReleaseReplayedScrollbackFromStore } from './replayed-scrollback-store-release'
import { fitAndFocusPanes, fitPanes } from './pane-helpers'
import { markTerminalPinnedViewport } from '@/lib/pane-manager/terminal-scroll-intent'
import { syncTerminalScrollIntentSoon } from '@/lib/pane-manager/terminal-scroll-intent-settle'
@@ -1382,12 +1383,23 @@ export function useTerminalPaneLifecycle({
replayingPanesRef,
restoredViewportBlankingPanesRef
)
if (restoredBuffers && initialLayoutRef.current.scrollbackRefsByLeafId) {
const hasScrollbackRefs = Boolean(initialLayoutRef.current.scrollbackRefsByLeafId)
if (
restoredBuffers &&
canReleaseReplayedScrollbackFromStore({
hasScrollbackRefs,
worktreeId,
repos: useAppStore.getState().repos
})
) {
const layoutWithoutRestoredBuffers = { ...initialLayoutRef.current }
delete layoutWithoutRestoredBuffers.buffersByLeafId
initialLayoutRef.current = layoutWithoutRestoredBuffers
if (hasScrollbackRefs) {
// Why refs-only: without a disk ref this mount is the sole replay source, so a re-run (StrictMode) still needs the bytes.
initialLayoutRef.current = layoutWithoutRestoredBuffers
}
if (initialLayoutHadBuffers) {
// Why: raw replay bytes belong to this mount only; drop legacy hydrated copies from Zustand so session writes stay ref-only.
// Why: xterm owns the replayed bytes now; leaving the park-time copy in Zustand retains up to 512KB/leaf for the app's lifetime.
useAppStore.getState().setTabLayout(tabId, layoutWithoutRestoredBuffers)
}
}
@@ -0,0 +1,214 @@
// @vitest-environment happy-dom
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { TerminalTab } from '../../../../shared/types'
const mocks = vi.hoisted(() => ({
storeState: {
pendingStartupByTabId: {} as Record<string, unknown>,
settings: {} as Record<string, unknown>,
terminalLayoutsByTabId: {} as Record<string, { ptyIdsByLeafId?: Record<string, string> }>
},
exemptTabIds: new Set<string>(),
exemptSelectCalls: 0
}))
vi.mock('../../store', () => ({
useAppStore: (selector: (state: unknown) => unknown) => selector(mocks.storeState)
}))
vi.mock('./terminal-eviction-exempt-tabs', () => ({
selectEvictionExemptTerminalTabIds: (_worktreeId: string, tabs: readonly { id: string }[]) => {
mocks.exemptSelectCalls += 1
return new Set(tabs.filter((tab) => mocks.exemptTabIds.has(tab.id)).map((tab) => tab.id))
},
selectEvictionExemptTerminalTabLayoutKey: (
state: typeof mocks.storeState,
tabs: readonly { id: string }[]
) =>
tabs
.map(
(tab) => `${tab.id}=${JSON.stringify(state.terminalLayoutsByTabId[tab.id]?.ptyIdsByLeafId)}`
)
.join('|')
}))
vi.mock('./terminal-parked-tab-watchers', () => ({
canWatcherCoverParkedTerminalTab: () => true,
disposeParkedTerminalWatchersForWorktree: vi.fn(),
syncParkedTerminalTabWatchers: vi.fn()
}))
import {
TERMINAL_TAB_COLD_PARK_DELAY_MS,
TERMINAL_TAB_HOT_RETAIN_MS
} from './terminal-hidden-view-parking'
import { useTerminalTabColdParking } from './use-terminal-tab-cold-parking'
const WORKTREE_ID = 'wt-1'
function terminalTab(id: string): TerminalTab {
return { id, ptyId: `${WORKTREE_ID}@@session-${id}` } as TerminalTab
}
function hookArgs(shouldMeasureHiddenWorktree: boolean) {
return {
worktreeId: WORKTREE_ID,
terminalTabs: [terminalTab('tab-1'), terminalTab('tab-2')],
assignments: new Map<string, { groupId: string; isActiveInGroup: boolean }>(),
isWorktreeActive: false,
coldParkTerminalPanes: false,
shouldMeasureHiddenWorktree,
activityTerminalPortals: [],
activationDeferredMountTabIds: null
}
}
describe('useTerminalTabColdParking measure-clock contract', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(1_000_000)
})
afterEach(() => {
vi.useRealTimers()
mocks.exemptTabIds = new Set()
mocks.exemptSelectCalls = 0
mocks.storeState.terminalLayoutsByTabId = {}
})
// Why: the worktree layer preserves hiddenSince through a background-measure
// window; the tab layer must share that contract (no clock reset) while a
// post-measure cool-down prevents the instant re-park thrash.
it('preserves tab hiddenSince through a measure window and re-parks only after the cool-down', () => {
const { result, rerender } = renderHook(
(args: ReturnType<typeof hookArgs>) => useTerminalTabColdParking(args),
{ initialProps: hookArgs(false) }
)
expect(result.current.parkedTerminalTabIds.size).toBe(0)
// Past hot-retain: tab-1 holds the last-active exemption, tab-2 parks.
act(() => {
vi.advanceTimersByTime(TERMINAL_TAB_HOT_RETAIN_MS + 1)
})
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2']))
// A measure window reveals every tab but must not clear the hidden clock.
act(() => {
rerender(hookArgs(true))
})
expect(result.current.parkedTerminalTabIds.size).toBe(0)
act(() => {
vi.advanceTimersByTime(3_000)
rerender(hookArgs(false))
})
// Measure just ended: the cool-down vetoes an instant re-park (the thrash).
expect(result.current.parkedTerminalTabIds.size).toBe(0)
act(() => {
vi.advanceTimersByTime(TERMINAL_TAB_COLD_PARK_DELAY_MS - 1)
})
expect(result.current.parkedTerminalTabIds.size).toBe(0)
// One cool-down later tab-2 re-parks — proving hiddenSince survived the
// measure (a cleared clock would demand a fresh 15-minute hot-retain).
act(() => {
vi.advanceTimersByTime(2)
})
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2']))
})
// Why: a measure window also ends when the user opens the worktree; the
// hysteresis is then owed to nobody, so still-hidden background tabs must not
// sit out a cool-down (Terminal.tsx clears the worktree clock the same way).
it('clears the post-measure cool-down when the worktree becomes visible', () => {
const { result, rerender } = renderHook(
(args: ReturnType<typeof hookArgs>) => useTerminalTabColdParking(args),
{ initialProps: hookArgs(false) }
)
act(() => {
vi.advanceTimersByTime(TERMINAL_TAB_HOT_RETAIN_MS + 1)
})
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2']))
act(() => {
rerender(hookArgs(true))
})
expect(result.current.parkedTerminalTabIds.size).toBe(0)
// Measure ends because the worktree went visible: tab-2 is still hidden
// (no active group assignment) and re-parks on this very pass.
act(() => {
vi.advanceTimersByTime(3_000)
rerender({ ...hookArgs(false), isWorktreeActive: true })
})
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2']))
})
// Why: force-park is the only park that can contain unrestorable ptys, so its
// exempt tabs keep their panes — a remount would orphan a live shell.
it('keeps eviction-exempt tabs mounted when the worktree is force-parked', () => {
mocks.exemptTabIds = new Set(['tab-1'])
const { result, rerender } = renderHook(
(args: ReturnType<typeof hookArgs> & { isForceParked: boolean }) =>
useTerminalTabColdParking(args),
{ initialProps: { ...hookArgs(false), coldParkTerminalPanes: true, isForceParked: true } }
)
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2']))
// The carve-out is scoped to force-parks: an ordinary worktree park has no
// exempt tabs to protect, so it evicts both.
act(() => {
rerender({ ...hookArgs(false), coldParkTerminalPanes: true, isForceParked: false })
})
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-1', 'tab-2']))
})
// Why: a split lands in the layout store, not in terminalTabs — a memo keyed
// on the tabs alone would keep serving a set that misses the new pane and
// unmount the live shell it should have exempted.
it('re-resolves exemptions when only the layout PTYs change', () => {
const stableArgs = { ...hookArgs(false), coldParkTerminalPanes: true, isForceParked: true }
const { result, rerender } = renderHook(
(args: typeof stableArgs) => useTerminalTabColdParking(args),
{ initialProps: stableArgs }
)
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-1', 'tab-2']))
// Same tabs, same verdict: nothing the memo can see has moved yet.
mocks.exemptTabIds = new Set(['tab-1'])
act(() => {
rerender(stableArgs)
})
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-1', 'tab-2']))
// The split's leaf pty lands in the layout store and re-keys the memo.
mocks.storeState.terminalLayoutsByTabId = {
'tab-1': { ptyIdsByLeafId: { 'leaf-2': 'pty-local-detached' } }
}
act(() => {
rerender(stableArgs)
})
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2']))
})
// Why: resolving an exemption re-reads the store and walks the layout tree per
// tab, so an unrelated re-render must not repeat that work.
it('resolves eviction exemptions once per force-park input change', () => {
mocks.exemptTabIds = new Set(['tab-1'])
const stableArgs = { ...hookArgs(false), coldParkTerminalPanes: true, isForceParked: true }
const { result, rerender } = renderHook(
(args: typeof stableArgs) => useTerminalTabColdParking(args),
{ initialProps: stableArgs }
)
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2']))
const callsAfterFirstRender = mocks.exemptSelectCalls
act(() => {
rerender({ ...stableArgs, isWorktreeActive: false })
})
expect(mocks.exemptSelectCalls).toBe(callsAfterFirstRender)
expect(result.current.parkedTerminalTabIds).toEqual(new Set(['tab-2']))
})
})
@@ -13,8 +13,9 @@ import {
findActivityTerminalPortal,
type ActivityTerminalPortalTarget
} from '../activity/activity-terminal-portal'
import { getTerminalTabColdParkRecheckDelayMs } from './terminal-cold-park-recheck-deadlines'
import {
getTerminalTabColdParkRecheckDelayMs,
TERMINAL_TAB_COLD_PARK_DELAY_MS,
selectColdParkedTerminalTabs,
type TerminalTabColdParkCandidate
} from './terminal-hidden-view-parking'
@@ -23,6 +24,10 @@ import {
type ParkVerdictFlipRecord
} from './terminal-park-verdict-flip-telemetry'
import { getTerminalParkingPolicyOverrides } from './terminal-parking-e2e-overrides'
import {
selectEvictionExemptTerminalTabIds,
selectEvictionExemptTerminalTabLayoutKey
} from './terminal-eviction-exempt-tabs'
import {
canWatcherCoverParkedTerminalTab,
disposeParkedTerminalWatchersForWorktree,
@@ -34,6 +39,8 @@ type TerminalOverlayTabAssignment = {
isActiveInGroup: boolean
}
const EMPTY_TAB_IDS: ReadonlySet<string> = new Set()
function haveSameTerminalTabIds(left: ReadonlySet<string>, right: ReadonlySet<string>): boolean {
if (left.size !== right.size) {
return false
@@ -53,6 +60,10 @@ export function useTerminalTabColdParking(args: {
isWorktreeActive: boolean
/** Worktree-level park verdict from Terminal.tsx. */
coldParkTerminalPanes: boolean
/** Retention-budget force-park (C1 slice B): unlike ordinary parks, the
* worktree may hold eviction-exempt tabs, whose panes must stay mounted —
* a remount would orphan their live pty (same carve-out as portals). */
isForceParked?: boolean
/** Hidden-measuring startup probe from Terminal.tsx — the panes must stay
* mounted for their first xterm fit, mirroring the worktree-level guard. */
shouldMeasureHiddenWorktree: boolean
@@ -70,6 +81,7 @@ export function useTerminalTabColdParking(args: {
assignments,
isWorktreeActive,
coldParkTerminalPanes,
isForceParked = false,
shouldMeasureHiddenWorktree,
activityTerminalPortals,
activationDeferredMountTabIds
@@ -78,7 +90,16 @@ export function useTerminalTabColdParking(args: {
const terminalParkingEnabled = useAppStore(
(state) => state.settings?.terminalHiddenViewParking !== false
)
const terminalSshParkingEnabled = useAppStore(
(state) => state.settings?.terminalSshViewParking !== false
)
const terminalTabHiddenSinceRef = useRef(new Map<string, number>())
// Why (shared measure-clock contract with Terminal.tsx): tab hiddenSince
// survives a background-measure window so per-tab park deadlines stay in
// sync with the worktree retention/TTL clock, and a post-measure cool-down
// re-grants the hysteresis so measure end can't immediately re-park.
const wasMeasuringHiddenWorktreeRef = useRef(false)
const measureParkCooldownUntilRef = useRef<number | null>(null)
const terminalTabParkingTimersRef = useRef(new Map<string, number>())
const parkVerdictRecordsRef = useRef(new Map<string, ParkVerdictFlipRecord>())
const [terminalTabParkingRevision, setTerminalTabParkingRevision] = useState(0)
@@ -120,15 +141,38 @@ export function useTerminalTabColdParking(args: {
}
}
// Why: measure end starts the re-park cool-down (worktree measure-clock
// contract) — hiddenSince is preserved through the window, so without the
// cool-down every past-deadline tab would re-park the instant it closes.
if (shouldMeasureHiddenWorktree) {
wasMeasuringHiddenWorktreeRef.current = true
} else {
if (wasMeasuringHiddenWorktreeRef.current) {
measureParkCooldownUntilRef.current =
nowMs + (overrides.coldParkDelayMs ?? TERMINAL_TAB_COLD_PARK_DELAY_MS)
}
wasMeasuringHiddenWorktreeRef.current = false
}
// Why: mirrors Terminal.tsx's worktree clock — a visible worktree ends the
// measure episode outright, so no re-park cool-down is owed.
if (isWorktreeActive) {
measureParkCooldownUntilRef.current = null
}
const candidates: TerminalTabColdParkCandidate[] = terminalTabs.map((terminalTab) => {
const assignment = assignments.get(terminalTab.id)
const isVisible = Boolean(isWorktreeActive && assignment && assignment.isActiveInGroup)
const hasActivityTerminalPortal = portalTabIds.has(terminalTab.id)
// Why: hidden-measuring counts as visibility — the startup probe needs
// mounted panes, so the hidden clock must not run during it.
if (isVisible || hasActivityTerminalPortal || shouldMeasureHiddenWorktree) {
// Why measuring preserves the clock: the startup probe still needs
// mounted panes (selection + render veto below), but deleting
// hiddenSince would restart the hysteresis AND desync per-tab deadlines
// from the worktree retention/TTL clock on every ~3s probe.
if (isVisible || hasActivityTerminalPortal) {
terminalTabHiddenSinceRef.current.delete(terminalTab.id)
} else if (!terminalTabHiddenSinceRef.current.has(terminalTab.id)) {
} else if (
!shouldMeasureHiddenWorktree &&
!terminalTabHiddenSinceRef.current.has(terminalTab.id)
) {
terminalTabHiddenSinceRef.current.set(terminalTab.id, nowMs)
}
return {
@@ -147,6 +191,8 @@ export function useTerminalTabColdParking(args: {
pendingStartupByTabId,
parkingEnabled: terminalParkingEnabled,
nowMs,
parkCooldownUntilMs: measureParkCooldownUntilRef.current,
restorePolicy: { sshParkingEnabled: terminalSshParkingEnabled },
...overrides
})
// Why: a tab the byte watchers cannot cover (no capture, no layout
@@ -177,6 +223,7 @@ export function useTerminalTabColdParking(args: {
const delayMs = getTerminalTabColdParkRecheckDelayMs({
parkingEnabled: terminalParkingEnabled,
hiddenSinceMs: candidate.hiddenSinceMs,
parkCooldownUntilMs: measureParkCooldownUntilRef.current,
nowMs,
...overrides
})
@@ -196,11 +243,29 @@ export function useTerminalTabColdParking(args: {
pendingStartupByTabId,
shouldMeasureHiddenWorktree,
terminalParkingEnabled,
terminalSshParkingEnabled,
terminalTabParkingRevision,
terminalTabs,
worktreeId
])
// Why subscribed: the exemption also reads layout leaf PTYs, which change
// without a terminalTabs change (split added, pty re-minted); gated on
// isForceParked so only force-parked worktrees build the key per store change.
const evictionExemptLayoutKey = useAppStore((state) =>
isForceParked ? selectEvictionExemptTerminalTabLayoutKey(state, terminalTabs) : ''
)
// Why memoized: resolving an exemption re-reads the store and walks the
// layout tree per tab, so recompute only when the force-park verdict, the
// tabs, or their layout PTYs change — not on every assignment/park-set change
// below.
const evictionExemptTerminalTabIds = useMemo(
() =>
isForceParked ? selectEvictionExemptTerminalTabIds(worktreeId, terminalTabs) : EMPTY_TAB_IDS,
// eslint-disable-next-line react-hooks/exhaustive-deps -- the layout key encodes the store fields the selector re-reads internally.
[evictionExemptLayoutKey, isForceParked, terminalTabs, worktreeId]
)
// Why: the rendered park verdict — worktree-level park (prop from
// Terminal.tsx) or per-tab cold park, never portal-hosted tabs. Render and
// the watcher-sync effect must share this exact set so watcher lifecycle
@@ -218,6 +283,11 @@ export function useTerminalTabColdParking(args: {
if (
(coldParkTerminalPanes || (!isVisible && coldParkedTerminalTabIds.has(terminalTab.id))) &&
!hasActivityTerminalPortal &&
// Why: a force-parked worktree's eviction-exempt tabs keep their
// mounted panes — a remount would orphan their live pty. Scoped to
// force-parks: ordinary parks never contain exempt tabs (eligibility
// requires every tab restorable, so the memo is empty for them).
!evictionExemptTerminalTabIds.has(terminalTab.id) &&
// Why: the hidden-measuring startup probe needs mounted panes; gate
// here too so the reveal lands in the same render that starts it.
!shouldMeasureHiddenWorktree
@@ -242,6 +312,7 @@ export function useTerminalTabColdParking(args: {
coldParkTerminalPanes,
coldParkedTerminalTabIds,
activationDeferredMountTabIds,
evictionExemptTerminalTabIds,
isWorktreeActive,
shouldMeasureHiddenWorktree,
terminalTabs,
+7 -2
View File
@@ -211,11 +211,16 @@ function isIdlePromptText(context: StatusScanContext): boolean {
export function createCommandCodeOutputStatusDetector(args: {
startupCommand?: string | null
/** Continuity seed for a detector created long after launch (parked watchers):
* the banner is off-screen by then, so a turn known to be in flight both arms
* the scrape and carries its prompt into the idle-composer done check. */
inFlightTurn?: { prompt: string } | null
onWorking: (prompt: string) => void
onDone?: (prompt: string) => void
}): CommandCodeOutputStatusDetector {
let hasSeenCommandCodeUi = isCommandCodeLaunchCommand(args.startupCommand)
let lastSubmittedPrompt = ''
let hasSeenCommandCodeUi =
isCommandCodeLaunchCommand(args.startupCommand) || Boolean(args.inFlightTurn)
let lastSubmittedPrompt = args.inFlightTurn?.prompt ?? ''
let recentRawText = ''
return {
+4
View File
@@ -300,6 +300,10 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
activeClaudeManagedAccountId: null,
terminalScopeHistoryByWorktree: true,
terminalHiddenViewParking: true,
// C1 kill switches — runtime reads stay `!== false` so older persisted
// settings objects (which omit them) keep the default-on behavior.
terminalSshViewParking: true,
terminalHiddenWorktreeRetentionBudget: true,
terminalMainSideEffectAuthority: true,
terminalHiddenDeliveryGate: true,
terminalModelQueryAuthority: true,
+13 -1
View File
@@ -6,6 +6,9 @@ export type E2EConfig = {
/** Test-only override (ORCA_E2E_TERMINAL_PARKING_DELAY_MS) shrinking the
* terminal hidden-view parking delays. null means use production timing. */
terminalParkingDelayMs: number | null
/** Test-only override (ORCA_E2E_TERMINAL_RETENTION_LIMIT) shrinking the
* hidden un-parkable worktree force-park budget. null means production (12). */
terminalRetentionLimit: number | null
}
type E2EConfigInput = {
@@ -13,6 +16,7 @@ type E2EConfigInput = {
exposeStore?: boolean
userDataDir?: string | null
terminalParkingDelayMs?: number | null
terminalRetentionLimit?: number | null
}
export function createE2EConfig(input: E2EConfigInput): E2EConfig {
@@ -25,12 +29,20 @@ export function createE2EConfig(input: E2EConfigInput): E2EConfig {
input.terminalParkingDelayMs > 0
? input.terminalParkingDelayMs
: null
// Why: a worktree count — only a positive integer is a meaningful budget.
const terminalRetentionLimit =
typeof input.terminalRetentionLimit === 'number' &&
Number.isInteger(input.terminalRetentionLimit) &&
input.terminalRetentionLimit > 0
? input.terminalRetentionLimit
: null
return {
enabled: headless || exposeStore || userDataDir !== null,
headless,
exposeStore,
userDataDir,
terminalParkingDelayMs
terminalParkingDelayMs,
terminalRetentionLimit
}
}
+4
View File
@@ -2855,6 +2855,10 @@ export type GlobalSettings = {
terminalScopeHistoryByWorktree: boolean
/** Kill switch for hidden terminal view parking: unmount long-hidden panes while a pane-less watcher keeps PTY side effects alive. */
terminalHiddenViewParking?: boolean
/** Kill switch for SSH terminal parking (C1): SSH panes park like local ones; reveal restores from main's headless model, falling back to relay replay. */
terminalSshViewParking?: boolean
/** Kill switch for the hidden-worktree retention budget (C1): force-parks the least-recently-hidden un-parkable worktrees beyond a count budget or TTL. */
terminalHiddenWorktreeRetentionBudget?: boolean
/** Kill switch for main-process PTY side-effect authority; on (default) = title/bell/agent facts via pty:sideEffect channel, not renderer byte parsing. */
terminalMainSideEffectAuthority?: boolean
/** Kill switch for main's hidden-delivery gate (Phase 4): drops PTY bytes to hidden views after model ingestion; requires terminalMainSideEffectAuthority. */
@@ -0,0 +1,67 @@
import type { Page } from '@stablyai/playwright-test'
import { expect } from '@stablyai/playwright-test'
// Why: the retention-budget spec needs several worktrees of ONE connected remote
// repo (adding a second repo mid-session misroutes its pty spawn to the local
// daemon — pre-existing multi-repo issue). Creation goes through the product's
// own createWorktree path so the result lands in worktreesByRepo (an external
// `git worktree add` only shows up as a detected worktree needing adoption).
// The create is polled: the relay channel can drop and reconnect shortly after
// connect, and an RPC inside that window fails with "Multiplexer disposed".
export async function createAndActivateDockerSshRelayWorktree(
page: Page,
repoId: string,
worktreeName: string
): Promise<{ worktreeId: string }> {
let worktreeId: string | null = null
await expect
.poll(
async () => {
worktreeId = await page.evaluate(
async ({ repoId, worktreeName }) => {
const store = window.__store
if (!store) {
throw new Error('Store unavailable')
}
// Why: a retried create must reuse a prior attempt's worktree
// instead of failing forever on "already exists".
const existing = (store.getState().worktreesByRepo[repoId] ?? []).find((candidate) =>
candidate.path.endsWith(`/${worktreeName}`)
)
if (existing) {
return existing.id
}
try {
const result = await store.getState().createWorktree(repoId, worktreeName)
await store.getState().fetchWorktrees(repoId)
return result.worktree.id
} catch {
return null
}
},
{ repoId, worktreeName }
)
return worktreeId
},
{
timeout: 90_000,
message: `remote worktree ${worktreeName} was not created in repo ${repoId}`
}
)
.not.toBeNull()
if (!worktreeId) {
throw new Error(`remote worktree ${worktreeName} did not resolve an id`)
}
await page.evaluate((id) => {
const store = window.__store
if (!store) {
throw new Error('Store unavailable')
}
store.getState().setActiveWorktree(id)
if ((store.getState().tabsByWorktree[id] ?? []).length === 0) {
store.getState().createTab(id)
}
store.getState().setActiveTabType('terminal')
}, worktreeId)
return { worktreeId }
}
+8 -5
View File
@@ -49,17 +49,20 @@ async function createActiveTerminalTab(page: Page, worktreeId: string): Promise<
return tabId
}
// Why: #8262 exempts the single most-recently-hidden tab from cold-park to keep
// the just-left view instantly warm, so a lone hidden tab never parks. Opening
// one more tab hides the current view (which then holds that exemption) and
// leaves the older `targetTabId` free to cold-park. Returns waitForTabParked's
// elapsed-ms so callers keep their parking annotations.
// Why: #8262 exempts the single most-recently-hidden tab from cold-park. An
// active target therefore needs two decoys (hide it, then move the exemption);
// an already-hidden target needs one. Returns waitForTabParked's elapsed time.
export async function parkHiddenTabBehindDecoy(
page: Page,
worktreeId: string,
targetTabId: string,
options?: { parkDelayMs?: number }
): Promise<number> {
// An active target needs one decoy to become old and another to take the
// last-active exemption; already-hidden targets need only the latter.
if ((await getActiveTabId(page)) === targetTabId) {
await createActiveTerminalTab(page, worktreeId)
}
await createActiveTerminalTab(page, worktreeId)
return waitForTabParked(page, targetTabId, options)
}
+115
View File
@@ -0,0 +1,115 @@
import type { TestInfo } from '@stablyai/playwright-test'
import { test, expect } from './helpers/orca-app'
import { waitForActiveWorktree, waitForSessionReady, getActiveTabId } from './helpers/store'
import {
getTerminalContent,
sendToTerminal,
waitForActivePanePtyId,
waitForActiveTerminalManager,
waitForPaneIdentitySnapshot
} from './helpers/terminal'
import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking'
import {
cleanupDockerSshRelayTarget,
startDockerSshRelayTarget,
type DockerSshRelayTarget
} from './helpers/docker-ssh-relay-target'
import { connectDockerSshRelayTarget } from './helpers/docker-ssh-relay-connection'
const RUN_DOCKER_SSH = process.env.ORCA_E2E_SSH_DOCKER === '1'
const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500
test.use({
seedTestRepo: false,
orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) }
})
// C1 slice A: SSH tabs park like local ones and reveal restores content from
// main's headless model (relay replay is the fallback). This is the SSH
// park+reveal round-trip fidelity check the design gate required.
test.describe('SSH terminal hidden view parking', () => {
test.skip(!RUN_DOCKER_SSH, 'Set ORCA_E2E_SSH_DOCKER=1 to run Docker-backed SSH tests.')
test.skip(process.platform === 'win32', 'Docker SSH parking uses POSIX SSH tooling.')
test('parks a hidden SSH tab and restores its scrollback on reveal', async ({
orcaPage
}, testInfo: TestInfo) => {
test.setTimeout(240_000)
let target: DockerSshRelayTarget | null = null
try {
target = startDockerSshRelayTarget(testInfo)
await waitForSessionReady(orcaPage)
const remote = await connectDockerSshRelayTarget(orcaPage, target)
await expect
.poll(() => waitForActiveWorktree(orcaPage), { timeout: 30_000 })
.toBe(remote.worktreeId)
await waitForActiveTerminalManager(orcaPage, 60_000)
const sshPtyId = await waitForActivePanePtyId(orcaPage, 60_000)
const sshTabId = await getActiveTabId(orcaPage)
if (!sshTabId) {
throw new Error('SSH terminal tab did not become active')
}
const snapshot = await waitForPaneIdentitySnapshot(orcaPage, 1)
expect(snapshot.panes[0]?.ptyId).toBe(sshPtyId)
// Why the ':' terminator: `${marker}_1:` must not substring-match _10/_100.
const marker = `SSH_PARK_MARKER_${Date.now()}`
await sendToTerminal(
orcaPage,
sshPtyId,
`for i in $(seq 1 200); do echo "${marker}_$i:"; done\r`
)
await expect
.poll(() => getTerminalContent(orcaPage, 20_000), {
timeout: 30_000,
message: 'SSH marker output did not render before parking'
})
.toContain(`${marker}_200:`)
// Why the pad: ~3000 × ~60B ≈ 180KB pushes the early markers past the
// relay's 100KiB rolling replay buffer while staying inside main's
// ~5k-row headless model — so a revealed `${marker}_1:` can only have
// come from the model paint, never the relay fallback.
await sendToTerminal(
orcaPage,
sshPtyId,
`for i in $(seq 1 3000); do echo "PAD_$i:0123456789012345678901234567890123456789"; done; echo "${marker}_PAD_DONE:"\r`
)
await expect
.poll(() => getTerminalContent(orcaPage, 20_000), {
timeout: 60_000,
message: 'SSH pad output did not finish before parking'
})
.toContain(`${marker}_PAD_DONE:`)
await parkHiddenTabBehindDecoy(orcaPage, remote.worktreeId, sshTabId, {
parkDelayMs: PARKING_DELAY_MS
})
// Reveal: reattach must paint from main's headless model (or relay
// replay when the model is unavailable) — never a blank pane.
await orcaPage.evaluate((tabId) => {
const state = window.__store?.getState()
state?.setActiveTab(tabId)
state?.setActiveTabType('terminal')
}, sshTabId)
await waitForActiveTerminalManager(orcaPage, 60_000)
await expect
.poll(() => getTerminalContent(orcaPage, 20_000), {
timeout: 60_000,
message: 'revealed SSH tab did not restore the final pad line'
})
.toContain(`${marker}_PAD_DONE:`)
// Depth proof: `${marker}_1:` predates >100KiB of later output, so its
// presence after reveal proves the headless-model paint restored
// scrollback the relay replay cannot hold.
await expect
.poll(() => getTerminalContent(orcaPage, 2_000_000), {
timeout: 15_000,
message: 'revealed SSH tab lost the pre-pad scrollback only the model paint restores'
})
.toContain(`${marker}_1:`)
} finally {
cleanupDockerSshRelayTarget(target)
}
})
})
+411 -2
View File
@@ -6,6 +6,8 @@ import { test, expect } from './helpers/orca-app'
import {
ensureTerminalVisible,
getActiveTabId,
getAllWorktreeIds,
switchToWorktree,
waitForActiveWorktree,
waitForSessionReady
} from './helpers/store'
@@ -49,13 +51,17 @@ const PARKED_MEMORY_TEST_TIMEOUT_MS = 300_000
// Why: mixed-width content (ASCII, CJK wide cells, emoji, box drawing) makes
// each xterm hold realistic narrow+wide buffer rows, so released parked-tab
// memory reflects real agent output rather than uniform filler.
function writeScrollbackFillScript(scriptPath: string, runId: string): void {
function writeScrollbackFillScript(
scriptPath: string,
runId: string,
lineCount: number = SCROLLBACK_LINE_COUNT
): void {
const script = [
`const tabIndex = process.argv[2] ?? '0'`,
`const wide = '統合端末記憶計測'`,
`const emoji = ['🟢', '🟡', '🔵', '🟣']`,
`const lines = []`,
`for (let i = 0; i < ${SCROLLBACK_LINE_COUNT}; i += 1) {`,
`for (let i = 0; i < ${lineCount}; i += 1) {`,
` const ascii = ('tab ' + tabIndex + ' line ' + String(i).padStart(4, '0') + ' ').padEnd(48, 'abcdefghijklmnopqrstuvwxyz')`,
` const box = '│' + '─'.repeat(8 + (i % 24)) + '│'`,
` lines.push(ascii + ' ' + wide.repeat(1 + (i % 3)) + ' ' + emoji[i % 4] + ' ' + box)`,
@@ -369,3 +375,406 @@ test.describe('Terminal parked memory', () => {
}
})
})
// ─────────────────────── C1 retention budget outcome ───────────────────────
// The tests above assert the parking MECHANISM. This one asserts the OUTCOME
// the retention budget exists for: hidden worktrees ordinary parking can never
// evict actually release their buffers once the budget engages, with the
// budget flip as the only change between the two samples.
//
// Honest caveats:
// - The un-parkable class is staged by rewriting tabsByWorktree[*].ptyId to a
// remote-runtime-shaped id. That is a fidelity proxy: park-restorability and
// eviction-exemption are decided from that field alone, but the transports
// underneath stay real LOCAL PTYs — this is not a live remote runtime.
// - The primary gate is retained xterm buffer CELLS (deterministic), not RSS.
// xterm rows are typed arrays outside the V8 heap, so usedJSHeapSize misses
// most of what is released; renderer RSS is recorded and only gated as
// non-growth because it moves with GC timing and compositor allocations.
const RETENTION_TAB_COUNT = 4
const RETENTION_FILL_LINE_COUNT = 12_000
const RETENTION_SCROLLBACK_ROWS = 25_000
// Why 12: xterm packs each cell as 3 uint32s in the BufferLine typed array.
const XTERM_BYTES_PER_CELL = 12
// Why 40: this staging measures ~87 MB of retained buffer, so half of that is a
// floor that fails loudly if the fill silently stops producing scrollback.
const MIN_STAGED_BUFFER_MB = 40
// Why 2s: force-park is a synchronous verdict re-run on the setting flip and
// measured 23-25ms locally; anything near a timer/TTL wait blows this budget.
const MAX_FORCE_PARK_EVICTION_MS = 2_000
// Why 0.05: only the exempt decoy's unfilled pane may survive (~0.1% of the
// baseline). One retained filled pane would be ~25%, so this fails on a partial
// eviction instead of passing it.
const MAX_RETAINED_CELL_FRACTION = 0.05
// Why a band, not zero: RSS is sampled and moved only -0.7 to -3.0 MB on a
// ~453 MB baseline across runs, so "must not grow" would flake on noise. 5 MB
// still fails loudly if an eviction starts planting 512KB/pane capture strings.
const RENDERER_RSS_NOISE_MB = 5
const RETENTION_TEST_TIMEOUT_MS = 420_000
const UNPARKABLE_PTY_PREFIX = 'remote:e2e-retention-'
type RetainedBufferSample = {
cells: number
rows: number
panes: number
}
// Why walk the buffers instead of trusting a heap delta: xterm rows live in
// typed arrays outside the V8 heap, so retained cells are the only
// deterministic measure of what a force-park actually released.
async function readRetainedTerminalBufferCells(page: Page): Promise<RetainedBufferSample> {
return page.evaluate(() => {
let cells = 0
let rows = 0
let panes = 0
for (const manager of window.__paneManagers?.values() ?? []) {
for (const pane of manager.getPanes?.() ?? []) {
const buffer = pane.terminal?.buffer?.active
if (!buffer) {
continue
}
panes += 1
rows += buffer.length
cells += buffer.length * pane.terminal.cols
}
}
return { cells, rows, panes }
})
}
// Why host-side RSS: the renderer process' resident set is the figure the C1
// crash reports are measured in, and performance.memory cannot see it.
async function readRendererResidentMb(page: Page): Promise<number | null> {
return page.evaluate(async () => {
const snapshot = await window.api?.memory?.getSnapshot?.()
const bytes = snapshot?.app?.renderer?.memory
return typeof bytes === 'number' && bytes > 0 ? bytes / (1024 * 1024) : null
})
}
type RetentionMemorySample = {
buffers: RetainedBufferSample
bufferMb: number
heapUsedMb: number
rendererMb: number | null
livePaneManagers: number
}
async function readRetentionMemorySample(page: Page): Promise<RetentionMemorySample> {
const metrics = await sampleParkedMemoryMetrics(page)
const buffers = await readRetainedTerminalBufferCells(page)
return {
buffers,
bufferMb: (buffers.cells * XTERM_BYTES_PER_CELL) / (1024 * 1024),
heapUsedMb: metrics.heapUsedMB,
rendererMb: await readRendererResidentMb(page),
livePaneManagers: metrics.livePaneManagers
}
}
function formatRetentionSample(label: string, sample: RetentionMemorySample): string {
return [
`${label}.cells=${sample.buffers.cells}`,
`${label}.rows=${sample.buffers.rows}`,
`${label}.panes=${sample.buffers.panes}`,
`${label}.bufferMB=${sample.bufferMb.toFixed(1)}`,
`${label}.heapMB=${sample.heapUsedMb.toFixed(1)}`,
`${label}.rendererRssMB=${sample.rendererMb === null ? 'n/a' : sample.rendererMb.toFixed(1)}`,
`${label}.paneManagers=${sample.livePaneManagers}`
].join(' ')
}
// Why rewrite only tab.ptyId: canPark* eligibility is decided from it, so a
// remote-runtime-shaped id makes the worktree un-parkable. Layout leaf maps
// stay on real local transports so live panes keep their bindings; watcher
// coverage may still read those locals, but eligibility already fails.
async function stageUnparkableWorktreeTabs(page: Page, worktreeId: string): Promise<number> {
return page.evaluate(
({ worktreeId, prefix }) => {
const store = window.__store
if (!store) {
throw new Error('stageUnparkableWorktreeTabs: window.__store is unavailable')
}
const state = store.getState()
const tabs = state.tabsByWorktree[worktreeId] ?? []
if (tabs.length === 0) {
throw new Error(`stageUnparkableWorktreeTabs: ${worktreeId} has no terminal tabs`)
}
const staged = tabs.map((tab) =>
typeof tab.ptyId === 'string' && tab.ptyId.startsWith(prefix)
? tab
: { ...tab, ptyId: `${prefix}${tab.id}` }
)
;(store as unknown as { setState: (partial: unknown) => void }).setState({
tabsByWorktree: { ...state.tabsByWorktree, [worktreeId]: staged }
})
return staged.length
},
{ worktreeId, prefix: UNPARKABLE_PTY_PREFIX }
)
}
// Why: bind/reconcile can rewrite tab.ptyId after staging. Poll so ordinary
// parking cannot regain park-restorable eligibility mid control-arm wait.
async function waitForUnparkableWorktreeTabs(page: Page, worktreeId: string): Promise<void> {
await expect
.poll(
() =>
page.evaluate(
({ worktreeId, prefix }) => {
const tabs = window.__store?.getState().tabsByWorktree[worktreeId] ?? []
return (
tabs.length > 0 &&
tabs.every((tab) => typeof tab.ptyId === 'string' && tab.ptyId.startsWith(prefix))
)
},
{ worktreeId, prefix: UNPARKABLE_PTY_PREFIX }
),
{
timeout: 5_000,
message: `worktree ${worktreeId} did not keep un-parkable remote: pty ids after staging`
}
)
.toBe(true)
}
// Why not getTerminalContent: it serializes the whole scrollback, which is
// megabytes of string per poll tick at RETENTION_SCROLLBACK_ROWS. The fill
// marker is the last line written, so scanning the buffer tail is enough.
async function waitForFillMarkerInTab(page: Page, tabId: string, marker: string): Promise<void> {
await expect
.poll(
() =>
page.evaluate(
({ tabId, marker }) => {
const manager = window.__paneManagers?.get(tabId)
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
const buffer = pane?.terminal?.buffer?.active
if (!buffer) {
return false
}
const firstRow = Math.max(0, buffer.length - 200)
for (let row = buffer.length - 1; row >= firstRow; row -= 1) {
if (buffer.getLine(row)?.translateToString(true).includes(marker) === true) {
return true
}
}
return false
},
{ tabId, marker }
),
{ timeout: 90_000, message: `scrollback fill marker ${marker} did not render` }
)
.toBe(true)
}
async function updateTerminalSettings(
page: Page,
patch: { terminalHiddenWorktreeRetentionBudget?: boolean; terminalScrollbackRows?: number }
): Promise<void> {
await page.evaluate(async (patch) => {
const store = window.__store
if (!store) {
throw new Error('updateTerminalSettings: window.__store is unavailable')
}
await store.getState().updateSettings(patch)
}, patch)
}
async function waitForRetentionBudgetSetting(page: Page, enabled: boolean): Promise<void> {
await expect
.poll(
() =>
page.evaluate(
() => window.__store?.getState().settings?.terminalHiddenWorktreeRetentionBudget
),
{ timeout: 5_000, message: `terminalHiddenWorktreeRetentionBudget did not become ${enabled}` }
)
.toBe(enabled)
}
test.describe('Terminal hidden worktree retention budget', () => {
test.use({
orcaAppExtraEnv: {
ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS),
// Why limit=1: the retention TTL is absolute production timing (45min) and
// the parking-delay override deliberately no longer shrinks it, so the
// COUNT CAP is the only knob a test can drive. With a budget of 1 the
// newest hidden un-parkable worktree takes the last-active exemption and
// the older one force-parks — cap and exemption proven in one run.
ORCA_E2E_TERMINAL_RETENTION_LIMIT: '1'
},
orcaAppExtraArgs: ['--enable-precise-memory-info']
})
test('releases un-parkable hidden worktree buffers only once the retention budget engages', async ({
orcaPage,
testRepoPath
}, testInfo: TestInfo) => {
test.setTimeout(RETENTION_TEST_TIMEOUT_MS)
await waitForSessionReady(orcaPage)
const victimWorktreeId = await waitForActiveWorktree(orcaPage)
await skipUnlessParkingWired(orcaPage)
const decoyWorktreeId = (await getAllWorktreeIds(orcaPage)).find(
(worktreeId) => worktreeId !== victimWorktreeId
)
if (!decoyWorktreeId) {
throw new Error('retention budget spec: the fixture seeded only one worktree')
}
// Budget OFF for the whole staging phase: that is the control arm proving
// ordinary parking can never evict this class, and it makes the release
// below attributable to the flip alone.
await updateTerminalSettings(orcaPage, {
terminalHiddenWorktreeRetentionBudget: false,
terminalScrollbackRows: RETENTION_SCROLLBACK_ROWS
})
await waitForRetentionBudgetSetting(orcaPage, false)
const runId = randomUUID()
const scriptPath = path.join(testRepoPath, `.orca-retention-memory-${runId}.mjs`)
writeScrollbackFillScript(scriptPath, runId, RETENTION_FILL_LINE_COUNT)
try {
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
const baselineSnapshot = await waitForPaneIdentitySnapshot(orcaPage, 1)
const baselinePtyId = baselineSnapshot.panes[0]?.ptyId
if (!baselinePtyId) {
throw new Error('retention budget spec: baseline terminal tab did not bind a PTY')
}
const victimTabs: ScrollbackTab[] = [{ tabId: baselineSnapshot.tabId, ptyId: baselinePtyId }]
for (let tabIndex = 0; tabIndex < RETENTION_TAB_COUNT; tabIndex += 1) {
if (tabIndex > 0) {
victimTabs.push(await createActiveTerminalTab(orcaPage, victimWorktreeId))
}
const tab = victimTabs[tabIndex]
await sendToTerminal(
orcaPage,
tab.ptyId,
`node ${JSON.stringify(scriptPath)} ${tabIndex}\r`
)
await waitForFillMarkerInTab(
orcaPage,
tab.tabId,
`PARKED_MEMORY_FILL_DONE_${runId}_${tabIndex}`
)
// Why stage after every fill rather than once at the end: each later
// fill takes seconds, and ordinary TAB-level parking would evict the
// already-hidden earlier tabs inside that window.
await stageUnparkableWorktreeTabs(orcaPage, victimWorktreeId)
}
// Hiding the victim first makes the decoy the more-recently-hidden
// candidate, so the cap's last-active exemption lands on the decoy.
await switchToWorktree(orcaPage, decoyWorktreeId)
await expect
.poll(() => orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId), {
timeout: 5_000,
message: 'decoy worktree did not become active before staging'
})
.toBe(decoyWorktreeId)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
// Why the active snapshot (not getWorktreeTabs alone): only tabs that
// actually bound a PaneManager can prove retention; empty/deferred ids
// would make the control arm look like a budget failure.
const decoySnapshot = await waitForPaneIdentitySnapshot(orcaPage, 1)
const decoyTabIds = [decoySnapshot.tabId]
expect(await countMountedPaneManagers(orcaPage, decoyTabIds)).toBe(1)
// Leaving the terminal view hides BOTH worktrees while keeping them
// mounted (App.tsx hides the workbench, it does not unmount it).
await orcaPage.evaluate(() => {
window.__store?.getState().setActiveView('tasks')
})
// Why stage AFTER hide: while a pane is visible/active, bind can rewrite
// our remote: fake ids back onto tab/layout state, so the decoy looks
// park-restorable and ordinary parking unmounts it during the control
// arm. Staging only once both are hidden keeps classification stable.
await stageUnparkableWorktreeTabs(orcaPage, victimWorktreeId)
await stageUnparkableWorktreeTabs(orcaPage, decoyWorktreeId)
await waitForUnparkableWorktreeTabs(orcaPage, victimWorktreeId)
await waitForUnparkableWorktreeTabs(orcaPage, decoyWorktreeId)
const victimTabIds = victimTabs.map((tab) => tab.tabId)
expect(victimTabIds).toHaveLength(RETENTION_TAB_COUNT)
// Control arm: stay hidden past the ordinary parking window with budget
// still off. Re-stage inside the poll so a late bind cannot restore
// park-restorable+coverable ids and unmount mid-wait.
const controlArmStartedAt = Date.now()
await expect
.poll(
async () => {
await stageUnparkableWorktreeTabs(orcaPage, victimWorktreeId)
await stageUnparkableWorktreeTabs(orcaPage, decoyWorktreeId)
const victimMounted = await countMountedPaneManagers(orcaPage, victimTabIds)
const decoyMounted = await countMountedPaneManagers(orcaPage, decoyTabIds)
const heldLongEnough = Date.now() - controlArmStartedAt >= PARKING_DELAY_MS * 4
return {
victimMounted,
decoyMounted,
heldLongEnough
}
},
{
timeout: Math.max(30_000, PARKING_DELAY_MS * 10),
message:
'control arm: un-parkable hidden worktrees did not stay mounted for the parking window'
}
)
.toEqual({
victimMounted: RETENTION_TAB_COUNT,
decoyMounted: 1,
heldLongEnough: true
})
await waitForUnparkableWorktreeTabs(orcaPage, victimWorktreeId)
await waitForUnparkableWorktreeTabs(orcaPage, decoyWorktreeId)
const before = await readRetentionMemorySample(orcaPage)
expect(before.bufferMb).toBeGreaterThan(MIN_STAGED_BUFFER_MB)
const flipStartedAt = Date.now()
await updateTerminalSettings(orcaPage, { terminalHiddenWorktreeRetentionBudget: true })
await waitForRetentionBudgetSetting(orcaPage, true)
await expect
.poll(() => countMountedPaneManagers(orcaPage, victimTabIds), {
timeout: 30_000,
message: 'retention budget did not force-park the older hidden un-parkable worktree'
})
.toBe(0)
const evictionMs = Date.now() - flipStartedAt
const after = await readRetentionMemorySample(orcaPage)
testInfo.annotations.push({
type: 'terminal-retention-budget-memory',
description: [
`stagedTabs=${RETENTION_TAB_COUNT}`,
`scrollbackRows=${RETENTION_SCROLLBACK_ROWS}`,
formatRetentionSample('before', before),
formatRetentionSample('after', after),
`releasedBufferMB=${(before.bufferMb - after.bufferMb).toFixed(1)}`,
`evictionMs=${evictionMs}`
].join(' ')
})
// Primary gate: the staged buffers are gone, not merely hidden.
expect(after.buffers.cells).toBeLessThan(before.buffers.cells * MAX_RETAINED_CELL_FRACTION)
// The decoy holds the cap's last-active exemption, so it stays mounted —
// this is the same run proving the cap did not simply evict everything.
expect(await countMountedPaneManagers(orcaPage, decoyTabIds)).toBe(decoyTabIds.length)
// Secondary only: freed typed arrays return to the allocator's free lists,
// not the OS, so RSS fell just 0.7-3.0 MB locally while 87 MB of buffer was
// released — a strict non-growth assertion would be reading sampling noise.
// What this CAN catch is the inverse regression the capture path risks:
// force-park planting serialized scrollback in the store as it evicts.
if (before.rendererMb !== null && after.rendererMb !== null) {
expect(after.rendererMb).toBeLessThanOrEqual(before.rendererMb + RENDERER_RSS_NOISE_MB)
}
expect(evictionMs).toBeLessThan(MAX_FORCE_PARK_EVICTION_MS)
} finally {
rmSync(scriptPath, { force: true })
}
})
})
+142
View File
@@ -0,0 +1,142 @@
import type { TestInfo } from '@stablyai/playwright-test'
import { test, expect } from './helpers/orca-app'
import { getActiveTabId, waitForActiveWorktree, waitForSessionReady } from './helpers/store'
import {
getTerminalContent,
sendToTerminal,
waitForActivePanePtyId,
waitForActiveTerminalManager
} from './helpers/terminal'
import { waitForTabParked } from './helpers/terminal-hidden-parking'
import {
cleanupDockerSshRelayTarget,
startDockerSshRelayTarget,
type DockerSshRelayTarget
} from './helpers/docker-ssh-relay-target'
import { connectDockerSshRelayTarget } from './helpers/docker-ssh-relay-connection'
import { createAndActivateDockerSshRelayWorktree } from './helpers/docker-ssh-relay-worktree-activation'
const RUN_DOCKER_SSH = process.env.ORCA_E2E_SSH_DOCKER === '1'
const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500
test.use({
// Why no seeded local repo: matching every green Docker SSH spec — the same
// mid-session repo-add misroute hits a remote repo added beside a local one.
seedTestRepo: false,
orcaAppExtraEnv: {
ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS),
// Why limit=1: two hidden un-parkable worktrees then exceed the budget while
// the last-active exemption still spares exactly one — the smallest live proof.
ORCA_E2E_TERMINAL_RETENTION_LIMIT: '1'
}
})
// C1 slice B: hidden worktrees ordinary parking can never evict (here: SSH with
// slice A's terminalSshViewParking off) force-park beyond the retention budget,
// least-recently-hidden first, and reveal restores content from the relay replay.
test.describe('terminal hidden-worktree retention budget', () => {
test.skip(!RUN_DOCKER_SSH, 'Set ORCA_E2E_SSH_DOCKER=1 to run Docker-backed SSH tests.')
test.skip(process.platform === 'win32', 'Docker SSH parking uses POSIX SSH tooling.')
test('force-parks the older hidden un-parkable worktree and spares the newest', async ({
orcaPage
}, testInfo: TestInfo) => {
test.setTimeout(240_000)
let target: DockerSshRelayTarget | null = null
try {
target = startDockerSshRelayTarget(testInfo)
await waitForSessionReady(orcaPage)
const older = await connectDockerSshRelayTarget(orcaPage, target)
await expect
.poll(() => waitForActiveWorktree(orcaPage), { timeout: 30_000 })
.toBe(older.worktreeId)
await waitForActiveTerminalManager(orcaPage, 60_000)
const olderPtyId = await waitForActivePanePtyId(orcaPage, 60_000)
const olderTabId = await getActiveTabId(orcaPage)
if (!olderTabId) {
throw new Error('older SSH terminal tab did not become active')
}
// Why the ':' terminator: match the exact echoed line, not the typed command.
const olderMarker = `RETENTION_OLD_${Date.now()}`
await sendToTerminal(orcaPage, olderPtyId, `echo "${olderMarker}:"\r`)
await expect
.poll(() => getTerminalContent(orcaPage, 20_000), {
timeout: 30_000,
message: 'older worktree marker did not render before hiding'
})
.toContain(`${olderMarker}:`)
// Why: with SSH view parking off, SSH ptys are not park-restorable, so the
// hidden remote worktrees join the un-parkable class the budget governs.
// Written after the first terminal is live so it cannot race target setup;
// parking eligibility reads it at verdict time, not spawn time.
await orcaPage.evaluate(async () => {
await window.__store?.getState().updateSettings({ terminalSshViewParking: false })
})
// Why worktrees of ONE remote repo: the retention budget ranks worktrees,
// and a repo added mid-session misroutes its pty spawn to the local daemon
// (pre-existing multi-repo issue, independent of retention).
// Activating the second worktree hides the older one, making the older the
// least-recently-hidden candidate.
const newer = await createAndActivateDockerSshRelayWorktree(
orcaPage,
older.repoId,
'retention-newer'
)
await expect
.poll(() => waitForActiveWorktree(orcaPage), { timeout: 30_000 })
.toBe(newer.worktreeId)
await waitForActiveTerminalManager(orcaPage, 60_000)
await waitForActivePanePtyId(orcaPage, 60_000)
const newerTabId = await getActiveTabId(orcaPage)
if (!newerTabId) {
throw new Error('newer SSH terminal tab did not become active')
}
// Third context: activating it hides BOTH earlier worktrees — two hidden
// un-parkable worktrees against a budget of one. It stays visible, so it
// is never a retention candidate itself.
const third = await createAndActivateDockerSshRelayWorktree(
orcaPage,
older.repoId,
'retention-third'
)
await expect
.poll(() => waitForActiveWorktree(orcaPage), { timeout: 30_000 })
.toBe(third.worktreeId)
await waitForActiveTerminalManager(orcaPage, 60_000)
// The older worktree must force-park (its pane managers unmount)…
await waitForTabParked(orcaPage, olderTabId, { parkDelayMs: PARKING_DELAY_MS })
// …while the newest hidden worktree keeps its mounted panes (last-active exemption).
const newerStillMounted = await orcaPage.evaluate(
(tabId) => window.__paneManagers?.get(tabId) !== undefined,
newerTabId
)
expect(newerStillMounted).toBe(true)
// Reveal the evicted worktree: with SSH parking disabled the model paint is
// off, so the relay replay must restore the marker tail — never a blank pane.
await orcaPage.evaluate(
({ worktreeId, tabId }) => {
const state = window.__store?.getState()
state?.setActiveWorktree(worktreeId)
state?.setActiveTab(tabId)
state?.setActiveTabType('terminal')
},
{ worktreeId: older.worktreeId, tabId: olderTabId }
)
await waitForActiveTerminalManager(orcaPage, 60_000)
await expect
.poll(() => getTerminalContent(orcaPage, 20_000), {
timeout: 60_000,
message: 'revealed evicted worktree did not restore the marker via relay replay'
})
.toContain(`${olderMarker}:`)
} finally {
cleanupDockerSshRelayTarget(target)
}
})
})