From a7c8b8e07161ec05c44dbf2a0d11dad9c71a4710 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Wed, 29 Jul 2026 00:47:18 -0700 Subject: [PATCH] fix(terminal): bound SSH & remote hidden-worktree terminal retention (C1) (#10625) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 --- .github/workflows/e2e.yml | 11 +- .../run-ssh-docker-terminal-parking-e2e.mjs | 45 ++ package.json | 1 + src/main/ipc/pty.test.ts | 39 ++ src/main/ipc/pty.ts | 5 + src/preload/e2e-config.ts | 3 +- src/renderer/src/components/Terminal.tsx | 247 ++++++++++- .../terminal-pane/TerminalOverlaySlot.tsx | 290 ++++++++++++ ...TerminalPaneOverlayLayer.react185.test.tsx | 2 +- .../TerminalPaneOverlayLayer.tsx | 294 +------------ .../command-code-done-settle.test.ts | 113 +++++ .../terminal-pane/command-code-done-settle.ts | 64 +++ .../force-park-buffer-capture.test.ts | 61 +++ .../force-park-buffer-capture.ts | 29 ++ .../parked-terminal-byte-watcher.test.ts | 108 ++++- .../parked-terminal-byte-watcher.ts | 38 ++ .../parked-terminal-command-status.test.ts | 345 +++++++++++++++ .../parked-terminal-command-status.ts | 197 +++++++++ .../terminal-pane/pty-connection.test.ts | 95 ++++ .../terminal-pane/pty-connection.ts | 266 +++++++---- .../terminal-pane/pty-transport.test.ts | 98 +++++ .../components/terminal-pane/pty-transport.ts | 40 ++ .../replayed-scrollback-store-release.test.ts | 63 +++ .../replayed-scrollback-store-release.ts | 22 + .../shutdown-buffer-captures.test.ts | 39 ++ .../terminal-pane/shutdown-buffer-captures.ts | 22 + .../ssh-reattach-model-restore.test.ts | 157 +++++++ .../ssh-reattach-model-restore.ts | 85 ++++ ...rminal-cold-park-recheck-deadlines.test.ts | 172 ++++++++ .../terminal-cold-park-recheck-deadlines.ts | 72 +++ .../terminal-eviction-exempt-tabs.test.ts | 49 +++ .../terminal-eviction-exempt-tabs.ts | 87 ++++ .../terminal-hidden-view-parking.test.ts | 204 ++++----- .../terminal-hidden-view-parking.ts | 114 +++-- ...terminal-hidden-worktree-retention.test.ts | 195 +++++++++ .../terminal-hidden-worktree-retention.ts | 130 ++++++ .../terminal-parked-tab-watchers.test.ts | 124 +++++- .../terminal-parked-tab-watchers.ts | 27 +- .../terminal-parked-watcher-registry.ts | 10 + .../terminal-parking-e2e-overrides.test.ts | 68 ++- .../terminal-parking-e2e-overrides.ts | 21 +- .../terminal-shutdown-layout-capture.test.ts | 72 +++ .../terminal-shutdown-layout-capture.ts | 62 ++- ...terminal-side-effect-facts-handler.test.ts | 130 ++++++ .../terminal-side-effect-facts-handler.ts | 77 +++- .../terminal-snapshot-replay-paint.test.ts | 68 +++ .../terminal-snapshot-replay-paint.ts | 62 +++ .../use-terminal-pane-lifecycle.ts | 18 +- .../use-terminal-tab-cold-parking.test.ts | 214 +++++++++ .../use-terminal-tab-cold-parking.ts | 81 +++- src/shared/command-code-output-status.ts | 9 +- src/shared/constants.ts | 4 + src/shared/e2e-config.ts | 14 +- src/shared/types.ts | 4 + .../docker-ssh-relay-worktree-activation.ts | 67 +++ tests/e2e/helpers/terminal-hidden-parking.ts | 13 +- tests/e2e/ssh-terminal-parking.spec.ts | 115 +++++ tests/e2e/terminal-parked-memory.spec.ts | 413 +++++++++++++++++- tests/e2e/terminal-retention-budget.spec.ts | 142 ++++++ 59 files changed, 5003 insertions(+), 614 deletions(-) create mode 100644 config/scripts/run-ssh-docker-terminal-parking-e2e.mjs create mode 100644 src/renderer/src/components/terminal-pane/TerminalOverlaySlot.tsx create mode 100644 src/renderer/src/components/terminal-pane/command-code-done-settle.test.ts create mode 100644 src/renderer/src/components/terminal-pane/command-code-done-settle.ts create mode 100644 src/renderer/src/components/terminal-pane/force-park-buffer-capture.test.ts create mode 100644 src/renderer/src/components/terminal-pane/force-park-buffer-capture.ts create mode 100644 src/renderer/src/components/terminal-pane/parked-terminal-command-status.test.ts create mode 100644 src/renderer/src/components/terminal-pane/parked-terminal-command-status.ts create mode 100644 src/renderer/src/components/terminal-pane/replayed-scrollback-store-release.test.ts create mode 100644 src/renderer/src/components/terminal-pane/replayed-scrollback-store-release.ts create mode 100644 src/renderer/src/components/terminal-pane/shutdown-buffer-captures.test.ts create mode 100644 src/renderer/src/components/terminal-pane/ssh-reattach-model-restore.test.ts create mode 100644 src/renderer/src/components/terminal-pane/ssh-reattach-model-restore.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-cold-park-recheck-deadlines.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-cold-park-recheck-deadlines.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-eviction-exempt-tabs.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-eviction-exempt-tabs.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.ts create mode 100644 src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts create mode 100644 src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts create mode 100644 tests/e2e/helpers/docker-ssh-relay-worktree-activation.ts create mode 100644 tests/e2e/ssh-terminal-parking.spec.ts create mode 100644 tests/e2e/terminal-retention-budget.spec.ts diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index c2b597faf..2ab1ed444 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -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 diff --git a/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs b/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs new file mode 100644 index 000000000..8d4183b45 --- /dev/null +++ b/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs @@ -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) diff --git a/package.json b/package.json index cdb8880f8..df94846cc 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index 58b841508..190a1288b 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -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' diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index feae29a00..5a82ff3df 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -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 ( diff --git a/src/preload/e2e-config.ts b/src/preload/e2e-config.ts index f1cdf668c..8414f62d3 100644 --- a/src/preload/e2e-config.ts +++ b/src/preload/e2e-config.ts @@ -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 }) diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index 96469e69f..c87c25cbd 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -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([ type TerminalStoreSnapshot = ReturnType -function haveSameWorktreeIds(left: ReadonlySet, right: ReadonlySet): boolean { +function haveSameIdSet(left: ReadonlySet, right: ReadonlySet): boolean { if (left.size !== right.size) { return false } @@ -251,6 +268,12 @@ function Terminal(): React.JSX.Element | null { const mountedWorktreeIdsRef = useRef(new Set()) const measurableBackgroundWorktreeIdsRef = useRef(new Set()) const terminalWorktreeHiddenSinceRef = useRef(new Map()) + // 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()) + const terminalWorktreeParkCooldownUntilRef = useRef(new Map()) const terminalWorktreeParkingTimersRef = useRef(new Map()) 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 + >(() => 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 + >(() => new Set()) + // Why a ref: eviction captures buffers exactly once per force-park episode, before the unmount render. + const forceParkedCaptureDoneRef = useRef(new Set()) // Tab restriction for targeted background mounts (wake/resume); a worktree absent from this map mounts all its tabs. const backgroundMountTabIdsByWorktreeRef = useRef(new Map>()) // 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() + 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() + 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 | null activationDeferredMountTabIds: ReadonlySet | 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} diff --git a/src/renderer/src/components/terminal-pane/TerminalOverlaySlot.tsx b/src/renderer/src/components/terminal-pane/TerminalOverlaySlot.tsx new file mode 100644 index 000000000..1da822d7c --- /dev/null +++ b/src/renderer/src/components/terminal-pane/TerminalOverlaySlot.tsx @@ -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(null) + const [measuredFallbackRect, setMeasuredFallbackRect] = useState( + 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('[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 = ( +