Skip to content

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

Merged
AmethystLiang merged 30 commits into
mainfrom
fix-c1-worktree-retention
Jul 29, 2026
Merged

AmethystLiang merged 30 commits into
mainfrom
fix-c1-worktree-retention

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #8652

C1 — memory-bounded terminal retention for SSH & remote worktrees

Renderer JS-heap growth to ~3.5 GB was the dominant cause in the 2026-07-25 crash triage (57 reports / 20 h). The failure mode is unbounded retention of mounted terminal panes on hidden SSH and remote worktrees: pre-fix, ordinary cold parking could not evict them, so every per-pane accumulator lived forever alongside them.

Field fit: the zero-git OOM bundle is an SSH workspace with multiple worktree activations — the exact “nothing can ever park this remote class” profile.

What this PR actually ships

Two live slices (demotion was tried and intentionally removed — see below):

slice what switch
A SSH worktrees park like local ones; reveal paints from main’s headless model (relay replay is fallback) terminalSshViewParking
B Hidden un-parkable worktrees (SSH with A off, remote-runtime, uncoverable tabs, etc.) force-park past a count budget (12) or TTL (45 min) terminalHiddenWorktreeRetentionBudget

Master parking switch: terminalHiddenViewParking (off ⇒ nothing parks or force-parks).

Not in this PR (removed on purpose): slice C scrollback demotion / terminalHiddenScrollbackDemotion. Retention is now a worktree fleet bound (how many hidden SSH/remote worktrees stay mounted), not a per-pane scrollback shrink. High-scrollback (50k) panes that remain mounted — including eviction-exempt local tabs inside a force-parked worktree — keep full scrollback; the budget still wins by unmounting the remote/SSH siblings that caused the OOMs.


Why SSH & remote are the special case

  • Pre-fix cold parking required a restorable pty for every tab. SSH (before A) and remote-runtime failed that test, so a whole hidden remote worktree stayed mounted forever.
  • SSH bytes do transit local main (runtime.onPtyData → headless model, ~5k rows via pty:getMainBufferSnapshot). Pre-fix SSH reattach only painted the relay’s rolling 100 KiB raw-byte tail, so parking SSH without a model-aware reveal would blank or truncate history.
  • Remote-runtime is harder: no bytes on main; desktop subscribe is screen-only. Force-park still bounds the fleet; reveal is cold-restore / screen + captured tail, not full model depth.

Local parkable worktrees were already covered by ordinary hot-retain / cold parking. This PR’s new levers exist so SSH can park safely and remaining un-parkable remote classes cannot accumulate without bound.

Measured cost per retained hidden pane (steady state):

scrollback V8 heap ArrayBuffers (off-heap)
5 000 rows (default) ~2.5 MB ~12 MB
50 000 rows (max) ~19.4 MB ~114.7 MB

Static retention alone reaches multi‑GB with large fleets of high-scrollback remote panes; multi-hour climbs are H1 (unbounded fleet) × per-pane accumulators.


Design as built

A — SSH park + model-preferring reveal

  • SSH-shaped pty ids are park-restorable when terminalSshViewParking is on.
  • Fact-mode parked watchers cover SSH (bytes transit main); non-null runtimeEnvironmentId still disqualifies remote-runtime.
  • On park-reveal only (not ordinary in-place reconnect), reattach prefers main’s headless model snapshot over relay replay; empty/non-headless snapshots fall back to relay — never a blank paint when either source has content.
  • Model probe is memoized, timeout-bounded (750 ms), and not taken on every SSH reattach.
  • Paint is inline in the reattach path (must not nest applyMainBufferSnapshot inside the structural-replay coordinator — deadlock).

B — Force-park retention budget (SSH-off / remote / uncoverable)

  • Targets worktrees ordinary parking cannot evict: SSH with A off, remote-runtime, uncoverable tabs, etc.
  • At most 12 hidden un-parkable worktrees, none past 45 minutes (TTL is absolute; last-active exemption bounds the cap only, not the clock). Evict least-recently-hidden first via force-park (same parked machinery as ordinary park).
  • Eviction exemption is per tab / per pane, not per worktree. Unrestorable local live shells keep their mounted panes so remount does not orphan them; the worktree still force-parks so SSH/remote sibling tabs unmount.
  • Pre-unmount buffer capture for classes that need it (relay/remote hosts); local daemon-backed panes do not plant large retained strings in the store.
  • Post-measure cool-down + hidden clock preserved through transient background-measure windows so SSH/remote force-park does not thrash on measure remounts.
  • Exempt-tab resolution is memoized per force-park verdict / tab set (selectEvictionExemptTerminalTabIds), so render and watcher sync do not re-walk layout/capture candidates on unrelated Terminal renders.

