Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
ff5833d
Stop hidden terminal panes from exhausting renderer memory (hidden-vi…
brennanb2025 Jul 4, 2026
5312357
Route e2e global-setup logs to stderr so JSON reporters stay parseabl…
brennanb2025 Jul 4, 2026
80a4487
Address review round 1: shutdown watcher disposal, e2e fixture flake-…
brennanb2025 Jul 4, 2026
15ec98b
Address review round 2: restore TEST_REPO_PATH_FILE import in split e…
brennanb2025 Jul 4, 2026
e39355d
Align the parking doc body with this build (byte mode only, #7214 pha…
brennanb2025 Jul 4, 2026
badd6f2
Dispose parked watchers on agent-pane hibernation kill (CodeRabbit)
brennanb2025 Jul 4, 2026
1d4e70e
Merge origin/main into brennanb2025/oom-hidden-pane-parking
brennanb2025 Jul 4, 2026
ed552cf
Fix e2e fixture repo matching on Windows (canonicalized-path comparison)
brennanb2025 Jul 5, 2026
20390d7
Make the parked side-effects e2e spec emit via a script file (Windows…
brennanb2025 Jul 5, 2026
e152f98
Merge origin/main into brennanb2025/oom-hidden-pane-parking; default …
brennanb2025 Jul 5, 2026
964bf15
Make hidden-view parking an experimental opt-in (default off, === tru…
brennanb2025 Jul 5, 2026
7047877
Reword parking toggle copy: lead with audience, drop fidelity caveat
brennanb2025 Jul 6, 2026
ad99976
Sync localization catalog for parking settings keys; restore best-eff…
brennanb2025 Jul 7, 2026
425fb71
Merge remote-tracking branch 'origin/main' into brennanb2025/oom-hidd…
brennanb2025 Jul 7, 2026
8a4a652
Clear a parked PTY's pre-handler backlog on watcher dispose
brennanb2025 Jul 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions config/reliability-gates.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -2134,6 +2134,106 @@
"Buffer-clean, pixels-stale variants are otherwise invisible to every buffer oracle in the manifest."
],
"demotionRule": "Drop from the golden suite back to nightly diagnostic if diff thresholds cannot be kept stable across CI runners."
},
{
"id": "terminal-session.hidden-view-parking-byte-mode",
"title": "Parked hidden terminal panes keep side effects alive in byte mode",
"maturity": "experimental",
"protection": "partial",
"owner": "terminal-runtime",
"layer": "renderer-unit",
"surfaces": [
"terminal lifecycle",
"hidden-to-visible resume",
"notifications"
],
"platforms": [
"macos",
"linux",
"windows"
],
"providers": [
"local",
"daemon"
],
"coveredPlatforms": [
"macos"
],
"coveredProviders": [],
"coverageNotes": "Local macOS evidence on the standalone byte-mode extraction of PR #7214's hidden-view parking. Three Electron e2e specs (terminal-hidden-view-parking, terminal-parked-memory, terminal-sleep-wake-restore) passed locally but live in the scheduled E2E suite, not PR-blocking CI.",
"motivatingLinks": [
"https://github.com/stablyai/orca/issues/7175",
"https://github.com/stablyai/orca/pull/7214"
],
"invariant": "A cold-parked hidden terminal tab keeps bell, title, and agent-completion side effects firing while unmounted, restores its view from the session snapshot on reveal, and the parked watcher never selects fact mode in a build whose preload lacks the pty:sideEffect channel.",
"oracle": "The byte-mode guard test asserts all four parking/authority defaults ship false, that the authority predicate selects byte mode under those defaults, and that park coverage is refused when authority is configured on without the channel; the watcher suites assert parked-side-effect policy parity with the mounted path.",
"commands": [
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-parking-byte-mode-guard.test.ts src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.test.ts"
],
"testFiles": [
"src/renderer/src/components/terminal-pane/terminal-parking-byte-mode-guard.test.ts",
"src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts",
"src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts",
"src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts",
"src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.test.ts"
],
"assertionRefs": [
{
"file": "src/renderer/src/components/terminal-pane/terminal-parking-byte-mode-guard.test.ts",
"assertions": [
"getDefaultSettings ships terminalHiddenViewParking, terminalMainSideEffectAuthority, terminalHiddenDeliveryGate, and terminalModelQueryAuthority all false",
"the side-effect authority predicate selects byte-parser mode under the shipped defaults",
"park coverage is refused when authority is configured on without window.api.pty.onSideEffect",
"park coverage is allowed in byte mode without any channel"
]
},
{
"file": "src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts",
"assertions": [
"a parked watcher fires bell unread and grace-delayed OS notification from raw bytes exactly like the mounted path",
"a working agent seeded via initialAgentTitle still produces its working-to-idle completion while parked",
"dispose clears watcher-written runtime title slots and stops all side effects"
]
}
],
"evidenceRuns": [
{
"date": "2026-07-04",
"runner": "local",
"platform": "macos",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-parking-byte-mode-guard.test.ts src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts src/renderer/src/components/terminal-pane/terminal-side-effect-facts-handler.test.ts",
"result": "passed",
"durationSeconds": 2,
"summary": "All parking unit suites plus the byte-mode guard passed on the extraction branch; the three parking Electron e2e specs also passed locally the same day (8 parked tabs collapsed to 1 live xterm)."
}
],
"runtimeBudget": {
"p95Seconds": 10,
"scope": "local unit test"
},
"flakeHistory": {
"status": "unknown",
"evidence": "New gate registered with the extraction PR; needs soak history before blocking promotion."
},
"redGreenEvidence": {
"status": "partial",
"evidence": "The guard test fails if any of the four defaults flips true or the coverage tripwire is removed; the parked-side-effect suites fail if watcher policy diverges from the mounted path. Needs a saved intentional-break artifact before blocking promotion."
},
"performanceBudget": {
"required": true,
"evidence": "Default-off ships zero parking timers and zero watchers (policy returns null recheck delays when disabled, pinned by terminal-hidden-view-parking.test.ts). The terminal-parked-memory e2e spec measures the parked-vs-retained xterm counts and heap when the flag is on."
},
"promotionCriteria": [
"Run in soak for at least 100 consecutive passes or 14 days across required CI platforms.",
"Confirm the memory relief and notification correctness on a real Windows multi-agent workspace with parking opted in.",
"Land the three parking e2e specs in the scheduled E2E suite with green history before flipping terminalHiddenViewParking on by default."
],
"knownGaps": [
"The three Electron e2e specs are scheduled-suite only, not PR-blocking CI.",
"Windows and Linux runs pending; parking itself ships default-off until the soak completes.",
"Fact mode (main-process side-effect authority) is intentionally absent until PR #7214 lands its emitter; the guard pins byte mode until then."
],
"demotionRule": "Demote or quarantine if the gate flakes once without a product bug or harness bug filed to the owner."
}
]
}
122 changes: 122 additions & 0 deletions docs/reference/terminal-hidden-view-parking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Terminal Hidden View Parking

