Repository navigation
Stop hidden terminal panes from exhausting renderer memory (experimental opt-in, default off) - #7375
brennanb2025 wants to merge 15 commits into
Conversation
…ew parking, byte mode, default off) Extracts the self-contained "hidden-view parking" slice from PR #7214 (orca-performance) as a standalone fix for the Windows renderer OOM/hang under multi-agent load (#7175 / STA-476): long-hidden terminal panes unmount after a 30s hysteresis while a pane-less byte watcher keeps bell/title/agent-completion side effects alive; reveal rides the existing tab-move reattach path. Byte mode only: no main-process side-effect emitter ships here, so constants.ts pins terminalMainSideEffectAuthority / terminalHiddenDeliveryGate / terminalModelQueryAuthority to false (the single intentional divergence from #7214, reconciled by taking #7214's values when its emitter lands). The parking kill switch terminalHiddenViewParking also ships default-OFF (opt-in) until the memory win is confirmed in a soak. Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com> Co-authored-by: Orca <help@stably.ai>
…e (from #7214) Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com> Co-authored-by: Orca <help@stably.ai>
…fix restore, parking reliability gate - Wire shutdownWorktreeTerminals → disposeParkedTerminalWatchersForPtyIds (byte-identical to #7214's terminals.ts hunk the extraction plan missed) so a slept/deleted worktree's teardown flush cannot mark unread or arm notification timers through a parked watcher; add a store-level regression test for the wiring. - Rebuild tests/e2e/helpers/orca-app.ts as main's version + only the orcaAppExtraEnv/orcaAppExtraArgs fixture additions — the wholesale copy from orca-performance had silently reverted the #7330 repo-load flake fix. Split the seeded-test-repo helpers into their own module to stay under max-lines. - Register the hidden-view parking byte-mode surface in the reliability gate manifest (experimental, renderer-unit layer, evidence from today's runs). - State the real shipped defaults in the four settings docstrings (types.ts) instead of #7214's "defaults to true" wording. Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com> Co-authored-by: Orca <help@stably.ai>
…2e helper - seeded-test-repo.ts: re-add the TEST_REPO_PATH_FILE import the round-1 split dropped (runtime-only ReferenceError on the worker's stale-repo fallback path — tests/e2e sits outside all typecheck configs), and drop the stray fixture JSDoc that came along with the extraction. Fallback verified by invoking createSeededTestRepo directly. - types.ts: qualify the two See-references to authority docs that ship with PR #7214 rather than this branch. Co-authored-by: Orca <help@stably.ai>
…ses not shipped) The header was adapted for the standalone extraction but two body sections still called fact mode "(default)" and phases 3-5 "(all shipped)" — the exact byte-mode-pinning confusion this PR guards against. Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com> Co-authored-by: Orca <help@stably.ai>
|
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:
📝 WalkthroughWalkthroughThis PR adds terminal hidden-view parking, which unmounts hidden terminal pane UI while keeping PTY/session side effects alive through parked watchers and sidecars. It also adds new settings and IPC surfaces, shared side-effect fact types, cold-parking policy and lifecycle wiring, shared agent-title and GitHub-link refactors, E2E/debug support, a reliability gate, reference documentation, and expanded unit/E2E coverage. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
tests/e2e/global-setup.ts (1)
56-97: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick winDuplicate git-repo seeding logic vs. the new
seeded-test-repo.tshelper.
seeded-test-repo.ts's docstring says it was "Extracted from orca-app.ts (fixture host)" andcreateSeededTestRepo()there implements the exact same git init/config/README/CLAUDE.md/package.json/.gitignore/src/index.ts/worktree-add sequence. This file still inlines its own copy instead of calling the shared helper, so any future change to the seed fixture (e.g. adding a file, changing worktree naming) has to be made in two places or they will silently drift.♻️ Proposed consolidation
- // ── 2. Create a seeded test git repo ─────────────────────────────── - // Why: each test run gets its own git repo so the suite is fully - // idempotent. No test depends on whatever repos the user has open. - // Why: realpathSync so the seeded path matches the store's repo.path on - // macOS, where os.tmpdir() (/var/...) symlinks to /private/var/... and the - // app canonicalizes repo.path via `git rev-parse --show-toplevel` on add. - const testRepoDir = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-repo-'))) - - execSync('git init', { cwd: testRepoDir, stdio: 'pipe' }) - ... - writeFileSync(TEST_REPO_PATH_FILE, testRepoDir) - console.error(`[e2e] Test repo created at ${testRepoDir}`) + // Why: each test run gets its own git repo so the suite is fully + // idempotent. No test depends on whatever repos the user has open. + const testRepoDir = createSeededTestRepo() + console.error(`[e2e] Test repo created at ${testRepoDir}`)src/renderer/src/store/slices/terminals.ts (1)
1845-1845: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winDispose parked PTY watchers during agent hibernation
shutdownCompletedAgentPaneForHibernationcan still hit background tabs, and parked tabs remain tracked by the parked-watcher registry.unregisterPtyDataHandlersalone won’t stop those byte watchers from seeing the final stop/kill flush; mirrorshutdownWorktreeTerminalshere and disposeshutdownPtyIdswatchers in both shutdown branches.
🧹 Nitpick comments (4)
tests/e2e/helpers/seeded-test-repo.ts (1)
13-29: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low valueStatic-analysis command-injection flags are false positives here.
Both
ast-grepand OpenGrep flag theexecSynccalls (isValidGitRepo'sgit rev-parse, andgit worktree add "${worktreeDir}") as command-injection risks. The interpolated values (repoPathused only ascwd, andworktreeDirbuilt fromos.tmpdir()+randomUUID()) are internally generated by the test harness, not attacker/user-controlled input, so there is no actual injection surface.If you want to fully silence the linters rather than suppress them,
execFileSync('git', ['worktree', 'add', worktreeDir, '-b', 'e2e-secondary'], { cwd: testRepoDir, stdio: 'pipe' })avoids shell interpolation entirely.Also applies to: 37-63
Source: Linters/SAST tools
tests/e2e/terminal-hidden-view-parking.spec.ts (1)
135-146: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the duplicated parking test helpers into a shared module.
skipUnlessParkingWired,readTerminalTabViewState,createActiveTerminalTab, andenableTerminalParkingare re-implemented nearly identically interminal-parked-memory.spec.ts(lines 71-82, 91-99, 122-148, 257-265). TheenableTerminalParkingcomment even explicitly says "Same mutation path as the kill-switch test in terminal-parked-memory.spec.ts," acknowledging the duplication. Consolidating these into a sharedtests/e2e/helpers/terminal-parking.tswould prevent the two specs from silently diverging as the parking machinery evolves.#!/bin/bash rg -n 'function (skipUnlessParkingWired|readTerminalTabViewState|createActiveTerminalTab|enableTerminalParking)' tests/e2eAlso applies to: 167-176, 209-231, 152-160
src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts (1)
238-241: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated mode-2031 reply expression.
mode2031SequenceFor(resolveTerminalColorSchemeMode(settings, getSystemPrefersDark()))is duplicated verbatim here and inparked-terminal-mode2031-responder.ts(lines 47-48). Consider extracting a small shared helper (e.g.sendMode2031ReplyFor(sendInput, settings)) inshared/terminal-color-scheme-protocol.tsso both responder paths stay in lockstep if theme-resolution logic changes.♻️ Proposed shared helper
+// shared/terminal-color-scheme-protocol.ts +export function sendMode2031Reply( + sendInput: (data: string) => void, + settings: Pick<GlobalSettings, 'theme'> | null | undefined +): void { + sendInput(mode2031SequenceFor(resolveTerminalColorSchemeMode(settings, getSystemPrefersDark()))) +}- const sendMode2031Reply = (): void => { - const settings = useAppStore.getState().settings - sendInput(mode2031SequenceFor(resolveTerminalColorSchemeMode(settings, getSystemPrefersDark()))) - } + const sendMode2031Reply = (): void => + sendMode2031ReplyFor(sendInput, useAppStore.getState().settings)src/shared/agent-title-identity.ts (1)
69-108: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider a data-driven table for the agent-name lookups.
The repeated
titleHasAgentName(title, 'x') → 'Y'blocks could be collapsed into an ordered array of[key, label]pairs and a loop, which would shrink this chain and make future agent additions a one-line change.♻️ Proposed refactor
- if (titleHasAgentName(title, 'codex')) { - return 'Codex' - } - if (titleHasAgentName(title, 'openclaude')) { - return 'OpenClaude' - } - if (titleHasAgentName(title, 'copilot')) { - return 'GitHub Copilot' - } - if (titleHasAgentName(title, 'grok')) { - return 'Grok' - } - if (titleHasAgentName(title, 'devin')) { - return 'Devin' - } - if (titleHasAgentName(title, 'antigravity') || AGY_AGENT_NAME_RE.test(title)) { - return 'Antigravity' - } - if (titleHasAgentName(title, 'opencode')) { - return 'OpenCode' - } - if (titleHasAgentName(title, 'mimo')) { - return 'MiMo Code' - } - if (titleHasAgentName(title, 'aider')) { - return 'Aider' - } - // Why: match explicit names before Claude's generic braille heuristic. - if (titleHasAgentName(title, 'cursor')) { - return 'Cursor' - } + // Why: match explicit names before Claude's generic braille heuristic. + const NAMED_AGENT_LABELS: readonly [string, string][] = [ + ['codex', 'Codex'], + ['openclaude', 'OpenClaude'], + ['copilot', 'GitHub Copilot'], + ['grok', 'Grok'], + ['devin', 'Devin'], + ['opencode', 'OpenCode'], + ['mimo', 'MiMo Code'], + ['aider', 'Aider'], + ['cursor', 'Cursor'] + ] + for (const [key, label] of NAMED_AGENT_LABELS) { + if (titleHasAgentName(title, key)) { + return label + } + } + if (AGY_AGENT_NAME_RE.test(title)) { + return 'Antigravity' + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: a174d5fd-e8ce-45fc-ac2b-2125dadccbf7
📒 Files selected for processing (51)
config/reliability-gates.jsoncdocs/reference/terminal-hidden-view-parking.mdsrc/main/ipc/settings.test.tssrc/main/ipc/settings.tssrc/preload/api-types.tssrc/preload/e2e-config.tssrc/preload/index.tssrc/renderer/src/components/Terminal.tsxsrc/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsxsrc/renderer/src/components/terminal-pane/agent-task-complete-policy.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-mode2031-responder.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/terminal-hidden-delivery-gate.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-parked-tab-watchers.test.tssrc/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.tssrc/renderer/src/components/terminal-pane/terminal-parked-watcher-registry.tssrc/renderer/src/components/terminal-pane/terminal-parking-byte-mode-guard.test.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/terminal-side-effect-facts-handler.test.tssrc/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.tssrc/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.tssrc/renderer/src/env.d.tssrc/renderer/src/lib/github-links.tssrc/renderer/src/store/slices/terminal-shutdown-parked-watcher-dispose.test.tssrc/renderer/src/store/slices/terminals.tssrc/renderer/src/store/slices/worktree-helpers.tssrc/shared/agent-detection.tssrc/shared/agent-title-core.tssrc/shared/agent-title-identity.tssrc/shared/agent-title-status.tssrc/shared/constants.tssrc/shared/e2e-config.tssrc/shared/github-links.tssrc/shared/terminal-github-pr-link-detector.test.tssrc/shared/terminal-github-pr-link-detector.tssrc/shared/terminal-side-effect-facts.tssrc/shared/types.tstests/e2e/global-setup.tstests/e2e/global-teardown.tstests/e2e/helpers/orca-app.tstests/e2e/helpers/seeded-test-repo.tstests/e2e/terminal-hidden-view-parking.spec.tstests/e2e/terminal-parked-memory.spec.tstests/e2e/terminal-sleep-wake-restore.spec.ts
| // Why: production cold-park hysteresis is 30s with a multi-minute hot-retain | ||
| // window. The fast-park override must be scoped to THIS spec's app launches — | ||
| // mutating process.env at module scope leaked into later specs when a worker | ||
| // reloaded files without replaying this file's afterAll. | ||
| const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 | ||
|
|
||
| test.use({ | ||
| orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
PARKING_DELAY_MS silently discards an explicit 0 override.
Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 treats an explicit "0" env value the same as "unset" (0 is falsy), forcing 500ms instead of the requested 0ms delay. It also masks non-numeric values (NaN || 500) as a side effect, which happens to work but is unintentional.
🐛 Proposed fix
-const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500
+const parsedParkingDelayMs = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS)
+const PARKING_DELAY_MS = Number.isFinite(parsedParkingDelayMs) ? parsedParkingDelayMs : 500The identical pattern exists in terminal-parked-memory.spec.ts line 22.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Why: production cold-park hysteresis is 30s with a multi-minute hot-retain | |
| // window. The fast-park override must be scoped to THIS spec's app launches — | |
| // mutating process.env at module scope leaked into later specs when a worker | |
| // reloaded files without replaying this file's afterAll. | |
| const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 | |
| test.use({ | |
| orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } | |
| }) | |
| // Why: production cold-park hysteresis is 30s with a multi-minute hot-retain | |
| // window. The fast-park override must be scoped to THIS spec's app launches — | |
| // mutating process.env at module scope leaked into later specs when a worker | |
| // reloaded files without replaying this file's afterAll. | |
| const parsedParkingDelayMs = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) | |
| const PARKING_DELAY_MS = Number.isFinite(parsedParkingDelayMs) ? parsedParkingDelayMs : 500 | |
| test.use({ | |
| orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } | |
| }) |
shutdownCompletedAgentPaneForHibernation already unregisters live pane handlers before pty.kill to prevent phantom notifications from the teardown flush, but a parked tab's byte watcher rides the dispatcher sidecar that call does not touch. Dispose it after a successful kill — deliberately not before: a failed kill leaves the session running and it must keep its watcher. This is the hibernation analog of the worktree-shutdown wiring and does not exist in PR #7214 yet (worth adopting there); regression tests cover both the success and kill-failure paths. Also: "afterwards" → "afterward" in the parking doc (static analysis). Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com> Co-authored-by: Orca <help@stably.ai>
fc23a00 to
badd6f2
Compare
|
CodeRabbit follow-up (all four items triaged):
|
Resolves the github-links.ts conflict with #7371: the parsing-core pieces (GitHubIssueOrPRLink type, parseGitHubIssueOrPRLink signature) land in src/shared/github-links.ts where this branch moved the core, and the renderer-side pieces (HTTP_URL_PREFIX_RE, GitHubLinkQuery.directLink, normalizeGitHubLinkQuery) stay in the lib shim. Co-authored-by: Orca <help@stably.ai>
The seedTestRepo fixture matched store repo/worktree paths against the seeded realpath with strict string equality, which fails on Windows when main's canonicalized path differs in separators or drive-letter case — every spec then dies at "Expected e2e repo to be loaded" before its own assertions (observed on a real Windows validation run of this branch). Compare through shared/cross-platform-path's normalizeRuntimePathForComparison instead, matching node-side so the shared helper is used verbatim. Co-authored-by: Orca <help@stably.ai>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
tests/e2e/helpers/orca-app.ts (2)
268-301: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider extracting the repeated normalized-repo-lookup logic.
Both polls fetch
store.getState().repos, map to{id, path}, and find a match vianormalizeRuntimePathForComparison(candidate.path) === repoPathKey. A small shared helper (e.g.findRepoByNormalizedPath(page, repoPathKey)) would remove the duplication, though the two callers differ slightly in fetch timing and return type.Also applies to: 327-352
383-391: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUndocumented
startsWithfallback in worktree matching.The prefix-match fallback (
worktreePathKey.startsWith(repoPathKey)) is a non-obvious heuristic beyond the exact-match case used elsewhere in this same function (line 288, 339). Since the secondary worktree is created as a sibling directory increateSeededTestRepo(not nested under the repo path), it's unclear what case this fallback is meant to catch. A short comment explaining the reasoning would help future maintainers, and reduces risk that this silently matches an unintended worktree in edge cases (e.g., a temp-dir path with a shared prefix).As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 993b4bff-126b-4552-9e3d-50f93f8fae0d
📒 Files selected for processing (1)
tests/e2e/helpers/orca-app.ts
… PowerShell) The parked bell/title test was the suite's only nested-escaped-quote `node -e "...\"...\""` invocation; Windows PowerShell 5.1 mangles that argv form, so the payload was never emitted and the title assertion saw ConPTY's spawn-time powershell.exe title (observed on a real Windows validation run — the other five tests, which all use script files or quote-free inline forms, passed). Emit through a script file like the rest of the suite, and re-assert the OSC 0 title on an interval so conhost's own title updates cannot race the store assertion. Co-authored-by: Orca <help@stably.ai>
…parking ON Resolve agent-detection.ts split-vs-monolith conflict by porting main's Gemini/Pi title fixes (#5270 masquerade guard, isLegacyPiCompatibleTitle) into the split module agent-title-core.ts; keep the compatibility barrel. Flip terminalHiddenViewParking default OFF->ON (byte mode). The three authority/gate/query flags stay false (no main emitter in this build). Update the byte-mode guard test, docs, reliability gate, and e2e comments. Co-authored-by: Orca <help@stably.ai>
…e gates) Move the parking toggle to Settings → Experimental and default it OFF: - constants.ts default false; gates read `settings.terminalHiddenViewParking === true` (was `!== false`) so absent/null settings (e.g. pre-hydration, when the store initializes settings=null) resolve OFF, not ON. - New Experimental UI toggle (TerminalParkingExperimentalSetting) + search entry, extracted into focused modules to satisfy max-lines. - Restore default-off wording in types.ts, docs, reliability gate, guard test. - #7214 reconcile: restore `!== false` gates + default-on when graduating. OFF-path audited as a no-op: unmount capture is bounded and cleaned by ungated sync/prune; the getSync blocking IPC is only used inside the parked watcher (never starts when off); shutdown dispose + pty-exit defer are no-ops on an empty registry; the initialAgentTitle param is unset on live callers. Co-authored-by: Orca <help@stably.ai>
Co-authored-by: Orca <help@stably.ai>
Parking memory validation — per-process, under sustained loadHEAD tested:
Steady-state flood, per process (mean of 5 samples during the hold, MB)
Renderer-internal at the same moments: OFF The four questions, answered1. Which process grows fastest / largest under load?
2. Does parking reduce the renderer working set at the OS level (and/or GPU/total)? — YES, all three. 3. Does parking keep the app responsive/alive longer? — Yes, with more headroom. 4. Reframe — is the renderer even the biggest/fastest grower, or is parking only partial? Bottom line: parking bends the renderer curve decisively at the OS level (−43% renderer RSS, −42% total, +300 MB avg free) at matched 16-terminal load — real relief, aimed at the right (largest) process — but it's a partial fix because the main process remains a slow monotonic grower it doesn't address. |
…ort guard on e2e worktree prefetch Co-authored-by: Orca <help@stably.ai>
…en-pane-parking # Conflicts: # tests/e2e/helpers/orca-app.ts
While parked, the dispatcher buffers every chunk (no primary handler) that the parked watcher has already consumed for side effects. Reveal's registerPtyDataHandler drained that backlog through the live output processor with attention enabled — double-firing bell/completion the watcher already dispatched — and wrote up to 512KiB into the fresh xterm only for the snapshot restore's 2J/3J clear to wipe it. Dispose now drops the backlog: the snapshot owns content, the watcher owned the side effects. Bytes arriving after dispose still buffer and drain normally. Also reword the parked-exit comments to state the real dead-leaf reveal behavior (fresh shell, app-restart restore semantics) instead of the aspirational 'handles dead PTYs per leaf'. Co-authored-by: Orca <help@stably.ai>
|
Closing as superseded by #7448, which lands the same renderer-side fix — unmount hidden terminal panes' xterm/DOM/WebGL trees, keep the PTY and its bell/title/completion side effects alive, remount on reveal — with a more robust restore path:
Same experimental opt-in, default-OFF posture as this PR, and the same Windows OOM motivation ( @Jinwoo-H — this PR was your #7214 parking slice shipped early; with #7448 landing instead, the parking phase of |
Fixes the Windows renderer OOM/hang under multi-agent load (#7175 / STA-476 diagnostic chain) by landing the hidden-view parking sub-feature of @Jinwoo-H's terminal performance initiative (
#7214) as a standalone, byte-mode-only slice. All parking production code is copied byte-identical fromorca-performanceso#7214later merges over it as a no-op — this is Jinwoo's feature shipped early, not a fork.What changes: terminal panes hidden for ≥30s unmount their xterm/DOM/WebGL subtree; a pane-less byte watcher keeps bell / title / agent-completion / PR-link side effects alive per PTY (the missing piece that got the naive unmount reverted); revealing the worktree remounts panes through the existing tab-move reattach path. Measured on the shipped e2e memory spec: 8 hidden tabs → 1 live xterm/PaneManager instead of 9.
What does NOT change (read this before flipping flags):
terminalHiddenViewParking === true(Settings → Experimental). Zero behavior change out of the box; opting in parks hidden panes in byte mode, and the byte watcher keeps side effects alive so notifications are unaffected.#7214's fact-mode emitter is not here, soterminalMainSideEffectAuthority/terminalHiddenDeliveryGate/terminalModelQueryAuthorityare pinnedfalseinconstants.ts. Getting this wrong (authority on without the emitter) would silently kill parked-pane notifications; a guard test + a runtime park-refusal tripwire pin it.#7214lands its emitter (both marked in-code): (1)constants.ts— take#7214'struevalues for the three authority/gate flags; (2)terminal-parked-tab-watchers.ts— delete the extraction-onlywouldParkedWatcherFactModeBeSilenttripwire (a rebase will NOT conflict on it, so it must be removed deliberately; it's harmless-but-dead once the channel exists). Every other parking production file is byte-identical toorca-performance.isSnapshotBackedTerminalPtyexclusion, tested).Windows validation — prompt for a Windows agent on this branch
Validation: COMPLETE. Correctness on real Windows + macOS (real Claude Code park/reveal/input/resize/notify-while-parked, no garble, no lost output); definitive per-process memory run on Windows at HEAD
7047877d0; default-OFF no-op confirmed on Windows (fresh profile →terminalHiddenViewParking === false, nothing parks).Harness: parking e2e spec 4/4 (including the 25-cycle byte-identical park/reveal test); unit suites green.
Real Claude Code park/reveal (macOS + Windows): parked a live Claude TUI, revealed it — pixel-faithful restore, unsubmitted draft preserved, first keystroke registered immediately, and a mid-park resize reflowed the TUI cleanly to the new width. Claude completed while parked → tab title took the
✳idle prefix + sidebar attention/unread fired (the pane-less watcher parsed Claude's completion while unmounted); reveal restored the full conversation including the model response.Per-process memory under sustained load (definitive run, 16 terminals / 8 worktrees, ~180s heavy PTY flood, real memory pressure ~4.1GB free). OS-level private working set walked from the main process down its child tree, sampled through the hold, parking ON vs OFF at matched load:
Renderer-internal at the same moments: xterms 16 → 1, DOM ~2450 → ~968 (−60%). ≈16MB real renderer RSS reclaimed per parked terminal; scales ~linearly with terminal count (far larger at 40–60). Renderer is the single largest process, so parking targets the right one. Neither run crashed or went "Not responding" (the low-RAM box was not pushed to OOM by design).
Two important caveats from this run — (1) an earlier lighter run (12 terminals / 90s / low pressure) showed renderer RSS flat; that was a low-pressure measurement artifact — Chromium only returns freed pages to the OS under pressure, which is exactly the crash regime, so the −43% above is the representative result. (2) The main process creeps monotonically in both runs (141→358 OFF, 116→318 ON) and parking does not address it — parked PTYs still buffer in main. Parking is therefore a large but partial fix; the main-side buffer drift is tracked as a separate diagnose-first follow-up (it's the fact-mode phase this byte-mode build excludes).
Live parked-agent proof (the STA-476 scenario): a Codex agent's tab parked while the agent was working; it completed while parked; unread attention fired (worktree + tab + pane — written by the notification dispatch path itself, proving the parked watcher delivered the completion); reveal restored content on the same PTY and accepted typed input immediately (~2.7s reveal under 24-PTY load; quick switches never pay this thanks to hot-retain). OS toast was correctly suppressed for a focused window (unread evidence proves the dispatch ran).
Two Windows-only test-infra fixes came out of validation and are on the branch: fixture path canonicalization (
ed552cf28) and script-file payload emission replacing a PowerShell-manglednode -eform (20390d7fc).Earlier prompt for re-running Windows validation (kept for reference):
Spawn a Windows agent on branch
brennanb2025/oom-hidden-pane-parking(git pull first) with this prompt:Extraction inventory (vs plan)
terminal-pane/+Terminal.tsx/TerminalPaneOverlayLayer.tsx(all byte-identical toorca-performance), 1 hunk each inuse-terminal-pane-lifecycle.ts(unmount capture) andpty-transport.ts(initialAgentTitleseed).#7214: theagent-title-*split ofagent-detection.ts(provides the tracker'sinitialTitleparam),shared/github-links.ts+shared/terminal-github-pr-link-detector.tsmoves, types-onlyshared/terminal-side-effect-facts.ts,settings:get-syncsync IPC +settings.getSyncpreload, e2e config/env plumbing.pty.onSideEffect/getSideEffectSnapshot/setHiddenRendererPty(no preload implementations —#7214makes them required + implemented).pty-delivery-interest,terminal-view-attributes-publisher,pty-model-restore-channel,terminal-parser-handler-guard,shared/terminal-output-side-effects, the bell-detector shared move, all fact-mode preload bridges.Validation
pnpm run lint(oxlint, switch-exhaustiveness, reliability-gate manifest, localization) — green.es.jsonbreakage, since fixed on main; unrelated to this branch.)terminal-hidden-view-parking.spec.ts4/4 (park + byte-identical TUI restore across 25 park/reveal cycles; bell/title side effects live while parked; exclusions honored),terminal-parked-memory.spec.ts2/2,terminal-sleep-wake-restore.spec.tspass. The specs opt in viaupdateSettingssince this build defaults the flag off.terminal-session.hidden-view-parking-byte-mode(experimental) inconfig/reliability-gates.jsoncwith today's evidence runs.orca-app.ts, isolated re-runs 3/3 pass, not PR-blocking CI); untouched-default proof — a fresh profile without the settings key resolvesterminalHiddenViewParkingtofalseend-to-end (defaults merge before persisted settings), hidden tabs keep their pane manager,parkedTabIds()stays empty; reliability-gate command green (115 tests). Verdict: land.Risks, residual observations, and non-goals
Headline status: implemented, experimental opt-in (default OFF, byte mode). The parking mechanism is fully implemented and e2e-proven, and exposed under Settings → Experimental. Out-of-the-box behavior is unchanged; users opt in to get the memory relief while the restore path soaks on real multi-agent Windows workspaces. The three authority/gate flags remain
false— no main-process emitter ships here.Reveal-time side-effect parity (fixed in-branch). While parked, the renderer dispatcher buffers chunks the watcher already consumed; the reveal drain used to replay that backlog through the live processor (double-firing bell/completion) before the snapshot's clear wiped its content. The watcher now drops the backlog on dispose — snapshot owns content, watcher owned the side effects (unit + byte-for-byte e2e pinned).
Accepted residual: parked split whose PTY exits cleanly while parked. With no PaneManager, the tab close is deferred to protect surviving siblings; on reveal the dead leaf comes back as a fresh shell (same as app-restart restore) instead of closing like a mounted pane's leaf. Niche (split + exit-while-parked); tracked as a follow-up.
Accepted residual: hibernation kill flush. Parked watchers are disposed only after a successful hibernation kill (a kill failure must keep the watcher, or the tab goes silent — the fatal failure mode). Main's pre-exit flush can therefore mark a rare phantom unread on a hibernated pane; timers are cleared by the exit-time dispose so no OS notification fires.
OFF path = no-op (reviewed hard)
Because this defaults off, the code that runs for non-opters was audited to be behavior-identical to pre-parking main:
=== true(not!== false), so a null/undefined settings object — e.g. the pre-hydration window where the store initializessettings = null— resolves off rather than transiently on.capturedPanesByTabId) is bounded and cleaned bysyncParkedTerminalTabWatchers(closed tabs) andpruneParkedTerminalWatchers(dead worktrees), both of which run ungated by the flag — no leak when off.settings:get-syncIPC is consulted only inside the parked byte watcher, which never starts when off — no new blocking IPC on any live/hot path.disposeParkedTerminalWatchersForPtyIdsand theshouldDeferParkedPtyExitTabClosePTY-exit guard are no-ops on an empty watcher registry, so shutdown and tab-close behave exactly as before.initialAgentTitletransport param is unset on all live callers (only the parked watcher passes it), so the live output-processor path is byte-identical.agent-detectionsplit andgithub-linksmove are import-consistent refactors (full typecheck green; existing suites cover them).#7214).#7330repo-load retry (restored in review round 1); passes consistently since.types.tsfield docs were corrected to state this build's real defaults (third, comment-only divergence from#7214).Process
This PR ran Brennan's PR process end to end: design verification of the handoff plan against
orca-performance(found and closed 4 plan gaps: the agent-title split dependency,shared/terminal-side-effect-facts.ts, the github-links cascade, the e2e config seam), implementation, independent completeness verification (10/10 pass), perf audit (no blocking issues; default-off is zero-timer), and a two-at-a-time adversarial review loop: round 1 found 2 real issues (missedterminals.tsshutdown-dispose wiring from #7214; the e2e fixture copy reverting#7330), round 2 found 2 in round 1's own fix (missing import in the split helper; doc refs), round 3 returned clean from both reviewers. Each fix landed with a regression test where applicable.Refs: #7175, STA-476, extracted from #7214. cc @Jinwoo-H — files are copied verbatim from your branch (co-authored commits); the
constants.tsbyte-mode pinning block and the doc's status paragraph are the only intentional divergences, called out inline.