Parked command lifecycle (SSH/local parity while parked)

  • OSC 133 / Command Code facts continue through parked watchers where transport exists.
  • Command Code done-settle is turn-owned (shared settle window): park/reveal hands the deadline across mount dispose ↔ parked watcher ↔ remount so a mid-settle turn does not strand as working.

Intentionally out of scope / removed

  • Scrollback demotion (former slice C): removed. Accept that memory bound is worktree count/TTL for the SSH/remote un-parkable class, not per-pane row demotion.
  • Deferred PTY side-effect queue is capped on this branch (H2 residual).

Kill switches

switch scope
terminalHiddenViewParking master parking
terminalSshViewParking A: SSH eligibility + model-paint reveal
terminalHiddenWorktreeRetentionBudget B: force-park budget for un-parkable (remote/SSH-off/…)
revert resulting behavior
A off, B on SSH rejoins un-parkable class → force-parks past budget/TTL; reveal uses relay only
B off, A on SSH parks ordinarily; other un-parkable remote classes can accumulate again
master off pre-parking: every mounted worktree retained forever

Test matrix (SSH & remote focused)

coverage status
SSH eligibility / paint-source / model probe gates unit
Force-park selector (budget, TTL, exemptions, cool-down) unit
Eviction exemption vs coverage on split panes unit
SSH park+reveal e2e with model-depth proof (early marker past 100 KiB relay pad) Docker e2e ssh-terminal-parking.spec.ts (ORCA_E2E_SSH_DOCKER=1)
Retention-budget force-park e2e on same-repo remote worktrees Docker e2e terminal-retention-budget.spec.ts
Local park/reveal + flip-loop pre-existing e2e

Residuals

  1. No per-pane scrollback bound — accepted tradeoff. Scrollback demotion (former slice C) is intentionally gone; retention is bounded by hidden-worktree count (12) + TTL (45 min) + force-park only. Panes that stay mounted — eviction-exempt local tabs inside a force-parked worktree, and the last-active spared un-parkable worktree — can therefore hold full scrollback (including the 50k max, ~19 MB heap / ~115 MB ArrayBuffers per pane) indefinitely. High-scrollback users rely on unmount eviction, not demotion. Do not restore demotion unless product asks for it; the measured per-pane costs above are the rationale for why the tradeoff matters.
  2. Remote-runtime reveal depth stays screen/capture-limited until a runtime scrollback RPC exists.
  3. Post-measure remount cool-down is unit-proven, accepted as unit-only: the selector test asserts a past-TTL measured worktree stays out of force-park until its cool-down ends (terminal-hidden-worktree-retention.test.ts), and the tab layer asserts the same hysteresis plus the visible-worktree clear (use-terminal-tab-cold-parking.test.ts). No e2e — the Docker SSH/remote setup cost outweighs the marginal proof.

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Terminal parking now supports SSH-specific restoration, retention-budget force parking, shutdown-buffer capture, eviction-exempt pane preservation, and cooldown-aware rechecks. SSH reattachment can use timed, memoized headless model snapshots with shared replay painting. Parked terminals now track command lifecycle status across byte and main-authority paths. PTY side-effect queues are bounded, E2E configuration exposes retention limits, and new unit and end-to-end tests cover these behaviors.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is informative, but it does not follow the required template and omits Screenshots, Testing, AI Review Report, Security Audit, and Notes. Rewrite the description with the template headings and add the missing screenshots, testing checklist, AI review, security audit, and notes sections.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main change: bounded retention for SSH and remote hidden worktrees.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
src/renderer/src/components/terminal-pane/ssh-reattach-model-restore.test.ts (1)

7-8: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the SSH fixture id from the shared builder.

ssh:conn-1@@relay-pty-1 is hardcoded, but changing SSH_PTY_ID_PREFIX/separator would make parseAppSshPtyId() return null and turn the positive SSH cases into fallback expectations silently. Use toAppSshPtyId for the SSH fixture and keep constants unexported/internal.