Status: Shipped standalone (byte mode only, extracted from PR #7214), kill
switch `terminalHiddenViewParking` **default off** — opt-in until the memory
win is confirmed in a soak, then a follow-up flips it on. The companion doc
`terminal-model-view-contract.md` (invariants this design extends and the full
phase list) ships with PR #7214 together with the fact-mode main emitter; in
this build `terminalMainSideEffectAuthority` must stay `false` (see
`src/shared/constants.ts`).

## Problem

Hidden terminal panes keep a full renderer xterm instance alive (buffer,
scrollback, DOM, addons). At many-worktree scale this is the dominant renderer
memory cost, and it forces every hidden byte through renderer-side write/skip
decisions. The main-process model (daemon + runtime headless emulators) already
ingests every byte and can serve restorable snapshots, so the renderer view for
a long-hidden pane is redundant state.

A previous attempt shipped and was reverted the same day. The post-mortem
finding: parking unmounted the pane component, which also tore down the
renderer's PTY byte parsers — and those parsers are the only source of bell
notifications, title-transition agent-complete notifications, and tab titles.
A parked worktree whose agent finished would never notify. This design keeps
those side effects alive while parked.

## Design

### Park policy (renderer)

A pure policy module decides which hidden terminal tabs may park:

- Cold-park hysteresis: a tab must be hidden for 30s before parking.
- Hot-retain working set: recently visible worktrees/tabs are retained
(5 minutes, bounded count) so quick tab switches never pay a re-hydrate.
- Eligibility excludes: visible panes, hidden-measuring startup probes,
activity-portal panes, tabs with pending startup commands or pending
activation spawns, floating-panel tabs, and any tab whose PTY is not
snapshot-backed (remote-runtime `remote:` PTYs and SSH PTYs are excluded).
- Kill switch: `settings.terminalHiddenViewParking === false` disables parking
entirely.

### Park mechanics

Parking a tab unmounts its `TerminalPane` React subtree (the overlay layer
renders null for parked tabs). This is the same teardown that tab-group moves
already exercise: transports detach but the PTY session, daemon model, and tab
state all survive. The xterm instance, its buffers, DOM, and WebGL/addon
resources are released.

### Parked watcher (the piece the reverted attempt lacked)

While a tab is parked, a pane-less watcher
(`parked-terminal-byte-watcher.ts`) keeps the pane's side effects alive. Its
consumption mode is decided once at watcher start:

- **Main side-effect authority on (arrives with PR #7214; forced off in this
build):** the watcher is purely
fact-driven — it registers exactly one `pty:sideEffect` fact consumer and
parses no bytes. Titles, agent working/idle/exited transitions, BEL
attention, and PR links arrive as main-tracker facts and drive the same
policy callbacks a mounted pane uses. With the hidden-delivery gate also on,
the watcher marks the PTY hidden so main stops renderer byte delivery
entirely; the DECSET 2031 color-scheme subscribe arrives as main's
`2031-subscribe` fact and the watcher replies out-of-band via
`transport.sendInput`.
- **Kill switch off (this build's only mode — see the status note above):**
the watcher subscribes to raw bytes through the
dispatcher sidecar mechanism (the same mechanism background agent launches
use) and runs the transport-level byte parsers with no xterm — OSC 0/1/2
titles (all-titles ordering, live-path normalization), the title-transition
agent tracker (completion notification, prompt-cache timer), the OSC-aware
stateful BEL detector, the GitHub PR link scan, and a dedicated DECSET 2031
byte responder (`parked-terminal-mode2031-responder.ts`, whose
`subscribeToPtyData` registration doubles as the delivery-interest signal).

The two modes drive one shared policy-callback block, so flipping the kill
switch never changes notification semantics. Main's synthetic
agent-title/permission frames feed the main tracker directly and arrive as
facts; the legacy synthetic `pty:data` copy exists only in kill-switch-off
mode.

Out of scope while parked: OSC 52 clipboard writes. Terminal queries inside
hidden-dropped chunks are answered by main's model responder
(`terminal-query-authority.md`, ships with PR #7214); in kill-switch-off byte
mode only the 2031 reply is answered and Command Code output is not scraped,
matching the pre-gate status quo.

### Reveal

Revealing a parked tab remounts the pane subtree and rides the existing
reattach path: fresh xterm via `openTerminal` (unicode provider activation
before any write), daemon model snapshot > relay replay > cold restore
precedence, replay-guarded so snapshot-embedded queries never answer, then
`POST_REPLAY_REATTACH_RESET` hygiene, fit, and PTY resize. The watcher is
disposed before the pane handlers re-register.

## Invariants

1. PTY reads never stop; parking only changes renderer-side view lifetime.
2. Bell, agent-completion, title, and PR-link side effects keep working while
parked (watcher parity tests).
3. Reveal shows model-correct output (visual gates: hidden TUI restore, long
table, rendering golden) and accepts input immediately.
4. Sleep/wake, pane close, and PTY restart while parked must not leak watchers
or strand parked state.
5. Memory: parked tabs hold no xterm buffers; renderer memory scales with
visible panes.

## Relation to later phases (ship with PR #7214, not this build)

Side-effect authority in main (Phase 3) replaces the watcher's byte parsing
with the `pty:sideEffect` fact consumer; the hidden-delivery gate (Phase 4)
stops hidden byte delivery in main, moving the parked 2031 reply from the
byte sidecar to the `2031-subscribe` fact; the model query responder
(Phase 5) answers queries in hidden-dropped chunks. None of that main-process
machinery exists in this build — the watcher's byte-parser mode is the only
mode until #7214 lands, and it remains the fallback behind the kill switches
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
afterwards. Parking still excludes
remote-runtime and SSH PTYs (no local snapshot to restore from); the watcher
would return as a byte parser only if remote-runtime tabs — whose bytes never
transit local main — ever became parkable.
21 changes: 20 additions & 1 deletion src/main/ipc/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
applyElectronProxySettingsMock,
browserWindowGetAllWindowsMock,
handleMock,
onMock,
previewGhosttyImportMock,
previewWarpThemeImportMock,
prepareLocalWorktreeRootsForReposMock,
Expand All @@ -14,6 +15,7 @@ const {
applyElectronProxySettingsMock: vi.fn(),
browserWindowGetAllWindowsMock: vi.fn(),
handleMock: vi.fn(),
onMock: vi.fn(),
previewGhosttyImportMock: vi.fn(),
previewWarpThemeImportMock: vi.fn(),
prepareLocalWorktreeRootsForReposMock: vi.fn(),
Expand All @@ -22,7 +24,7 @@ const {

vi.mock('electron', () => ({
BrowserWindow: { getAllWindows: browserWindowGetAllWindowsMock },
ipcMain: { handle: handleMock },
ipcMain: { handle: handleMock, on: onMock },
nativeTheme: { themeSource: 'system' }
}))

Expand Down Expand Up @@ -70,6 +72,7 @@ const store = {
describe('registerSettingsHandlers', () => {
beforeEach(() => {
handleMock.mockClear()
onMock.mockClear()
applyAppIconMock.mockClear()
applyElectronProxySettingsMock.mockClear()
applyElectronProxySettingsMock.mockResolvedValue({ source: 'settings' })
Expand All @@ -89,6 +92,22 @@ describe('registerSettingsHandlers', () => {
expect(channels).toContain('settings:previewGhosttyImport')
})

it('answers the synchronous settings read with the persisted settings', () => {
// Why: panes can bind PTYs before async hydration; the side-effect
// authority kill switch needs the persisted value synchronously.
store.getSettings.mockReturnValue({ terminalMainSideEffectAuthority: false })
registerSettingsHandlers(store as never)

const listener = onMock.mock.calls.find(
(call) => call[0] === 'settings:get-sync'
)?.[1] as (event: { returnValue: unknown }) => void
expect(listener).toBeTypeOf('function')

const event = { returnValue: undefined as unknown }
listener(event)
expect(event.returnValue).toEqual({ terminalMainSideEffectAuthority: false })
})

it('registers settings:previewWarpThemeImport handler', () => {
registerSettingsHandlers(store as never)
const channels = handleMock.mock.calls.map((call) => call[0])
Expand Down
9 changes: 9 additions & 0 deletions src/main/ipc/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ export function registerSettingsHandlers(
return store.getSettings()
})

// Why: terminal panes can bind PTYs before async settings hydration
// completes. The side-effect authority kill switch is consulted once at
// transport creation, so the renderer needs the persisted value
// synchronously or pre-hydration bindings would always pick main authority
// (terminal-side-effect-authority.md, migration switch).
ipcMain.on('settings:get-sync', (event) => {
event.returnValue = store.getSettings()
})

ipcMain.handle('settings:set', async (event, args: Partial<GlobalSettings>) => {
const sanitizedArgs = sanitizeRendererSettingsUpdate(args)
// Why: Floating Workspace grants are trusted only when written by the
Expand Down
18 changes: 18 additions & 0 deletions src/preload/api-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ import type {
MigrationUnsupportedPtyEntry
} from '../shared/agent-status-types'
import type { AgentInterruptInferenceRequest } from '../shared/agent-interrupt-intent'
import type { TerminalSideEffectBatch } from '../shared/terminal-side-effect-facts'
import type {
RuntimeBrowserDriverState,
RuntimeMobileSessionTabMove,
Expand Down Expand Up @@ -1155,6 +1156,11 @@ export type PreloadApi = {
ackData: (id: string, charCount: number) => void
setActiveRendererPty: (id: string, active: boolean) => void
setRendererPtyVisible: (id: string, visible: boolean) => void
/** Hidden-delivery gate (PR #7214): absent in this build — no main-process
* gate exists yet. Declared optional so gate-aware renderer code
* (parked-terminal byte watcher) typechecks; it only fires when the
* terminalHiddenDeliveryGate setting is on, which requires the emitter. */
setHiddenRendererPty?: (id: string, hidden: boolean) => void
hasChildProcesses: (id: string) => Promise<boolean>
getForegroundProcess: (id: string) => Promise<string | null>
getCwd: (id: string) => Promise<string>
Expand Down Expand Up @@ -1199,6 +1205,14 @@ export type PreloadApi = {
}) => void
) => () => void
onReplay: (callback: (data: { id: string; data: string }) => void) => () => void
/** Batched derived side-effect facts channel (PR #7214): absent in this
* build — main has no side-effect emitter yet. Declared optional so the
* renderer facts-handler typechecks and degrades to "no channel";
* terminalMainSideEffectAuthority defaults false until the emitter lands. */
onSideEffect?: (callback: (batch: TerminalSideEffectBatch) => void) => () => void
/** Title-only replay snapshot companion to onSideEffect (PR #7214):
* absent in this build for the same reason. */
getSideEffectSnapshot?: (id: string) => Promise<TerminalSideEffectBatch | null>
onExit: (callback: (data: { id: string; code: number }) => void) => () => void
onSerializeBufferRequest: (
callback: (data: {
Expand Down Expand Up @@ -1894,6 +1908,10 @@ export type PreloadApi = {
telemetryAcknowledgeBanner: () => Promise<void>
settings: {
get: () => Promise<GlobalSettings>
/** Synchronous persisted-settings read for startup decisions that cannot
* wait for async hydration (terminal side-effect authority). Blocking
* IPC — call sparingly. */
getSync: () => GlobalSettings | null
set: (args: Partial<GlobalSettings>) => Promise<GlobalSettings>
listFonts: () => Promise<string[]>
previewGhosttyImport: () => Promise<GhosttyImportPreview>
Expand Down
5 changes: 4 additions & 1 deletion src/preload/e2e-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,8 @@ const exposeStore = preloadEnv?.MODE === 'e2e' || isEnvFlagEnabled(preloadEnv?.V
export const preloadE2EConfig = createE2EConfig({
headless: process.env.ORCA_E2E_HEADLESS === '1',
exposeStore,
userDataDir: process.env.ORCA_E2E_USER_DATA_DIR ?? null
userDataDir: process.env.ORCA_E2E_USER_DATA_DIR ?? null,
// Why: Number('') is 0 and Number(undefined) is NaN; both coerce to null so
// only a real positive override reaches the renderer parking policy.
terminalParkingDelayMs: Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || null
})
4 changes: 4 additions & 0 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1688,6 +1688,10 @@ const api = {
settings: {
get: (): Promise<unknown> => ipcRenderer.invoke('settings:get'),

// Why: blocking read for the few startup decisions (terminal side-effect
// authority) that cannot wait for async hydration. Call sparingly.
getSync: (): unknown => ipcRenderer.sendSync('settings:get-sync'),

set: (args: Record<string, unknown>): Promise<unknown> =>
ipcRenderer.invoke('settings:set', args),

Expand Down
Loading
Loading