Repository navigation
fix(terminal): bound SSH & remote hidden-worktree terminal retention (C1) - #10625
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughTerminal 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)
✅ Passed checks (3 passed)
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/renderer/src/components/terminal-pane/ssh-reattach-model-restore.test.ts (1)
7-8: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDerive the SSH fixture id from the shared builder.
ssh:conn-1@@relay-pty-1is hardcoded, but changingSSH_PTY_ID_PREFIX/separator would makeparseAppSshPtyId()returnnulland turn the positive SSH cases into fallback expectations silently. UsetoAppSshPtyIdfor the SSH fixture and keep constants unexported/internal.src/renderer/src/components/Terminal.tsx (2)
913-940: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueHoist the single
restorePolicyliteral.
{ 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 winMemoize
isEvictionExemptTerminalTabper tab like watcher coverage.
hasEvictionExemptTabrunsisEvictionExemptTerminalTabfor 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
📒 Files selected for processing (19)
src/renderer/src/components/Terminal.tsxsrc/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsxsrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/ssh-reattach-model-restore.test.tssrc/renderer/src/components/terminal-pane/ssh-reattach-model-restore.tssrc/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.test.tssrc/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.tssrc/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.tssrc/renderer/src/components/terminal-pane/terminal-hidden-view-parking.tssrc/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.test.tssrc/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.tssrc/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.tssrc/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.tssrc/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.test.tssrc/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.tssrc/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.tssrc/shared/types.tstests/e2e/ssh-terminal-parking.spec.ts
There was a problem hiding this comment.
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 winByte-mode test coverage for Command Code "done" is missing.
Only
onCommandCodeWorkingis exercised via the byte-parser path here;onCommandCodeDonewiring (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
📒 Files selected for processing (12)
src/preload/e2e-config.tssrc/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.tssrc/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.tssrc/renderer/src/components/terminal-pane/parked-terminal-command-status.test.tssrc/renderer/src/components/terminal-pane/parked-terminal-command-status.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.test.tssrc/renderer/src/components/terminal-pane/terminal-parking-e2e-overrides.tssrc/shared/e2e-config.tstests/e2e/helpers/docker-ssh-relay-worktree-activation.tstests/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
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/pty-connection.test.ts (1)
17781-17820: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winGood 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 assertgetMainBufferSnapshotwas called exactly once — which is the actual guaranteememoizeSshReattachModelSnapshotProbeis supposed to provide here (avoiding a second timeout window). Addingexpect(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
📒 Files selected for processing (28)
src/renderer/src/components/Terminal.tsxsrc/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.tssrc/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.tssrc/renderer/src/components/terminal-pane/parked-terminal-command-status.test.tssrc/renderer/src/components/terminal-pane/parked-terminal-command-status.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/shutdown-buffer-captures.test.tssrc/renderer/src/components/terminal-pane/shutdown-buffer-captures.tssrc/renderer/src/components/terminal-pane/ssh-reattach-model-restore.test.tssrc/renderer/src/components/terminal-pane/ssh-reattach-model-restore.tssrc/renderer/src/components/terminal-pane/terminal-cold-park-recheck-deadlines.test.tssrc/renderer/src/components/terminal-pane/terminal-cold-park-recheck-deadlines.tssrc/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.test.tssrc/renderer/src/components/terminal-pane/terminal-hidden-scrollback-demotion.tssrc/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.tssrc/renderer/src/components/terminal-pane/terminal-hidden-view-parking.tssrc/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.test.tssrc/renderer/src/components/terminal-pane/terminal-hidden-worktree-retention.tssrc/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.test.tssrc/renderer/src/components/terminal-pane/terminal-snapshot-replay-paint.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.tssrc/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.tssrc/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.tssrc/shared/command-code-output-status.tssrc/shared/constants.tstests/e2e/helpers/terminal-hidden-parking.tstests/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
|
@coderabbitai[bot] resolvede |
2 similar comments
|
@coderabbitai[bot] resolvede |
|
@coderabbitai[bot] resolvede |
|
Tip For best results, initiate chat on the files or code changes.
|
|
Tip For best results, initiate chat on the files or code changes.
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! |
|
Tip For best results, initiate chat on the files or code changes.
This will resolve all of my review comments on PR |
27d0a9f to
0e44e91
Compare
…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.
…e PR body Co-authored-by: Orca <[email protected]>
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]>
… 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).
0e44e91 to
31e0c9f
Compare
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 SummaryBounds 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,
Confidence Score: 4/5Safe 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).
|
| 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.
…(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]>
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):
terminalSshViewParkingterminalHiddenWorktreeRetentionBudgetMaster 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
runtime.onPtyData→ headless model, ~5k rows viapty: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.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):
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
terminalSshViewParkingis on.runtimeEnvironmentIdstill disqualifies remote-runtime.applyMainBufferSnapshotinside the structural-replay coordinator — deadlock).B — Force-park retention budget (SSH-off / remote / uncoverable)
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)
working.Intentionally out of scope / removed
Kill switches
terminalHiddenViewParkingterminalSshViewParkingterminalHiddenWorktreeRetentionBudgetTest matrix (SSH & remote focused)
ssh-terminal-parking.spec.ts(ORCA_E2E_SSH_DOCKER=1)terminal-retention-budget.spec.tsResiduals
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 🐋