src/renderer/src/components/Terminal.tsx (2)

913-940: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Hoist the single restorePolicy literal.

{ sshParkingEnabled: terminalSshParkingEnabled } is built inline at Line 913 and again as a const at Line 940. Declare it once before Line 908 and reuse.

♻️ Proposed tidy-up
+    const restorePolicy = { sshParkingEnabled: terminalSshParkingEnabled }
     const nextParkedTerminalWorktreeIds = selectColdParkedTerminalWorktrees({
       worktrees: retentionCandidates,
       pendingStartupByTabId,
       parkingEnabled: terminalParkingEnabled,
       nowMs,
-      restorePolicy: { sshParkingEnabled: terminalSshParkingEnabled },
+      restorePolicy,
       ...overrides
     })
@@
-    const restorePolicy = { sshParkingEnabled: terminalSshParkingEnabled }
     const retentionBudgetCandidates: TerminalWorktreeRetentionCandidate[] = retentionCandidates.map(

941-973: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Memoize isEvictionExemptTerminalTab per tab like watcher coverage.

hasEvictionExemptTab runs isEvictionExemptTerminalTab for every tab of every mounted worktree on each pass, and each call re-reads the store and can walk the layout tree — the exact cost the comment at Line 916 memoized away for coverage. This effect re-runs on every tab-model change and recheck timer, so the exemption path deserves the same one-pass cache.

♻️ Proposed cache
+    const evictionExemptByTabId = new Map<string, boolean>()
+    const tabIsEvictionExempt = (worktreeId: string, tab: TerminalTab): boolean => {
+      const cached = evictionExemptByTabId.get(tab.id)
+      if (cached !== undefined) {
+        return cached
+      }
+      const exempt = isEvictionExemptTerminalTab(tab, worktreeId)
+      evictionExemptByTabId.set(tab.id, exempt)
+      return exempt
+    }
@@
-          hasEvictionExemptTab: tabs.some((tab) =>
-            isEvictionExemptTerminalTab(tab, candidate.worktreeId)
-          ),
+          hasEvictionExemptTab: tabs.some((tab) => tabIsEvictionExempt(candidate.worktreeId, tab)),

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9c2ba6bf-e492-424b-8f5d-a4d4d7f28d63

📥 Commits

Reviewing files that changed from the base of the PR and between 468f5b7 and 1260d4c.

📒 Files selected for processing (19)
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/ssh-reattach-model-restore.test.ts
  • src/renderer/src/components/terminal-pane/ssh-reattach-model-restore.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.test.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.test.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts
  • src/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
  • src/shared/types.ts
  • tests/e2e/ssh-terminal-parking.spec.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts (1)

401-409: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Byte-mode test coverage for Command Code "done" is missing.

Only onCommandCodeWorking is exercised via the byte-parser path here; onCommandCodeDone wiring (line 238-240 of the source) has no equivalent byte-mode test, only the fact-mode one. A regression swapping the two callbacks in the byte-mode object literal would slip through.

✅ Suggested companion test
it('feeds Command Code idle output through the parked byte detector as done', async () => {
  const { dispose } = await startWatcher()

  emit('# Command Code v0.27.2')
  emit('❯ Fix the spinner\n')
  emit('❯ ')

  expect(commandStatusPolicy.onCommandCodeDone).toHaveBeenCalled()
  dispose()
})

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8ae541c9-2315-43c2-96dc-72da3c50b432

📥 Commits

Reviewing files that changed from the base of the PR and between 1260d4c and 68d83f1.

📒 Files selected for processing (12)
  • src/preload/e2e-config.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-command-status.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-command-status.ts
  • src/renderer/src/components/terminal-pane/pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.test.ts
  • src/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.ts
  • src/shared/e2e-config.ts
  • tests/e2e/helpers/docker-ssh-relay-worktree-activation.ts
  • tests/e2e/terminal-retention-budget.spec.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

17781-17820: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Good coverage of the stall→fallback path; consider locking in the single-probe guarantee.

The test confirms relay-replay content appears only after SSH_REATTACH_MODEL_SNAPSHOT_TIMEOUT_MS, but doesn't assert getMainBufferSnapshot was called exactly once — which is the actual guarantee memoizeSshReattachModelSnapshotProbe is supposed to provide here (avoiding a second timeout window). Adding expect(window.api.pty.getMainBufferSnapshot).toHaveBeenCalledTimes(1) would directly pin that invariant.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 18890ca3-07c4-4f02-b81c-f3505dbac4fa

📥 Commits

Reviewing files that changed from the base of the PR and between 68d83f1 and db60fa1.

📒 Files selected for processing (28)
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-command-status.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-command-status.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/shutdown-buffer-captures.test.ts
  • src/renderer/src/components/terminal-pane/shutdown-buffer-captures.ts
  • src/renderer/src/components/terminal-pane/ssh-reattach-model-restore.test.ts
  • src/renderer/src/components/terminal-pane/ssh-reattach-model-restore.ts
  • src/renderer/src/components/terminal-pane/terminal-cold-park-recheck-deadlines.test.ts
  • src/renderer/src/components/terminal-pane/terminal-cold-park-recheck-deadlines.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.test.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.test.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.ts
  • src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.ts
  • src/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.ts
  • src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts
  • src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts
  • src/shared/command-code-output-status.ts
  • src/shared/constants.ts
  • tests/e2e/helpers/terminal-hidden-parking.ts
  • tests/e2e/ssh-terminal-parking.spec.ts
🚧 Files skipped from review as they are similar to previous changes (10)
  • src/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.test.ts
  • tests/e2e/ssh-terminal-parking.spec.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-command-status.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-command-status.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.ts
  • src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.ts
  • src/renderer/src/components/Terminal.tsx
  • src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.test.ts

@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai[bot] resolvede

2 similar comments
@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai[bot] resolvede

@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai[bot] resolvede

@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Tip

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

@AmethystLiang, did you mean @coderabbitai resolve to resolve all of my review comments?

@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Tip

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

@AmethystLiang: Thanks for resolving these.


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

Thank you for using CodeRabbit!

@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Tip

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

@AmethystLiang, it looks like there’s a typo again. Please post:

@coderabbitai resolve

This will resolve all of my review comments on PR #10625.

@AmethystLiang
AmethystLiang force-pushed the fix-c1-worktree-retention branch from 27d0a9f to 0e44e91 Compare July 28, 2026 01:49
@AmethystLiang AmethystLiang changed the title fix(terminal): memory-bounded terminal retention (C1) — SSH parking, force-park budget, scrollback demotion fix(terminal): bound SSH & remote hidden-worktree terminal retention (C1) Jul 28, 2026
AmethystLiang and others added 16 commits July 28, 2026 13:21
…e 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 <[email protected]>
…et (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 <[email protected]>
… (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 <[email protected]>
…ordinator (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 <[email protected]>
…s (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 <[email protected]>
… 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 <[email protected]>
…ion-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 <[email protected]>
…(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 <[email protected]>
…ed (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 <[email protected]>
…ound-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 <[email protected]>
…del 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 <[email protected]>
…(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 <[email protected]>
…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.
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 <[email protected]>
…(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 <[email protected]>
AmethystLiang and others added 10 commits July 28, 2026 13:21
… 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 <[email protected]>
…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 <[email protected]>
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.
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.
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.
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.
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.
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.
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.
Reflow to 80-character lines and remove internal ticket references
(C1, C1 slice C).
@AmethystLiang
AmethystLiang force-pushed the fix-c1-worktree-retention branch from 0e44e91 to 31e0c9f Compare July 28, 2026 21:14
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.
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.
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.
@greptile-apps

greptile-apps Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

Bounds unbounded SSH and remote hidden-worktree terminal retention that was causing ~3.5 GB renderer heap growth (57 crash reports over 20 h). Two independent slices: SSH worktrees now park and reveal like local ones via a main-process headless-model snapshot (slice A, terminalSshViewParking), and un-parkable hidden worktrees (remote-runtime, SSH-off, uncoverable tabs) are force-parked past a count/TTL budget (slice B, terminalHiddenWorktreeRetentionBudget).

  • Slice A adds isParkRestorableTerminalPty to make SSH ptys park-eligible, a memoized 750 ms-bounded model probe on reveal, and a shared command-code-done-settle cross-mount settle window so park/reveal hand-offs cannot strand a turn at 'working'.
  • Slice B adds selectRetentionForceParkedTerminalWorktrees (≤ 12 worktrees, ≤ 45 min absolute TTL, last-active exemption for the cap only), per-tab eviction exemption for live local shells that cannot reattach on remount, and a post-measure cool-down clock to prevent remount thrash on periodic background-measure leases.
  • Kill switches (terminalHiddenViewParking, terminalSshViewParking, terminalHiddenWorktreeRetentionBudget) are all default-on and revert independently; scrollback demotion (former slice C) was intentionally removed in favour of the fleet count/TTL bound.

Confidence Score: 4/5

Safe to merge with careful rollout monitoring; the retention budget and SSH parking paths are gated behind independent kill switches that can be toggled at runtime without a restart.

The individual pieces (retention selector, eviction-exempt tabs, SSH model probe, command-code settle hand-off) are each well-scoped and unit-tested. The primary risk is in Terminal.tsx's parking pass, which orchestrates three new state updates in a single callback that the render gate, watcher-sync effect, and per-worktree useTerminalTabColdParking hook all depend on staying consistent. The force-park capture path reads repos via getState() outside the effect dependency array — an intentional but acknowledged trade-off where a stale read on a newly-registered SSH workspace would mark the episode captured with no buffers written and no retry.

Files Needing Attention: Terminal.tsx (force-park orchestration pass — three new state updates + capture ref must stay consistent), use-terminal-tab-cold-parking.ts (measure cool-down and exempt-tab memo interact with the worktree-level clock), pty-connection.ts (inline SSH model paint must not nest inside structuralReplayCoordinator).

Important Files Changed

Filename Overview
src/renderer/src/components/Terminal.tsx Major orchestration changes: adds force-park path (slice B) with retention budget, eviction-exempt tab tracking, pre-unmount buffer capture, and measure cool-down clocks — the most complex integration surface in the PR.
src/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.ts New file: defines the 12-worktree / 45-minute retention budget selector, eviction-exempt PTY classification, and the last-active TTL override re-application — logic is correct and well-commented.
src/renderer/src/components/terminal-pane/terminal-eviction-exempt-tabs.ts New file: eviction exemption logic for tabs whose PTYs cannot survive a remount; the layout-key memo correctly invalidates when split-pane leaf PTYs change without a tab-array change.
src/renderer/src/components/terminal-pane/ssh-reattach-model-restore.ts New file: SSH park-reveal paint-source decision (headless model vs relay replay) — correctly gates on headless source, non-zero content length, and SSH-parking kill-switch; probe is memoized and timeout-bounded.
src/renderer/src/components/terminal-pane/command-code-done-settle.ts New file: cross-mount settle window for Command Code done state — last-registrant-wins design is intentional with correct identity-check release.
src/renderer/src/components/terminal-pane/parked-terminal-command-status.ts New file: ports store-level command-lifecycle signals to parked panes; correctly scopes SSH-only status drop to the SSH pty path and shares the cross-mount settle window.
src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.ts Adds measure cool-down clocks and force-park exempt-tab integration; the layout-key store subscription correctly invalidates the exempt-tab memo when split-pane PTYs change without a tab-array change.
src/renderer/src/components/terminal-pane/pty-connection.ts Adds SSH reveal model-snapshot path (memoized probe, inline paint) and cross-mount Command Code settle window integration; mountFollowsTerminalPark correctly gates the model probe to the first reveal reattach only.

Reviews (2): Last reviewed commit: "fix: memoize terminal eviction exemption..." | Re-trigger Greptile

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.
@AmethystLiang
AmethystLiang merged commit a7c8b8e into main Jul 29, 2026
41 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…(C1) (stablyai#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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* fix(terminal): paint SSH reveal from main's model even when the relay replay is empty (C1 review stablyai#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 <[email protected]>

* fix(terminal): decouple scrollback demotion (slice C) from the retention-budget switch (C1 review stablyai#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 <[email protected]>

* fix(terminal): scope eviction exemption to the tab, not the worktree (C1 review stablyai#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 <[email protected]>

* fix(terminal): demote un-parkable worktrees the force-park lever spared (C1 review stablyai#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 <[email protected]>

* fix(terminal): keep the hidden clock running through transient background-measure windows (C1 review stablyai#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 <[email protected]>

* 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 <[email protected]>

* docs(terminal): rewrite DESIGN.md as the single as-built C1 contract (review stablyai#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 <[email protected]>

* fix(terminal): resolve the eviction exemption per pane, not per tab (C1 review stablyai#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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SSH & remote-server PTY tabs excluded from hidden-view parking causes unbounded renderer heap growth

1 participant