Bound hidden terminal rendering work

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo-H
2026-06-16 10:09:56 -07:00
co-authored by Orca
parent 198c136440
commit 9ea6cb784a
17 changed files with 2578 additions and 119 deletions
+864
View File
@@ -0,0 +1,864 @@
# Terminal freeze / renderer memory spike investigation
## Context
User report: on macOS Orca 1.4.70, terminals sometimes become unresponsive while typing. Existing terminals appear frozen, and newly-created terminals show only a blank cursor instead of the usual shell prompt line. The same user also reported renderer memory spiking to ~1.2GB.
This investigation is on branch `terminal-freeze-after-renderer-memory-spike`.
## Current diagnostic files
Diagnostic E2E files intentionally kept in this worktree:
- `tests/e2e/helpers/terminal-liveness-diagnostics.ts`
- `tests/e2e/terminal-background-pressure-liveness.spec.ts`
These are opt-in pressure/benchmark harnesses. The broader memory-pressure and scrollback-reflow probes were removed from the PR surface after they helped rule out non-root causes.
## What we ruled out
- Raw renderer memory pressure alone did not reproduce terminal breakage.
- Visible sibling terminal output pressure did not reproduce the freeze.
- Large scrollback resize/reflow was locally modest and did not explain the reported symptom.
- WebGL/GPU context loss was not observed in the strongest repro; WebGL stayed active.
## Strongest repro so far
Command shape:
```sh
ORCA_E2E_TERMINAL_CROSS_WORKSPACE_PRESSURE=1 \
ORCA_E2E_TERMINAL_BACKGROUND_PANES=17 \
ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE_MIB_PER_PANE=4 \
ORCA_E2E_TERMINAL_BACKGROUND_PROBES=4 \
ORCA_E2E_TERMINAL_LIVENESS_TIMEOUT_MS=10000 \
npx playwright test tests/e2e/terminal-background-pressure-liveness.spec.ts \
--grep "another workspace" \
--config tests/playwright.config.ts \
--project electron-headful \
--workers=1
```
Baseline after rebasing onto current `main`:
- Active terminal remains technically alive, but echo/liveness latency climbed roughly:
- ~22ms → ~308ms → ~1684ms → ~2971ms
- Renderer scheduler backlog reached ~8.2M chars.
- Renderer memory climbed substantially during the run.
- Main→renderer counters showed hidden output flowing through the renderer path.
With a 2s liveness timeout, the same scenario can fail as `pty-backend-not-echoing`, then recover later. This matches the user-facing “terminal feels frozen” class of symptom.
## Important implementation finding
Current main has a hidden-output restore path in:
- `src/renderer/src/components/terminal-pane/pty-connection.ts`
But the skip gate currently only applies to a narrow hidden Codex/startup case:
```ts
!shouldSnapshotHiddenCodexOutput
```
So ordinary hidden shell terminals in another workspace can still stream live bytes into renderer/xterm work.
## Experiment 1: broaden renderer-side hidden output skipping
Experimental change:
- Let snapshot-capable hidden local PTYs skip renderer xterm writes, not just hidden Codex startup output.
- Mark hidden renderer state dirty and restore from the main-owned buffer when visible.
Measured effect after rebuild:
- Renderer scheduler backlog collapsed from ~8M chars to near-zero.
- Renderer memory stayed much lower, around ~300–370MiB instead of rising toward ~800MiB+ in the same test.
- Main→renderer pending/in-flight counters also improved once hidden renderer delivery was gated.
But the active terminal could still miss a 2s liveness probe even when:
- `schedulerQueuedChars = 0`
- `mainPendingChars = 0`
- `mainRendererInFlightChars = 0`
Conclusion: renderer/xterm/IPC delivery was a major memory/backlog contributor, but not the whole freeze.
## Experiment 2: deliberately lossy hidden runtime/headless skip
Temporary experiment only — do **not** ship:
- In `src/main/ipc/pty.ts`, before runtime/headless processing, skip hidden local PTY data entirely when the renderer pane is hidden.
- Still mark hidden renderer output skipped.
Measured effect:
- The 2s repro passed.
- Active terminal latency stayed around ~10ms / ~500ms / ~500ms / ~10ms.
- Renderer memory stayed around ~296–307MiB.
- App total memory stayed around ~703–727MiB.
Conclusion: the remaining freeze after renderer gating is caused by main/runtime work, most likely `OrcaRuntime.trackHeadlessTerminalData()` parsing every hidden output chunk through the headless xterm emulator.
Relevant code:
- `src/main/ipc/pty.ts`
- local provider `onData`
- `runtime?.onPtyData(...)`
- `src/main/runtime/orca-runtime.ts`
- `onPtyData`
- `trackHeadlessTerminalData`
- `serializeMainTerminalBuffer`
- `src/main/daemon/headless-emulator.ts`
- `HeadlessEmulator.write`
## Current best root-cause model
This is not primarily a GPU renderer death.
The strongest model is:
1. Many hidden/cross-workspace terminals produce high-volume output.
2. Orca processes that hidden output as if the terminals still need live renderer/headless state.
3. Renderer-side xterm work creates memory/backlog pressure.
4. Even after renderer work is avoided, main/runtime headless xterm parsing can still monopolize enough time that active PTY echo is delayed beyond 2s.
5. The terminal is not permanently dead; it is starved/backpressured and later recovers.
## Prototype code currently in worktree
There is prototype code for:
- `pty:setVisibleRendererPty`
- `pty:rendererOutputSkipped`
- main-side hidden local PTY renderer-delivery suppression
- renderer-side restore notification wiring
Files touched:
- `src/main/ipc/pty.ts`
- `src/preload/api-types.ts`
- `src/preload/index.ts`
- `src/renderer/src/components/terminal-pane/pty-connection.ts`
- `src/renderer/src/components/terminal-pane/pty-dispatcher.ts`
- `src/renderer/src/components/terminal-pane/pty-transport.ts`
- `src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts`
- `src/renderer/src/web/web-preload-api.ts`
Also touched incidentally:
- `src/renderer/src/components/tab-bar/TabBar.windows-shell-launch.test.ts`
- Removed a duplicate mocked `useCallback` property after rebasing main.
Validation so far:
```sh
pnpm run typecheck:web
```
passed after removing the duplicate `useCallback` mock.
## What not to ship
Do not ship the lossy hidden runtime/headless skip. It proves the root cause, but it drops hidden terminal history/status and would break restore/mobile/read correctness.
## Likely final fix direction
The safer fix is a two-level hidden terminal strategy:
1. Renderer side:
- Do not send/parse hidden local PTY output through renderer xterm live.
- Mark hidden renderer state dirty.
- Restore from a main-owned snapshot when the pane becomes visible.
2. Main/runtime side:
- Do not synchronously parse every hidden high-volume PTY chunk through the headless xterm emulator while another terminal is active.
- Buffer hidden output cheaply with caps / sequence metadata.
- Preserve enough tail/status/restore information to avoid losing user-visible terminal history.
- Defer or budget headless parsing, then catch up when:
- the hidden pane becomes visible,
- a mobile/client snapshot is requested,
- `orca terminal read` needs the output,
- or the PTY exits and final state must be persisted.
The final solution needs regression coverage proving:
- 17+ hidden/cross-workspace streaming PTYs do not delay active terminal echo beyond the target budget.
- Renderer queue and renderer memory stay bounded.
- Hidden panes restore visible output when shown.
- TUI/alternate-screen restore still works.
- `orca terminal read --limit` and cursor metadata remain correct.
- SSH/remote PTYs are not accidentally put on the local-only hidden-snapshot path.
## Reference-app findings
Checked local OSS reference repos via the `ref-oss` workflow.
High-level pattern:
- Electron/xterm-style apps generally do **not** treat hiding a terminal as
killing the terminal object. Hidden groups/tabs keep the terminal instance
around, toggle visibility/display, and re-open/resize on show.
- They commonly keep PTY output flowing into xterm while hidden, because that is
the simplest way to preserve TUI state and avoid corrupted restore.
- Terminal-emulator-style apps often add flow control around xterm writes:
xterm write callbacks become the backpressure signal, preventing unbounded
renderer write queues.
- Agent/workspace-style notes point out that FIFO replay alone is not enough for
TUI correctness. Important terminal modes such as bracketed paste, focus,
mouse, cursor visibility, application cursor, and kitty keyboard protocol can
be lost if the replay buffer evicts the early mode-setting bytes. A headless
terminal mirror can preserve those modes, but parsing every hidden byte
synchronously is the cost center Orca is currently hitting.
What this means for Orca:
- We should **not** reintroduce the old “unmount hidden terminals and replay a
FIFO later” approach. That is exactly the path that causes restore delays and
damaged TUIs.
- The safer design is a hybrid:
- visible terminals stay live;
- hidden local terminals avoid renderer work;
- main/runtime preserves mode/state correctness, but with budgeting/deferred
catch-up instead of unlimited synchronous parsing for every hidden byte.
- Orca is different from ordinary terminal apps because many hidden agent
terminals can stream output at once, and Orca also maintains main-owned
terminal state for restore/mobile/read APIs. That duplication is where the
freeze appears.
## Goal-ready action items
### 1. Keep and polish the diagnostic repro
- Convert the current cross-workspace pressure probe into a committed regression
test or an opt-in perf test.
- Keep the test focused on the real user symptom:
- active terminal echo/liveness latency,
- renderer memory,
- renderer scheduler backlog,
- main→renderer pending/in-flight chars.
- Add one extra counter for main/runtime headless backlog or hidden deferred
bytes once that mechanism exists.
Suggested success target:
- 17 hidden/cross-workspace PTYs streaming 4MiB each should keep active terminal
liveness under 2s, ideally under ~500ms for all probes.
- Renderer scheduler queue should stay near zero for hidden panes.
- Renderer memory should not climb toward ~1GB in this scenario.
### 2. Finish the safe renderer-side hidden output gate
- Keep the prototype direction where hidden local PTYs are not sent through the
renderer/xterm live path.
- Make the visibility signal robust:
- all visible split panes must be marked visible, not just the focused pane;
- hidden workspaces/tabs must mark their local PTYs hidden;
- pane close/PTY exit must clean up visibility state.
- Keep SSH/remote PTYs off this path until a remote-safe restore source exists.
- Ensure hidden panes get a restore-needed signal when skipped bytes arrive.
- Verify hidden panes restore from the main-owned snapshot when shown.
Suggested tests:
- Unit test main-side hidden renderer delivery suppression.
- E2E test hidden local terminal output restores when switching back.
- E2E test visible split panes still update live.
- E2E test SSH/remote PTYs are not suppressed by the local-only path.
### 3. Design non-lossy deferred headless/runtime ingestion
This is the core unresolved piece.
- Do **not** ship the lossy experiment that simply skips `runtime.onPtyData` for
hidden PTYs.
- Add a deferred path for hidden high-volume local PTY output:
- append hidden bytes to a cheap bounded buffer with sequence metadata;
- keep lightweight side effects that are cheap and important, if needed
(for example title/status tails), but avoid full headless xterm parsing on
every hidden chunk;
- mark the headless terminal state as dirty/stale.
- Drain/catch up the deferred buffer under controlled conditions:
- when the pane becomes visible;
- when a mobile/client snapshot is requested;
- when `orca terminal read` needs data;
- on PTY exit/final persistence;
- opportunistically during idle time, with a strict budget.
- Preserve terminal mode/state correctness. FIFO-only replay is not enough for
rich TUIs; modes such as bracketed paste, focus, mouse, cursor visibility,
app cursor, and kitty keyboard protocol matter.
Open design choice:
- Either keep the headless emulator authoritative but feed it through a
budgeted queue, or maintain a cheap raw/tail buffer while hidden and rebuild
the headless emulator from a bounded replay when needed. The first is safer
for mode continuity; the second may be cheaper but risks old restore bugs if
the replay window loses mode-setting bytes.
### 4. Preserve terminal read/mobile correctness
- Audit `runtime.serializeMainTerminalBuffer`, mobile terminal snapshot paths,
and `orca terminal read` pagination before changing headless ingestion.
- Add tests proving:
- `orca terminal read --limit` still returns recent hidden output;
- cursor metadata remains correct (`oldestCursor`, `nextCursor`,
`latestCursor`, returned line count);
- partial-line behavior is preserved;
- truncation flags and total line counts remain correct;
- mobile/browser clients can still hydrate terminal state.
### 5. Protect TUI restore explicitly
- Keep or extend the existing hidden TUI visual restore coverage.
- Add/verify cases for:
- alternate screen,
- bracketed paste,
- cursor visibility,
- synchronized output (`DEC 2026`),
- terminal color-scheme query/reply behavior,
- rich table/full-screen agent UI restore.
- Switching back to a hidden TUI should not show corrupted rows, missing cursor,
duplicated prompts, or a long blank restore delay.
### 6. Add before/after benchmark evidence
Record the same scenario before and after the final fix:
- command used,
- pane count,
- MiB per pane,
- active liveness probe latencies,
- renderer memory,
- app total memory,
- scheduler queued/peak chars,
- main pending/in-flight chars,
- hidden deferred/backlog counters.
Expected comparison:
- Baseline: active latency can climb to multi-second; renderer queue can hit
millions of chars; memory can approach the reported ~1GB class.
- Fixed: active terminal stays responsive; hidden output does not build renderer
backlog; main/runtime work is bounded.
### 7. Clean up prototypes before PR
- Remove any purely diagnostic or lossy experiment code.
- Keep only production-safe visibility/restore/deferred-ingestion code.
- Decide which diagnostic E2E files should be committed and which should remain
local investigation artifacts.
- Run at minimum:
- focused terminal unit tests,
- hidden TUI restore E2E,
- cross-workspace pressure repro,
- `pnpm run typecheck:web`,
- relevant lint on touched files.
## Suggested `/goal` prompt
Continue the terminal freeze investigation on branch `terminal-freeze-after-renderer-memory-spike` and turn the proven findings into a production-safe fix. The user report is: after renderer memory spikes, existing terminals stop echoing input and new terminals can show only a blank cursor/prompt area. Do not solve this by unmounting hidden terminals or dropping hidden PTY output. Preserve terminal restore, TUI correctness, SSH/remote behavior, mobile/browser hydration, and `orca terminal read` correctness.
Use the existing diagnostic repros to prove the issue and the fix. The leading finding is that hidden/cross-workspace local terminals stream output through both renderer xterm work and main/runtime headless xterm parsing. Renderer-side gating reduces memory/backlog, but active terminal liveness can still fail until hidden main/runtime headless parsing is bounded. A deliberately lossy skip proved the cost center, but must not ship.
Deliver a PR-ready fix with benchmark evidence, regression tests, and a short plain-English explanation of what changed and what risk remains.
## Concrete action checklist for the next goal
### Phase A: Re-establish baseline and protect the investigation
- Run `git status --short` and separate three buckets:
- production candidate changes,
- diagnostic tests/helpers worth keeping,
- throwaway experiment code that must not ship.
- Re-run the strongest repro once before changing behavior so the goal has fresh numbers from this machine.
- Save the benchmark output in this markdown file or a small dedicated benchmark note before editing the implementation further.
- Confirm there is no remaining lossy hidden-output skip before starting the real fix.
### Phase B: Make renderer-side hidden output gating production-safe
- Finalize the local-only hidden renderer suppression path.
- Ensure visibility means “actually visible on screen,” not merely “focused.” Visible split panes should keep live output.
- Ensure hidden tabs/workspaces stop receiving live renderer writes.
- Clean up visibility state on pane close, PTY exit, workspace switch, and renderer reload.
- Keep SSH/remote PTYs out of this path unless there is an explicitly verified remote-safe restore source.
- Add or update tests that prove:
- hidden local PTY output does not build renderer scheduler backlog,
- hidden local terminal output restores when shown again,
- visible split terminals still update live,
- remote/SSH terminals are not accidentally suppressed.
### Phase C: Fix the remaining main/runtime starvation without losing data
- Audit `src/main/ipc/pty.ts`, `src/main/runtime/orca-runtime.ts`, and `src/main/daemon/headless-emulator.ts` around local PTY data flow.
- Identify exactly where hidden terminal output is synchronously parsed by the headless emulator.
- Replace unlimited hidden synchronous parsing with a non-lossy bounded/budgeted path.
- The path should preserve raw output and sequence/order metadata, mark headless state dirty when needed, and catch up under controlled conditions.
- Catch-up triggers should include:
- pane becomes visible,
- terminal snapshot/mobile/browser hydration is requested,
- `orca terminal read` needs hidden output,
- PTY exits or final persistence runs,
- idle/background budget is available.
- Avoid FIFO-only replay if it can lose TUI mode state. If replay is used, prove it preserves modes or constrain it to cases where mode loss cannot corrupt restore.
### Phase D: Verify correctness-sensitive paths
- Verify hidden terminal restore with ordinary shell output.
- Verify hidden TUI restore, especially alternate screen behavior.
- Verify cursor/mode-sensitive behavior: cursor visibility, bracketed paste, mouse/focus modes if practical, synchronized output if existing fixtures cover it.
- Verify `orca terminal read --limit` still returns recent hidden output with correct cursor metadata.
- Verify mobile/browser terminal snapshot hydration still works.
- Verify active terminal input latency stays healthy while hidden terminals are streaming.
### Phase E: Benchmark before/after and make the PR easy to review
- Capture before/after metrics for the strongest repro:
- hidden pane count,
- MiB per pane,
- active liveness probe latencies,
- renderer memory,
- total app memory if available,
- renderer scheduler queued/peak chars,
- main pending/in-flight chars,
- new hidden deferred/backlog counters if added.
- Target outcome:
- active liveness stays below 2s, ideally below ~500ms,
- renderer queue stays near zero for hidden panes,
- renderer memory stays bounded and does not approach the reported ~1GB class,
- hidden output restore remains correct.
- Clean the PR scope:
- remove throwaway diagnostics unless they are committed as intentional perf tests,
- remove any lossy experiment code,
- keep comments short and focused on why hidden terminal data is budgeted/deferred,
- do not mention private reference-app names in code, docs, or PR text.
### Minimum validation before handing back
```sh
pnpm run typecheck:web
npx playwright test tests/e2e/terminal-hidden-tui-visual-restore.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1
ORCA_E2E_TERMINAL_CROSS_WORKSPACE_PRESSURE=1 \
ORCA_E2E_TERMINAL_BACKGROUND_PANES=17 \
ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE_MIB_PER_PANE=4 \
ORCA_E2E_TERMINAL_BACKGROUND_PROBES=4 \
ORCA_E2E_TERMINAL_LIVENESS_TIMEOUT_MS=10000 \
npx playwright test tests/e2e/terminal-background-pressure-liveness.spec.ts \
--grep "another workspace" \
--config tests/playwright.config.ts \
--project electron-headful \
--workers=1
```
If the final implementation changes runtime/headless ingestion, add the most focused unit tests available around terminal buffer serialization and cursor metadata rather than relying only on the large E2E repro.
## Progress update: production-safe deferred headless parsing prototype
Implemented and verified a safer version of the two-level strategy:
- Renderer delivery is suppressed only for local PTYs that the renderer explicitly reports as hidden.
- Unknown/new PTYs default to live renderer delivery, which preserves startup and existing batching behavior.
- Hidden panes send a `pty:rendererOutputSkipped` signal so the renderer knows its xterm state is stale and must restore from the main-owned snapshot when shown.
- Remote/SSH PTYs are not put on this local-only hidden path.
- Runtime/headless xterm parsing is no longer unlimited inline work for explicitly hidden local PTYs.
- Raw hidden bytes are kept in order in a deferred queue with output sequence metadata.
- Terminal read/status/tail/subscriber paths still update from raw PTY data immediately.
- Headless snapshots drain deferred bytes before serializing, so hidden restore/mobile snapshots still see a current main-owned xterm snapshot.
- A small global background drain budget exists so idle catch-up cannot become one parser loop per hidden PTY.
- The in-memory deferred queue is capped per PTY; larger hidden backlogs spill to temp files without dropping bytes.
Important correction made during validation:
- The first implementation treated PTYs as hidden until marked visible. That broke normal spawn/batching tests because renderer output was suppressed before any renderer visibility report. The current behavior is safer: output is suppressed only after an explicit `visible: false` signal.
- The first snapshot flush path accidentally widened an existing write-chain race by awaiting an already-resolved no-op flush. The current path preserves the original race semantics when there are no deferred hidden bytes.
New focused tests added:
- `src/main/runtime/orca-runtime.test.ts`
- hidden headless parsing defers while `readTerminal` remains current;
- `serializeMainTerminalBuffer` drains deferred bytes and returns the expected sequence.
- `src/main/ipc/pty.test.ts`
- hidden local PTY renderer delivery is suppressed;
- normal renderer delivery resumes when the PTY is visible again;
- remote-owned PTYs are not suppressed by the local hidden-output path.
Validation run after this change:
```sh
pnpm vitest run src/main/ipc/pty.test.ts src/main/runtime/mobile-subscribe-integration.test.ts
pnpm run typecheck:web
git diff --check
```
Result:
- `src/main/ipc/pty.test.ts`: 157 passed
- `src/main/runtime/mobile-subscribe-integration.test.ts`: 43 passed, 2 skipped
- `pnpm run typecheck:web`: passed
- `git diff --check`: passed
Next action items:
- Cross-workspace pressure E2E has been run with the deferred-headless path and benchmark evidence is recorded below.
- Keep only the pressure E2E harness and its liveness helper as durable opt-in benchmark coverage.
- Hidden TUI visual restore E2E passed under `electron-headless`.
- Deferred headless backlog counters are exposed through the existing renderer-delivery debug snapshot and recorded by the pressure harness.
- A follow-up audit found and fixed a spool-only snapshot edge case: if the in-memory deferred queue had drained but temp-file spillover still contained hidden bytes, snapshots now still flush the spool before serializing. `src/main/runtime/orca-runtime.test.ts` covers this by draining in-memory deferred chunks first and then asserting the spooled tail appears in `serializeMainTerminalBuffer`.
## Benchmark/update: cross-workspace pressure after deferred headless parsing
Final command run after rebuilding the Electron E2E bundle:
```sh
ORCA_E2E_TERMINAL_CROSS_WORKSPACE_PRESSURE=1 \
ORCA_E2E_TERMINAL_BACKGROUND_PANES=17 \
ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE_MIB_PER_PANE=4 \
ORCA_E2E_TERMINAL_BACKGROUND_PROBES=4 \
ORCA_E2E_TERMINAL_LIVENESS_TIMEOUT_MS=10000 \
npx playwright test tests/e2e/terminal-background-pressure-liveness.spec.ts \
--grep "another workspace" \
--config tests/playwright.config.ts \
--project electron-headful \
--workers=1
```
Result: passed.
Measured probes after adding the bounded in-memory deferred queue plus temp-file spillover for larger hidden backlogs. These numbers were refreshed after rebasing onto latest `origin/main` and updating the renderer hidden-restore tests:
| Probe | Active liveness | Renderer memory | Total app memory | Scheduler queued | Scheduler peak | Main pending | Main in-flight | Hidden/deferred headless |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | 64.6ms | 386MiB | 867MiB | 0 | 767 chars | 0 | 0 | 17 hidden / 15 deferred / 1,114,304 chars |
| 2 | 1165.4ms | 385MiB | 925MiB | 0 | 767 chars | 0 | 0 | 17 hidden / 17 deferred / 18,593,063 chars |
| 3 | 755.4ms | 385MiB | 1016MiB | 0 | 767 chars | 0 | 0 | 17 hidden / 17 deferred / 70,312,870 chars |
| 4 | 61.1ms | 385MiB | 1017MiB | 0 | 767 chars | 0 | 0 | 17 hidden / 17 deferred / 70,191,014 chars |
Interpretation:
- This fixes the strongest user-shaped liveness failure in the repro: all probes stayed below the 2s target and classified as `terminal-layer-healthy`.
- Renderer queue pressure stayed eliminated (`schedulerQueuedChars=0`; peak only 767 chars).
- Renderer memory stayed around ~385–386MiB, much lower than the earlier ~800MiB+ class in this scenario.
- Total app memory reached ~1.0GiB in this run while renderer memory stayed bounded. This addresses the terminal liveness/render-queue side of the report; it still should not be represented as a complete explanation for every possible 1.2GB resource-manager observation.
- Hidden headless backlog is now visible in benchmark output. The in-memory queue is capped per PTY and spills larger hidden backlogs to temp files without dropping terminal bytes.
Hidden TUI restore validation:
```sh
SKIP_BUILD=1 npx playwright test tests/e2e/terminal-hidden-tui-visual-restore.spec.ts \
--grep "restores hidden full-screen" \
--config tests/playwright.config.ts \
--project electron-headless \
--workers=1
```
Result: passed.
Note: the earlier checklist used `electron-headful`, but this spec is not tagged `@headful`; the current Playwright config only includes it in the `electron-headless` project.
## Cleanup update
The PR surface now keeps the cross-workspace/background terminal pressure harness and shared liveness diagnostic helper. The one-off memory-pressure, basic liveness, and scrollback-reflow diagnostic specs were removed from the worktree because they were useful for investigation but do not directly guard the final fix.
The pressure harness records hidden/deferred headless backlog counters via `window.api.pty.getRendererDeliveryDebugSnapshot()`, so benchmark output shows both renderer queue pressure and main/runtime deferred backlog in the same output.
## Validation update after final audit
Fresh validation after fixing the spool-only snapshot edge case:
```sh
pnpm vitest run src/main/runtime/orca-runtime.test.ts src/main/ipc/pty.test.ts src/main/runtime/mobile-subscribe-integration.test.ts
pnpm run typecheck:web
git diff --check
SKIP_BUILD=1 npx playwright test tests/e2e/terminal-hidden-tui-visual-restore.spec.ts \
--grep "restores hidden full-screen" \
--config tests/playwright.config.ts \
--project electron-headless \
--workers=1
ORCA_E2E_TERMINAL_CROSS_WORKSPACE_PRESSURE=1 \
ORCA_E2E_TERMINAL_BACKGROUND_PANES=17 \
ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE_MIB_PER_PANE=4 \
ORCA_E2E_TERMINAL_BACKGROUND_PROBES=4 \
ORCA_E2E_TERMINAL_LIVENESS_TIMEOUT_MS=10000 \
npx playwright test tests/e2e/terminal-background-pressure-liveness.spec.ts \
--grep "another workspace" \
--config tests/playwright.config.ts \
--project electron-headful \
--workers=1
```
Results:
- Runtime/IPC/mobile integration tests: `3 passed`, `548 passed | 2 skipped`.
- `pnpm run typecheck:web`: passed.
- `git diff --check`: passed.
- Hidden TUI restore E2E: passed.
- Cross-workspace pressure E2E: passed with the refreshed metrics above.
## Current `/goal` action items
Use this section as the starting point for a new focused goal. The code is close to PR-ready, but should be treated as a production-safety audit plus evidence pass, not as a finished merge.
### 1. Audit the final diff for correctness and scope
- Inspect every touched file and confirm the shipped behavior is non-lossy.
- Confirm hidden local PTY output still updates main-owned raw output/read/status state before any renderer/headless deferral.
- Confirm remote/SSH-owned PTYs are never suppressed by the local hidden renderer path.
- Confirm new PTYs default to live delivery until the renderer explicitly reports them hidden.
- Inspect `shouldSnapshotHiddenCodexOutput` in `src/renderer/src/components/terminal-pane/pty-connection.ts`; keep it only if it is still needed for renderer-query/startup behavior, otherwise rename/remove stale logic.
- Verify temp-file spillover cleanup runs on PTY clear/dispose/error paths and uses private file permissions where supported.
### 2. Re-run the focused validation suite
Run these before considering the PR ready:
```sh
pnpm vitest run src/main/runtime/orca-runtime.test.ts src/main/ipc/pty.test.ts src/main/runtime/mobile-subscribe-integration.test.ts
pnpm run typecheck:web
git diff --check
SKIP_BUILD=1 npx playwright test tests/e2e/terminal-hidden-tui-visual-restore.spec.ts \
--grep "restores hidden full-screen" \
--config tests/playwright.config.ts \
--project electron-headless \
--workers=1
ORCA_E2E_TERMINAL_CROSS_WORKSPACE_PRESSURE=1 \
ORCA_E2E_TERMINAL_BACKGROUND_PANES=17 \
ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE_MIB_PER_PANE=4 \
ORCA_E2E_TERMINAL_BACKGROUND_PROBES=4 \
ORCA_E2E_TERMINAL_LIVENESS_TIMEOUT_MS=10000 \
npx playwright test tests/e2e/terminal-background-pressure-liveness.spec.ts \
--grep "another workspace" \
--config tests/playwright.config.ts \
--project electron-headful \
--workers=1
```
### 3. Decide what diagnostic coverage belongs in the PR
- Keep `tests/e2e/helpers/terminal-liveness-diagnostics.ts` if the pressure spec remains committed.
- Keep `tests/e2e/terminal-background-pressure-liveness.spec.ts` as an opt-in benchmark/regression harness if reviewers are comfortable with the runtime.
- Do not re-add the one-off memory-pressure, basic liveness, or scrollback-reflow investigation specs unless they directly guard the final behavior.
- Make sure committed tests are deterministic enough for local/CI use, or clearly env-gated as perf diagnostics.
### 4. Prepare an honest PR description
The PR should claim:
- Hidden local terminals no longer keep doing unlimited live renderer/xterm work while off-screen.
- Hidden local headless parsing is deferred/budgeted instead of synchronously parsing every hidden byte inline.
- Raw output is still retained; snapshots/read/mobile restore paths catch up before they need current terminal state.
- The strongest repro stays responsive under 17 hidden streaming PTYs.
The PR should **not** claim:
- This fully explains every possible 1.2GB renderer/resource-manager memory report.
- This fixes all terminal freezes in Orca.
- Hidden terminals are unmounted or output is dropped.
### 5. Include benchmark evidence in the PR body
Use the final benchmark table already recorded above, especially:
- active liveness: `64.6ms`, `1165.4ms`, `755.4ms`, `61.1ms`;
- renderer memory: `386MiB`, `385MiB`, `385MiB`, `385MiB`;
- scheduler queued chars: `0` on every probe;
- hidden/deferred headless backlog reaching `70,312,870` chars without dropping bytes;
- hidden TUI restore E2E passed under `electron-headless`.
Frame this as a fix for the terminal liveness/render-queue starvation path, with bounded memory/backlog behavior, not as the complete postmortem for all reported memory spikes.
### 6. Plain-English final explanation to preserve
The likely bug was not that the visible terminal itself broke. Orca was letting many hidden terminals keep doing expensive live terminal-rendering work in the background. That work built up enough renderer and main-process terminal parsing pressure that the active terminal could not echo input quickly, so it looked frozen. The fix keeps hidden terminal output safe and restorable, but stops treating off-screen local terminals like they need full live rendering every moment.
## Normalized terminal tail cap benchmark: 256KB vs 64KB
This benchmark isolates Orca's main-owned normalized text tail (`appendNormalizedToTailBuffer`) and compares a 256KB retained tail with a hypothetical 64KB retained tail as terminal count scales. It does **not** measure xterm/headless parsing, renderer painting, WebGL, or human scrollback. It is specifically about the retained text buffer used by programmatic reads/previews/waits/status.
Command run:
```sh
node --expose-gc .tmp/terminal-tail-cap-benchmark.js > .tmp/terminal-tail-cap-benchmark.json
```
Setup:
- Standalone copy of the current tail-retention algorithm, parameterized by byte cap.
- 512KB of normalized output per simulated terminal, chunked into 16KB writes.
- Median of 5 runs for 1/10/50/100 terminals, 3 runs for 250 terminals, and 2 runs for 500 terminals.
- Existing caps preserved in the benchmark: 2,000 completed lines and 4KB partial line.
### Wide log lines: 200-char completed lines, byte cap dominates
| Terminals | 64KB median | 256KB median | 64KB retained | 256KB retained | CPU delta | Retained delta |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | 0.75ms | 0.78ms | 63.9KiB | 255.9KiB | -4.5% | -75.0% |
| 10 | 6.43ms | 7.70ms | 638.7KiB | 2,558.6KiB | -16.5% | -75.0% |
| 50 | 29.00ms | 30.86ms | 3,193.4KiB | 12,793.0KiB | -6.0% | -75.0% |
| 100 | 53.47ms | 62.01ms | 6,386.7KiB | 25,585.9KiB | -13.8% | -75.0% |
| 250 | 138.06ms | 178.95ms | 15,966.8KiB | 63,964.8KiB | -22.8% | -75.0% |
| 500 | 284.94ms | 339.91ms | 31,933.6KiB | 127,929.7KiB | -16.2% | -75.0% |
### Short shell-ish lines: 80-char completed lines, line cap competes with byte cap
| Terminals | 64KB median | 256KB median | 64KB retained | 256KB retained | CPU delta | Retained delta |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | 0.83ms | 1.30ms | 64.0KiB | 156.3KiB | -36.4% | -59.1% |
| 10 | 8.66ms | 8.29ms | 639.8KiB | 1,562.5KiB | +4.5% | -59.1% |
| 50 | 40.82ms | 49.08ms | 3,199.2KiB | 7,812.5KiB | -16.8% | -59.1% |
| 100 | 85.36ms | 99.13ms | 6,398.4KiB | 15,625.0KiB | -13.9% | -59.1% |
| 250 | 238.27ms | 263.70ms | 15,996.1KiB | 39,062.5KiB | -9.6% | -59.1% |
| 500 | 473.68ms | 588.96ms | 31,992.2KiB | 78,125.0KiB | -19.6% | -59.1% |
### Newline-free TUI redraws: CR/ANSI redraw stream, partial-line cap dominates
| Terminals | 64KB median | 256KB median | 64KB retained | 256KB retained | CPU delta | Retained delta |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | 0.91ms | 0.87ms | 0.2KiB | 0.2KiB | +4.1% | 0.0% |
| 10 | 8.22ms | 8.23ms | 2.0KiB | 2.0KiB | -0.2% | 0.0% |
| 50 | 39.39ms | 39.83ms | 10.0KiB | 10.0KiB | -1.1% | 0.0% |
| 100 | 79.23ms | 79.48ms | 19.9KiB | 19.9KiB | -0.3% | 0.0% |
| 250 | 199.50ms | 199.90ms | 49.8KiB | 49.8KiB | -0.2% | 0.0% |
| 500 | 407.20ms | 399.42ms | 99.6KiB | 99.6KiB | +1.9% | 0.0% |
Takeaways:
- Lowering the normalized tail from 256KB to 64KB saves up to about 192KB per terminal in this layer, or about 94MiB at 500 terminals when the byte cap is the limiter.
- For short shell-like output, the 2,000-line cap already prevents reaching 256KB, so the practical saving is closer to 92KB per terminal in this benchmark.
- For newline-free TUI redraw streams, the 4KB partial-line cap already dominates, so 64KB vs 256KB makes no meaningful difference.
- CPU scales roughly linearly with terminal count. In completed-line workloads, the 64KB cap was usually about 10-20% faster at larger terminal counts because each append scans/trims fewer retained line characters. That is helpful but not the main terminal-freeze fix; the larger win remains suppressing/defering hidden renderer/headless terminal work.
## Hidden restore visual side-effect harness: 1,000 hidden lines
Added a focused Playwright harness in `tests/e2e/terminal-hidden-restore-no-catchup-scroll.spec.ts` to answer whether a hidden terminal visibly scrolls/replays when it is refocused after a large hidden burst.
Harness shape:
- Open a terminal in a secondary worktree.
- Seed visible baseline content before hiding the terminal.
- Switch to another worktree so the terminal is hidden.
- Write 1,000 lines to the hidden PTY from a script.
- Wait for the script completion file from the test process, avoiding a pre-focus main-buffer snapshot that would make the restore path easier than reality.
- Assert the hidden burst exercised deferred headless restore (`deferredHeadlessChars > 20,000`).
- Start a `requestAnimationFrame` recorder before switching back.
- Record each visible terminal frame: whether the pane is actually DOM-visible, whether the old baseline is present, whether the final hidden line is present, the latest hidden line number seen, serialized text length, `baseY`, and `viewportY`.
Current result on `electron-headless`:
```sh
SKIP_BUILD=1 npx playwright test tests/e2e/terminal-hidden-restore-no-catchup-scroll.spec.ts \
--config tests/playwright.config.ts \
--project electron-headless \
--workers=1
```
Result: the strict “first visible frame is already fully caught up” assertion currently fails.
Observed frame sequence after returning to the hidden terminal:
- Frames 0–1: terminal pane is DOM-visible, but still shows the old baseline content; no hidden burst lines are visible yet.
- Frame 2 onward: final restored state is present immediately, with line 1,000 visible in the serialized buffer and stable `baseY`/`viewportY` values.
- No sampled frame showed intermediate catch-up line numbers such as 200 → 500 → 1,000. In this harness, the restore does **not** visibly scroll through the 1,000 hidden lines; it swaps from stale content to the final restored state after roughly 1–2 animation frames.
Interpretation:
- The current PR does not appear to cause line-by-line catch-up scrolling for a 1,000-line hidden burst.
- It does appear to have a small visible stale-frame artifact on refocus: for about 1–2 frames, the user can see the pre-hidden terminal contents before the main-owned snapshot replay finishes.
- This is less severe than “watching 1,000 lines replay,” but it is a real visual side effect if the bar is “first visible frame must already be current.”
Follow-up options:
1. Keep the PR as-is and document the tradeoff honestly: no visible catch-up scroll, but possible brief stale frame on refocus.
2. Make the harness a failing/manual regression guard for a follow-up polish PR that eliminates the stale frame.
3. Explore a pre-restore path before a hidden terminal becomes visible. The risk is reintroducing a restore delay or hidden renderer work; any fix should preserve the current no-loss, no-hidden-live-rendering behavior.
### Follow-up result: blank stale renderer copy before restore
Implemented a small renderer-side polish in `src/renderer/src/components/terminal-pane/pty-connection.ts`:
- When hidden output is skipped, clear the stale renderer xterm copy once with `CSI 2J / CSI 3J / cursor home`.
- Keep the main-owned terminal snapshot as the authoritative state.
- Reset the blanking flag after the real snapshot is replayed.
This changes the visible refocus behavior from:
1. old/stale terminal content for ~1–2 frames;
2. final restored terminal state;
into:
1. blank/minimal terminal surface for ~1–2 frames;
2. final restored terminal state.
Validation:
```sh
npx playwright test tests/e2e/terminal-hidden-restore-no-catchup-scroll.spec.ts \
--config tests/playwright.config.ts \
--project electron-headless \
--workers=1
SKIP_BUILD=1 npx playwright test tests/e2e/terminal-hidden-restore-no-catchup-scroll.spec.ts \
--config tests/playwright.config.ts \
--project electron-headless \
--workers=1
```
Result after the change: passed.
Observed sample behavior after rebuild:
- Pre-restore visible frames contained only a tiny clear/reset remnant (`textLength ~= 8`, preview `ESC [?2004h`), not the old baseline terminal contents.
- No sampled frame showed intermediate hidden line numbers.
- Once restored, every later sampled frame had the final hidden line 1,000 and stable viewport state.
Timed follow-up on 2026-06-16:
- Added `performance.now()` timestamps to the hidden restore frame recorder.
- Reran the focused harness with `SKIP_BUILD=1` after the renderer blanking change.
- Result: passed.
- Visible samples before restore: 2 blank/minimal frames.
- First visible blank frame → first fully restored frame: `30.9ms`.
- Last blank frame → first fully restored frame: `19.5ms`.
- First restored sample was frame index 2; every later sample stayed fully restored with line 1,000 present.
Interpretation: in this run it was actually 1–2 visible rAF samples / ~31ms, not several dozen frames.
## PR prep validation after rebasing latest main
Commands run on 2026-06-16 after the final renderer test update:
```sh
pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts
pnpm vitest run src/main/runtime/orca-runtime.test.ts src/main/ipc/pty.test.ts src/main/runtime/mobile-subscribe-integration.test.ts
pnpm run typecheck:web
git diff --check
SKIP_BUILD=1 npx playwright test tests/e2e/terminal-hidden-restore-no-catchup-scroll.spec.ts \
--config tests/playwright.config.ts \
--project electron-headless \
--workers=1
SKIP_BUILD=1 npx playwright test tests/e2e/terminal-hidden-tui-visual-restore.spec.ts \
--grep "restores hidden full-screen" \
--config tests/playwright.config.ts \
--project electron-headless \
--workers=1
SKIP_BUILD=1 ORCA_E2E_TERMINAL_CROSS_WORKSPACE_PRESSURE=1 \
ORCA_E2E_TERMINAL_BACKGROUND_PANES=17 \
ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE_MIB_PER_PANE=4 \
ORCA_E2E_TERMINAL_BACKGROUND_PROBES=4 \
ORCA_E2E_TERMINAL_LIVENESS_TIMEOUT_MS=10000 \
npx playwright test tests/e2e/terminal-background-pressure-liveness.spec.ts \
--grep "another workspace" \
--config tests/playwright.config.ts \
--project electron-headful \
--workers=1
```
Results:
- Renderer PTY connection tests: `161 passed`.
- Main/runtime/mobile tests: `564 passed | 2 skipped`.
- `pnpm run typecheck:web`: passed after refreshing the local frozen install for declared dependencies.
- `git diff --check`: passed.
- Hidden no-catchup-scroll E2E: passed.
- Hidden TUI restore E2E: passed.
- Cross-workspace pressure E2E: passed with the refreshed metrics above.
+119 -6
View File
@@ -2,6 +2,7 @@
one focused file because the registration helper is stateful and each spawn-path
assertion reuses the same mocked IPC and node-pty harness. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
const {
@@ -488,6 +489,19 @@ describe('registerPtyHandlers', () => {
return activeCall[1] as (event: unknown, args: { id: string; active: boolean }) => void
}
function getPtySetVisibleRendererPtyListener(): (
event: unknown,
args: { id: string; visible: boolean }
) => void {
const visibleCall = onMock.mock.calls.find(
(call: unknown[]) => call[0] === 'pty:setVisibleRendererPty'
)
if (!visibleCall) {
throw new Error('missing pty:setVisibleRendererPty listener')
}
return visibleCall[1] as (event: unknown, args: { id: string; visible: boolean }) => void
}
/** Helper: trigger pty:spawn and return the env passed to node-pty. */
async function spawnAndGetEnv(
argsEnv?: Record<string, string>,
@@ -4354,7 +4368,7 @@ describe('registerPtyHandlers', () => {
const spawnResult = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp'
cwd: tmpdir()
})) as { id: string }
mainWindow.webContents.send.mockClear()
@@ -4383,7 +4397,7 @@ describe('registerPtyHandlers', () => {
const spawnResult = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp'
cwd: tmpdir()
})) as { id: string }
const writeListener = getPtyWriteListener()
@@ -4442,7 +4456,7 @@ describe('registerPtyHandlers', () => {
const spawnResult = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp'
cwd: tmpdir()
})) as { id: string }
const writeListener = getPtyWriteListener()
@@ -4476,7 +4490,7 @@ describe('registerPtyHandlers', () => {
const spawnResult = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp'
cwd: tmpdir()
})) as { id: string }
const writeListener = getPtyWriteListener()
@@ -4767,6 +4781,105 @@ describe('registerPtyHandlers', () => {
}
})
it('suppresses hidden local PTY renderer delivery and resumes when visible', async () => {
vi.useFakeTimers()
const provider = installObservableDaemonTestProvider()
const runtime = {
onPtyData: vi.fn((_id: string, data: string) => data.length),
getPtyOutputSequence: vi.fn(() => 0),
onPtySpawned: vi.fn(),
onPtyExit: vi.fn(),
setPtyHeadlessTerminalVisible: vi.fn(),
setPtyController: vi.fn(),
createPreAllocatedTerminalHandle: vi.fn(() => 'term-preallocated'),
registerPreAllocatedHandleForPty: vi.fn()
}
try {
registerPtyHandlers(mainWindow as never, runtime as never)
const spawnResult = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: tmpdir()
})) as { id: string }
const setVisibleRendererPty = getPtySetVisibleRendererPtyListener()
mainWindow.webContents.send.mockClear()
setVisibleRendererPty(null, { id: spawnResult.id, visible: false })
provider.emitData(spawnResult.id, 'hidden-output')
vi.advanceTimersByTime(8)
expect(runtime.setPtyHeadlessTerminalVisible).toHaveBeenCalledWith(spawnResult.id, false)
expect(mainWindow.webContents.send).toHaveBeenCalledTimes(1)
expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:rendererOutputSkipped', {
id: spawnResult.id
})
expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({
pendingPtyCount: 0,
rendererInFlightChars: 0
})
setVisibleRendererPty(null, { id: spawnResult.id, visible: true })
provider.emitData(spawnResult.id, 'visible-output')
vi.advanceTimersByTime(8)
expect(runtime.setPtyHeadlessTerminalVisible).toHaveBeenLastCalledWith(spawnResult.id, true)
expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
id: spawnResult.id,
data: 'visible-output',
seq: 'visible-output'.length,
rawLength: 'visible-output'.length
})
} finally {
vi.useRealTimers()
}
})
it('does not suppress renderer delivery for hidden remote-owned PTYs', async () => {
vi.useFakeTimers()
const provider = installObservableDaemonTestProvider()
const runtime = {
onPtyData: vi.fn((_id: string, data: string) => data.length),
getPtyOutputSequence: vi.fn(() => 0),
onPtySpawned: vi.fn(),
onPtyExit: vi.fn(),
setPtyHeadlessTerminalVisible: vi.fn(),
setPtyController: vi.fn(),
createPreAllocatedTerminalHandle: vi.fn(() => 'term-preallocated'),
registerPreAllocatedHandleForPty: vi.fn()
}
try {
registerPtyHandlers(mainWindow as never, runtime as never)
const spawnResult = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: tmpdir()
})) as { id: string }
setPtyOwnership(spawnResult.id, 'ssh-1')
const setVisibleRendererPty = getPtySetVisibleRendererPtyListener()
mainWindow.webContents.send.mockClear()
setVisibleRendererPty(null, { id: spawnResult.id, visible: false })
provider.emitData(spawnResult.id, 'remote-hidden-output')
vi.advanceTimersByTime(8)
expect(runtime.setPtyHeadlessTerminalVisible).not.toHaveBeenCalled()
expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
id: spawnResult.id,
data: 'remote-hidden-output',
seq: 'remote-hidden-output'.length,
rawLength: 'remote-hidden-output'.length
})
expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('pty:rendererOutputSkipped', {
id: spawnResult.id
})
} finally {
deletePtyOwnership('daemon-pty')
vi.useRealTimers()
}
})
it('reserves a bounded renderer lane for interactive output when bulk output is saturated', async () => {
vi.useFakeTimers()
const bulkProcs = Array.from({ length: 16 }, () => createMockProc())
@@ -4781,13 +4894,13 @@ describe('registerPtyHandlers', () => {
await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp'
cwd: tmpdir()
})
}
const interactiveSpawn = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp'
cwd: tmpdir()
})) as { id: string }
const writeListener = getPtyWriteListener()
mainWindow.webContents.send.mockClear()
+81 -3
View File
@@ -91,6 +91,8 @@ const ptySizes = new Map<string, { cols: number; rows: number }>()
const lastInputAtByPty = new Map<string, number>()
const interactiveOutputCharsByPty = new Map<string, number>()
const activeRendererPtys = new Set<string>()
const hiddenRendererPtys = new Set<string>()
const skippedRendererOutputPtys = new Set<string>()
// Why: the agent-hooks server caches per-paneKey state (last prompt, last
// tool) that otherwise grows unbounded as panes come and go. Track the
// spawn-time paneKey so clearProviderPtyState can clear that cache on PTY
@@ -850,6 +852,8 @@ export function clearProviderPtyState(id: string): void {
lastInputAtByPty.delete(id)
interactiveOutputCharsByPty.delete(id)
activeRendererPtys.delete(id)
hiddenRendererPtys.delete(id)
skippedRendererOutputPtys.delete(id)
const paneKey = ptyPaneKey.get(id)
const stillOwnsPaneKey = paneKey ? paneKeyPtyId.get(paneKey) === id : false
// Why: drop the memory-collector registration so a dead PTY does not keep
@@ -954,6 +958,10 @@ export type PtyRendererDeliveryDebugSnapshot = {
peakRendererInFlightChars: number
peakMaxRendererInFlightCharsByPty: number
ackGatedFlushSkipCount: number
hiddenHeadlessPtyCount: number
deferredHeadlessPtyCount: number
deferredHeadlessChars: number
maxDeferredHeadlessCharsByPty: number
}
const EMPTY_PTY_RENDERER_DELIVERY_DEBUG_SNAPSHOT: PtyRendererDeliveryDebugSnapshot = {
@@ -969,7 +977,11 @@ const EMPTY_PTY_RENDERER_DELIVERY_DEBUG_SNAPSHOT: PtyRendererDeliveryDebugSnapsh
peakMaxPendingCharsByPty: 0,
peakRendererInFlightChars: 0,
peakMaxRendererInFlightCharsByPty: 0,
ackGatedFlushSkipCount: 0
ackGatedFlushSkipCount: 0,
hiddenHeadlessPtyCount: 0,
deferredHeadlessPtyCount: 0,
deferredHeadlessChars: 0,
maxDeferredHeadlessCharsByPty: 0
}
let readPtyRendererDeliveryDebugSnapshot = (): PtyRendererDeliveryDebugSnapshot => ({
@@ -1046,6 +1058,8 @@ export function registerPtyHandlers(
ipcMain.removeAllListeners('pty:write')
ipcMain.removeAllListeners('pty:ackColdRestore')
ipcMain.removeAllListeners('pty:ackData')
ipcMain.removeAllListeners('pty:setActiveRendererPty')
ipcMain.removeAllListeners('pty:setVisibleRendererPty')
ipcMain.removeAllListeners('pty:serializeBuffer:response')
// Configure the local provider with app-specific hooks.
@@ -1105,6 +1119,9 @@ export function registerPtyHandlers(
onExit: (id, code) => {
clearProviderPtyState(id)
ptyOwnership.delete(id)
activeRendererPtys.delete(id)
hiddenRendererPtys.delete(id)
skippedRendererOutputPtys.delete(id)
markClaudePtyExited(id)
runtime?.onPtyExit(id, code)
},
@@ -1164,6 +1181,10 @@ export function registerPtyHandlers(
pendingChars += chars
maxPendingCharsByPty = Math.max(maxPendingCharsByPty, chars)
}
const headlessBacklog =
typeof runtime?.getHeadlessTerminalBacklogDebugSnapshot === 'function'
? runtime.getHeadlessTerminalBacklogDebugSnapshot()
: null
return {
pendingPtyCount: pendingData.size,
pendingChars,
@@ -1177,7 +1198,11 @@ export function registerPtyHandlers(
peakMaxPendingCharsByPty,
peakRendererInFlightChars,
peakMaxRendererInFlightCharsByPty,
ackGatedFlushSkipCount
ackGatedFlushSkipCount,
hiddenHeadlessPtyCount: headlessBacklog?.hiddenPtyCount ?? 0,
deferredHeadlessPtyCount: headlessBacklog?.deferredPtyCount ?? 0,
deferredHeadlessChars: headlessBacklog?.deferredChars ?? 0,
maxDeferredHeadlessCharsByPty: headlessBacklog?.maxDeferredCharsByPty ?? 0
}
}
@@ -1278,6 +1303,22 @@ export function registerPtyHandlers(
mainWindow.webContents.send('pty:data', payload)
}
function shouldSkipRendererDeliveryForHiddenPty(id: string): boolean {
// Why: only local PTYs have a main-owned buffer snapshot that can restore
// hidden bytes later. SSH/remote PTYs still need the live renderer path.
return ptyOwnership.get(id) === null && hiddenRendererPtys.has(id)
}
function markRendererOutputSkipped(id: string): void {
if (skippedRendererOutputPtys.has(id)) {
return
}
skippedRendererOutputPtys.add(id)
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('pty:rendererOutputSkipped', { id })
}
}
function getPendingPtyFlushEntries(): [string, PendingPtyData][] {
const entries = Array.from(pendingData.entries())
const active: [string, PendingPtyData][] = []
@@ -1322,6 +1363,8 @@ export function registerPtyHandlers(
pendingData.clear()
rendererInFlightCharsByPty.clear()
rendererInFlightTotalChars = 0
skippedRendererOutputPtys.clear()
hiddenRendererPtys.clear()
recordPtyRendererDeliveryPressure()
return
}
@@ -1401,6 +1444,18 @@ export function registerPtyHandlers(
recordPtyRendererDeliveryPressure()
return
}
if (shouldSkipRendererDeliveryForHiddenPty(payload.id)) {
pendingData.delete(payload.id)
rendererInFlightTotalChars = Math.max(
0,
rendererInFlightTotalChars - (rendererInFlightCharsByPty.get(payload.id) ?? 0)
)
rendererInFlightCharsByPty.delete(payload.id)
markRendererOutputSkipped(payload.id)
recordPtyRendererDeliveryPressure()
tryGetProviderForPty(payload.id)?.acknowledgeDataEvent(payload.id, payload.data.length)
return
}
const existing = pendingData.get(payload.id)
const pending = appendPendingPtyData(existing, payload.data, startSeq)
const nextData = pending.data
@@ -1441,6 +1496,9 @@ export function registerPtyHandlers(
if (!isLocalProvider) {
clearProviderPtyState(payload.id)
ptyOwnership.delete(payload.id)
activeRendererPtys.delete(payload.id)
hiddenRendererPtys.delete(payload.id)
skippedRendererOutputPtys.delete(payload.id)
markClaudePtyExited(payload.id)
runtime?.onPtyExit(payload.id, payload.code)
}
@@ -2713,7 +2771,6 @@ export function registerPtyHandlers(
}
})
ipcMain.removeAllListeners('pty:setActiveRendererPty')
ipcMain.on('pty:setActiveRendererPty', (_event, args: { id: string; active: boolean }) => {
if (typeof args.id !== 'string' || !args.id) {
return
@@ -2731,6 +2788,27 @@ export function registerPtyHandlers(
}
})
ipcMain.on('pty:setVisibleRendererPty', (_event, args: { id: string; visible: boolean }) => {
if (typeof args.id !== 'string' || !args.id) {
return
}
const isLocalPty = ptyOwnership.get(args.id) === null
if (args.visible) {
hiddenRendererPtys.delete(args.id)
if (skippedRendererOutputPtys.delete(args.id) && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('pty:rendererOutputSkipped', { id: args.id })
}
} else {
hiddenRendererPtys.add(args.id)
}
if (pendingData.size > 0 && !flushTimer) {
schedulePendingDataFlush(0)
}
if (isLocalPty) {
runtime?.setPtyHeadlessTerminalVisible(args.id, args.visible)
}
})
ipcMain.removeAllListeners('pty:signal')
ipcMain.on('pty:signal', (_event, args: { id: string; signal: string }) => {
tryGetProviderForPty(args.id)
+95
View File
@@ -4096,6 +4096,101 @@ describe('OrcaRuntimeService', () => {
})
})
it('defers hidden headless parsing while keeping terminal reads current', async () => {
const runtime = createRuntime()
syncSinglePty(runtime, 'pty-1')
const [terminal] = (await runtime.listTerminals()).terminals
runtime.setPtyHeadlessTerminalVisible('pty-1', false)
runtime.onPtyData('pty-1', 'hidden line 1\nhidden line 2\n', 100)
expect(runtime.getHeadlessTerminalBacklogDebugSnapshot()).toMatchObject({
hiddenPtyCount: 1,
deferredPtyCount: 1,
deferredChars: 'hidden line 1\nhidden line 2\n'.length
})
await expect(runtime.readTerminal(terminal.handle)).resolves.toMatchObject({
tail: ['hidden line 1', 'hidden line 2'],
latestCursor: '2'
})
const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 1000 })
expect(snapshot).toMatchObject({
source: 'headless',
seq: 'hidden line 1\nhidden line 2\n'.length
})
expect(snapshot?.data).toContain('hidden line 1')
expect(runtime.getHeadlessTerminalBacklogDebugSnapshot()).toMatchObject({
deferredPtyCount: 0,
deferredChars: 0
})
})
it('spools large hidden headless backlog outside the in-memory queue', async () => {
const runtime = createRuntime()
syncSinglePty(runtime, 'pty-1')
const hiddenOutput = `${'x'.repeat(9 * 1024 * 1024)}\nSPOOLED_HIDDEN_TAIL\n`
runtime.setPtyHeadlessTerminalVisible('pty-1', false)
runtime.onPtyData('pty-1', hiddenOutput, 100)
const headless = (
runtime as unknown as {
headlessTerminals: Map<
string,
{
deferredChunks: { data: string; outputSequence: number }[]
deferredChars: number
deferredSpoolChars: number
deferredSpoolPath?: string
}
>
}
).headlessTerminals.get('pty-1')
expect(headless?.deferredSpoolChars).toBeGreaterThan(0)
expect(headless?.deferredSpoolPath).toBeTruthy()
expect(headless?.deferredChars).toBeLessThan(hiddenOutput.length)
if (!headless) {
throw new Error('expected headless terminal state')
}
const internals = runtime as unknown as {
drainOneDeferredHeadlessChunk: (state: NonNullable<typeof headless>) => Promise<void>
}
while (headless.deferredChunks.length > 0) {
await internals.drainOneDeferredHeadlessChunk(headless)
}
expect(headless.deferredChars).toBe(0)
expect(headless.deferredSpoolChars).toBeGreaterThan(0)
const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 1000 })
expect(snapshot?.seq).toBe(hiddenOutput.length)
expect(snapshot?.data).toContain('SPOOLED_HIDDEN_TAIL')
expect(runtime.getHeadlessTerminalBacklogDebugSnapshot()).toMatchObject({
deferredPtyCount: 0,
deferredChars: 0
})
})
it('preserves deferred hidden headless order when visible output resumes', async () => {
const runtime = createRuntime()
syncSinglePty(runtime, 'pty-1')
const hiddenOutput = `${'A'.repeat(20 * 1024)}\nHIDDEN_DONE\n`
const visibleOutput = 'VISIBLE_AFTER_HIDDEN\n'
runtime.setPtyHeadlessTerminalVisible('pty-1', false)
runtime.onPtyData('pty-1', hiddenOutput, hiddenOutput.length)
runtime.setPtyHeadlessTerminalVisible('pty-1', true)
runtime.onPtyData('pty-1', visibleOutput, hiddenOutput.length + visibleOutput.length)
const snapshot = await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 1000 })
const hiddenDoneIndex = snapshot?.data.indexOf('HIDDEN_DONE') ?? -1
const visibleIndex = snapshot?.data.indexOf('VISIBLE_AFTER_HIDDEN') ?? -1
expect(hiddenDoneIndex).toBeGreaterThanOrEqual(0)
expect(visibleIndex).toBeGreaterThan(hiddenDoneIndex)
expect(snapshot?.seq).toBe(hiddenOutput.length + visibleOutput.length)
})
it('adopts renderer-seeded titles into headless main terminal snapshots', async () => {
const serializeBuffer = vi.fn().mockResolvedValue({
data: 'renderer scrollback\n',
+286 -7
View File
@@ -28,9 +28,9 @@ import {
} from '../git/repo-clone-path'
import { getGitCloneFailureMessage } from '../../shared/git-clone-failure-message'
import { createHash, randomUUID } from 'crypto'
import { homedir } from 'os'
import { homedir, tmpdir } from 'os'
import { isAbsolute, join, resolve } from 'path'
import { mkdir, readFile, readdir, rm, stat } from 'fs/promises'
import { appendFile, mkdir, readFile, readdir, rm, stat, unlink, writeFile } from 'fs/promises'
import { OrchestrationDb } from './orchestration/db'
import { formatMessagesForInjection } from './orchestration/formatter'
import type {
@@ -603,6 +603,11 @@ import {
resolveNestedRepoSelection
} from '../project-groups/nested-repo-import'
const HIDDEN_HEADLESS_DRAIN_BUDGET_MS = 2
const HIDDEN_HEADLESS_DRAIN_CONTINUE_MS = 50
const HIDDEN_HEADLESS_DRAIN_CHUNK_CHARS = 16 * 1024
const HIDDEN_HEADLESS_MEMORY_CHARS_PER_PTY = 8 * 1024 * 1024
function sanitizeNestedRepoRuntimeImportError(context: string, error: unknown): string {
console.warn(`[project-groups] ${context}`, error)
return 'Repository could not be imported'
@@ -870,6 +875,12 @@ type RuntimeHeadlessTerminal = {
// the seq actually painted into this emulator, not the latest PTY seq.
outputSequence: number
writeChain: Promise<void>
deferredChunks: { data: string; outputSequence: number }[]
deferredChars: number
deferredSpoolPath?: string
deferredSpoolStartSequence?: number
deferredSpoolChars: number
deferredSpoolWriteChain: Promise<void>
}
type HeadlessSeedMetadata = {
@@ -1696,6 +1707,9 @@ export class OrcaRuntimeService {
private ptysById = new Map<string, RuntimePtyWorktreeRecord>()
private titleObservationSequence = 0
private headlessTerminals = new Map<string, RuntimeHeadlessTerminal>()
private hiddenHeadlessPtys = new Set<string>()
private deferredHeadlessDrainTimer: ReturnType<typeof setTimeout> | null = null
private deferredHeadlessDrainRunning = false
private ptyOutputSequenceById = new Map<string, number>()
// Why: OSC 9999 status can span PTY chunks. Keeping parser state in the
// runtime lets hidden/model-owned terminals observe agent state without a
@@ -3999,6 +4013,41 @@ export class OrcaRuntimeService {
return addListenerToMap(this.dataListeners, ptyId, listener)
}
setPtyHeadlessTerminalVisible(ptyId: string, visible: boolean): void {
if (visible) {
this.hiddenHeadlessPtys.delete(ptyId)
void this.flushDeferredHeadlessTerminal(ptyId)
return
}
this.hiddenHeadlessPtys.add(ptyId)
}
getHeadlessTerminalBacklogDebugSnapshot(): {
hiddenPtyCount: number
deferredPtyCount: number
deferredChars: number
maxDeferredCharsByPty: number
} {
let deferredPtyCount = 0
let deferredChars = 0
let maxDeferredCharsByPty = 0
for (const state of this.headlessTerminals.values()) {
const stateDeferredChars = (state.deferredChars ?? 0) + (state.deferredSpoolChars ?? 0)
if (stateDeferredChars <= 0) {
continue
}
deferredPtyCount++
deferredChars += stateDeferredChars
maxDeferredCharsByPty = Math.max(maxDeferredCharsByPty, stateDeferredChars)
}
return {
hiddenPtyCount: this.hiddenHeadlessPtys.size,
deferredPtyCount,
deferredChars,
maxDeferredCharsByPty
}
}
subscribeToFitOverrideChanges(
ptyId: string,
listener: (event: { mode: 'mobile-fit' | 'desktop-fit'; cols: number; rows: number }) => void
@@ -4100,7 +4149,11 @@ export class OrcaRuntimeService {
const state: RuntimeHeadlessTerminal = {
emulator: new HeadlessEmulator({ cols: dims.cols, rows: dims.rows }),
outputSequence: 0,
writeChain: Promise.resolve()
writeChain: Promise.resolve(),
deferredChunks: [],
deferredChars: 0,
deferredSpoolChars: 0,
deferredSpoolWriteChain: Promise.resolve()
}
this.headlessTerminals.set(ptyId, state)
state.writeChain = state.writeChain
@@ -4146,7 +4199,11 @@ export class OrcaRuntimeService {
const state: RuntimeHeadlessTerminal = {
emulator: new HeadlessEmulator({ cols: dims.cols, rows: dims.rows }),
outputSequence: 0,
writeChain: Promise.resolve()
writeChain: Promise.resolve(),
deferredChunks: [],
deferredChars: 0,
deferredSpoolChars: 0,
deferredSpoolWriteChain: Promise.resolve()
}
this.headlessTerminals.set(ptyId, state)
@@ -4220,6 +4277,18 @@ export class OrcaRuntimeService {
private trackHeadlessTerminalData(ptyId: string, data: string, outputSequence: number): void {
const state = this.getOrCreateHeadlessTerminal(ptyId)
if (this.hiddenHeadlessPtys.has(ptyId) || this.hasDeferredHeadlessTerminalDataForState(state)) {
this.deferHeadlessTerminalData(ptyId, state, data, outputSequence)
return
}
this.enqueueHeadlessTerminalWrite(state, data, outputSequence)
}
private enqueueHeadlessTerminalWrite(
state: RuntimeHeadlessTerminal,
data: string,
outputSequence: number
): Promise<void> {
state.writeChain = state.writeChain
.then(async () => {
await state.emulator.write(data)
@@ -4229,6 +4298,191 @@ export class OrcaRuntimeService {
// Best-effort state tracking; live streaming must continue even if
// xterm rejects a malformed or raced write during shutdown.
})
return state.writeChain
}
private deferHeadlessTerminalData(
ptyId: string,
state: RuntimeHeadlessTerminal,
data: string,
outputSequence: number
): void {
// Why: hidden local terminals can stream megabytes from agents. Keep raw
// bytes ordered for later snapshots, but avoid parsing every byte inline.
for (let offset = 0; offset < data.length; offset += HIDDEN_HEADLESS_DRAIN_CHUNK_CHARS) {
const chunk = data.slice(offset, offset + HIDDEN_HEADLESS_DRAIN_CHUNK_CHARS)
const chunkSequence = outputSequence - (data.length - offset - chunk.length)
this.enqueueDeferredHeadlessChunk(state, chunk, chunkSequence)
}
this.scheduleDeferredHeadlessDrain(HIDDEN_HEADLESS_DRAIN_CONTINUE_MS)
}
private enqueueDeferredHeadlessChunk(
state: RuntimeHeadlessTerminal,
data: string,
outputSequence: number
): void {
if (
!state.deferredSpoolPath &&
state.deferredChars + data.length <= HIDDEN_HEADLESS_MEMORY_CHARS_PER_PTY
) {
state.deferredChunks.push({ data, outputSequence })
state.deferredChars += data.length
return
}
const path = this.getDeferredHeadlessSpoolPath(state, outputSequence - data.length)
state.deferredSpoolChars += data.length
state.deferredSpoolWriteChain = state.deferredSpoolWriteChain
.then(async () => {
if (state.deferredSpoolStartSequence === outputSequence - data.length) {
// Why: hidden terminal output may contain command output or secrets.
// Create the spill file owner-only before appending raw PTY bytes.
await writeFile(path, '', { flag: 'wx', mode: 0o600 })
}
await appendFile(path, data, 'utf8')
})
.catch(() => {
// Why: hidden restore must stay non-lossy even if temp-file spooling
// fails. Fall back to memory rather than dropping terminal bytes.
state.deferredSpoolChars = Math.max(0, state.deferredSpoolChars - data.length)
state.deferredChunks.push({ data, outputSequence })
state.deferredChars += data.length
})
}
private getDeferredHeadlessSpoolPath(
state: RuntimeHeadlessTerminal,
startSequence: number
): string {
if (state.deferredSpoolPath) {
return state.deferredSpoolPath
}
const path = join(tmpdir(), `orca-hidden-headless-${randomUUID()}.log`)
state.deferredSpoolPath = path
state.deferredSpoolStartSequence = startSequence
state.deferredSpoolWriteChain = Promise.resolve()
return path
}
private scheduleDeferredHeadlessDrain(delayMs: number): void {
if (this.deferredHeadlessDrainTimer || this.deferredHeadlessDrainRunning) {
return
}
if (!this.hasDeferredHeadlessTerminalData()) {
return
}
this.deferredHeadlessDrainTimer = setTimeout(() => {
this.deferredHeadlessDrainTimer = null
void this.drainDeferredHeadlessTerminalsWithinBudget()
}, delayMs)
}
private hasDeferredHeadlessTerminalData(): boolean {
for (const state of this.headlessTerminals.values()) {
if (this.hasDeferredHeadlessTerminalDataForState(state)) {
return true
}
}
return false
}
private hasDeferredHeadlessTerminalDataForState(state: RuntimeHeadlessTerminal): boolean {
return (state.deferredChunks?.length ?? 0) > 0 || (state.deferredSpoolChars ?? 0) > 0
}
private async drainDeferredHeadlessTerminalsWithinBudget(): Promise<void> {
if (this.deferredHeadlessDrainRunning) {
return
}
this.deferredHeadlessDrainRunning = true
const startedAt = Date.now()
try {
for (const [ptyId, state] of this.headlessTerminals) {
if (
!this.hiddenHeadlessPtys.has(ptyId) ||
!this.hasDeferredHeadlessTerminalDataForState(state)
) {
continue
}
await this.drainOneDeferredHeadlessChunk(state)
if (Date.now() - startedAt >= HIDDEN_HEADLESS_DRAIN_BUDGET_MS) {
break
}
}
} finally {
this.deferredHeadlessDrainRunning = false
}
this.scheduleDeferredHeadlessDrain(HIDDEN_HEADLESS_DRAIN_CONTINUE_MS)
}
private async flushDeferredHeadlessTerminal(ptyId: string): Promise<void> {
const state = this.headlessTerminals.get(ptyId)
if (!state) {
return
}
while (this.hasDeferredHeadlessTerminalDataForState(state)) {
await this.drainOneDeferredHeadlessChunk(state)
}
}
private async drainOneDeferredHeadlessChunk(state: RuntimeHeadlessTerminal): Promise<void> {
if ((state.deferredChunks?.length ?? 0) === 0 && (state.deferredSpoolChars ?? 0) > 0) {
await this.restoreDeferredHeadlessSpoolToMemory(state)
}
const chunk = state.deferredChunks?.shift()
if (!chunk) {
return
}
state.deferredChars = Math.max(0, state.deferredChars - chunk.data.length)
await this.enqueueHeadlessTerminalWrite(state, chunk.data, chunk.outputSequence)
}
private async restoreDeferredHeadlessSpoolToMemory(
state: RuntimeHeadlessTerminal
): Promise<void> {
const path = state.deferredSpoolPath
const startSequence = state.deferredSpoolStartSequence
const writeChain = state.deferredSpoolWriteChain ?? Promise.resolve()
if (!path || typeof startSequence !== 'number') {
state.deferredSpoolPath = undefined
state.deferredSpoolStartSequence = undefined
state.deferredSpoolChars = 0
state.deferredSpoolWriteChain = Promise.resolve()
return
}
state.deferredSpoolPath = undefined
state.deferredSpoolStartSequence = undefined
state.deferredSpoolChars = 0
state.deferredSpoolWriteChain = Promise.resolve()
await writeChain
let data = ''
try {
data = await readFile(path, 'utf8')
} finally {
await unlink(path).catch(() => undefined)
}
for (let offset = 0; offset < data.length; offset += HIDDEN_HEADLESS_DRAIN_CHUNK_CHARS) {
const chunk = data.slice(offset, offset + HIDDEN_HEADLESS_DRAIN_CHUNK_CHARS)
state.deferredChunks.push({
data: chunk,
outputSequence: startSequence + offset + chunk.length
})
state.deferredChars += chunk.length
}
}
private async clearDeferredHeadlessSpool(state: RuntimeHeadlessTerminal): Promise<void> {
const path = state.deferredSpoolPath
const writeChain = state.deferredSpoolWriteChain ?? Promise.resolve()
state.deferredSpoolPath = undefined
state.deferredSpoolStartSequence = undefined
state.deferredSpoolChars = 0
state.deferredSpoolWriteChain = Promise.resolve()
if (!path) {
return
}
await writeChain.catch(() => undefined)
await unlink(path).catch(() => undefined)
}
private getOrCreateHeadlessTerminal(ptyId: string): RuntimeHeadlessTerminal {
@@ -4240,14 +4494,28 @@ export class OrcaRuntimeService {
const state: RuntimeHeadlessTerminal = {
emulator: new HeadlessEmulator({ cols: size.cols, rows: size.rows }),
outputSequence: 0,
writeChain: Promise.resolve()
writeChain: Promise.resolve(),
deferredChunks: [],
deferredChars: 0,
deferredSpoolChars: 0,
deferredSpoolWriteChain: Promise.resolve()
}
this.headlessTerminals.set(ptyId, state)
return state
}
private resizeHeadlessTerminal(ptyId: string, cols: number, rows: number): void {
this.headlessTerminals.get(ptyId)?.emulator.resize(cols, rows)
const state = this.headlessTerminals.get(ptyId)
if (!state) {
return
}
if (this.hasDeferredHeadlessTerminalDataForState(state)) {
void this.flushDeferredHeadlessTerminal(ptyId).then(() => {
state.emulator.resize(cols, rows)
})
return
}
state.emulator.resize(cols, rows)
}
private async clearHeadlessTerminalBuffer(ptyId: string): Promise<void> {
@@ -4255,6 +4523,9 @@ export class OrcaRuntimeService {
if (!state) {
return
}
state.deferredChunks = []
state.deferredChars = 0
await this.clearDeferredHeadlessSpool(state)
// Why: headless writes are queued to preserve xterm parser order. Clear
// must join that same chain or an earlier PTY chunk can finish after the
// clear request and repopulate mobile scrollback.
@@ -4372,7 +4643,13 @@ export class OrcaRuntimeService {
if (!state) {
return null
}
await state.writeChain
if (this.hasDeferredHeadlessTerminalDataForState(state)) {
await this.flushDeferredHeadlessTerminal(ptyId)
await state.writeChain
} else {
const writeChain = state.writeChain
await writeChain
}
// Why: when an alternate-screen TUI (Claude Code, vim, etc.) is currently
// active, the visible content is the alt-screen snapshot — replaying any
// normal-buffer scrollback before it can duplicate shell prompts and
@@ -4399,11 +4676,13 @@ export class OrcaRuntimeService {
private disposeHeadlessTerminal(ptyId: string): void {
this.headlessHydrationState.delete(ptyId)
this.hiddenHeadlessPtys.delete(ptyId)
const state = this.headlessTerminals.get(ptyId)
if (!state) {
return
}
this.headlessTerminals.delete(ptyId)
void this.clearDeferredHeadlessSpool(state)
state.writeChain.finally(() => state.emulator.dispose()).catch(() => state.emulator.dispose())
}
+6
View File
@@ -1037,6 +1037,7 @@ export type PreloadApi = {
ackColdRestore: (id: string) => void
ackData: (id: string, charCount: number) => void
setActiveRendererPty: (id: string, active: boolean) => void
setVisibleRendererPty: (id: string, visible: boolean) => void
hasChildProcesses: (id: string) => Promise<boolean>
getForegroundProcess: (id: string) => Promise<string | null>
getCwd: (id: string) => Promise<string>
@@ -1066,6 +1067,10 @@ export type PreloadApi = {
peakRendererInFlightChars: number
peakMaxRendererInFlightCharsByPty: number
ackGatedFlushSkipCount: number
hiddenHeadlessPtyCount: number
deferredHeadlessPtyCount: number
deferredHeadlessChars: number
maxDeferredHeadlessCharsByPty: number
}>
resetRendererDeliveryDebug: () => Promise<void>
onData: (
@@ -1073,6 +1078,7 @@ export type PreloadApi = {
) => () => void
onReplay: (callback: (data: { id: string; data: string }) => void) => () => void
onExit: (callback: (data: { id: string; code: number }) => void) => () => void
onRendererOutputSkipped: (callback: (data: { id: string }) => void) => () => void
onSerializeBufferRequest: (
callback: (data: {
requestId: string
+13
View File
@@ -748,6 +748,9 @@ const api = {
setActiveRendererPty: (id: string, active: boolean): void => {
ipcRenderer.send('pty:setActiveRendererPty', { id, active })
},
setVisibleRendererPty: (id: string, visible: boolean): void => {
ipcRenderer.send('pty:setVisibleRendererPty', { id, visible })
},
kill: (id: string, opts?: { keepHistory?: boolean }): Promise<void> =>
ipcRenderer.invoke('pty:kill', { id, keepHistory: opts?.keepHistory ?? false }),
@@ -781,6 +784,10 @@ const api = {
peakRendererInFlightChars: number
peakMaxRendererInFlightCharsByPty: number
ackGatedFlushSkipCount: number
hiddenHeadlessPtyCount: number
deferredHeadlessPtyCount: number
deferredHeadlessChars: number
maxDeferredHeadlessCharsByPty: number
}> => ipcRenderer.invoke('pty:getRendererDeliveryDebugSnapshot'),
resetRendererDeliveryDebug: (): Promise<void> =>
@@ -824,6 +831,12 @@ const api = {
return () => ipcRenderer.removeListener('pty:exit', listener)
},
onRendererOutputSkipped: (callback: (data: { id: string }) => void): (() => void) => {
const listener = (_event: Electron.IpcRendererEvent, data: { id: string }) => callback(data)
ipcRenderer.on('pty:rendererOutputSkipped', listener)
return () => ipcRenderer.removeListener('pty:rendererOutputSkipped', listener)
},
onSerializeBufferRequest: (
callback: (data: {
requestId: string
@@ -83,7 +83,6 @@ vi.mock('react', async () => {
memo: <T>(component: T) => component,
useEffect: () => {},
useLayoutEffect: () => {},
useCallback: <T extends (...args: never[]) => unknown>(callback: T) => callback,
useMemo: <T>(factory: () => T) => factory(),
useRef: <T>(current: T) => ({ current }),
useState: <T>(initial: T | (() => T)) => {
@@ -29,6 +29,7 @@ const LEAF_1 = '11111111-1111-4111-8111-111111111111' as const
const LEAF_2 = '22222222-2222-4222-8222-222222222222' as const
const AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS = 250
const AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS = 1_500
const HIDDEN_RESTORE_CLEAR_SEQUENCE = '\x1b[2J\x1b[3J\x1b[H'
function leafIdForPane(paneId: number): string {
return paneId === 2 ? LEAF_2 : LEAF_1
@@ -3243,50 +3244,7 @@ describe('connectPanePty', () => {
expect(transport.sendInput).not.toHaveBeenCalled()
})
it('keeps non-visible local PTY bytes on the live xterm path for release', async () => {
const pendingTimeouts: (() => void)[] = []
const originalSetTimeout = globalThis.setTimeout
globalThis.setTimeout = vi.fn((fn: () => void) => {
pendingTimeouts.push(fn)
return 999 as unknown as ReturnType<typeof setTimeout>
}) as unknown as typeof setTimeout
try {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
}
)
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps({
isVisibleRef: { current: false }
})
connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks(6)
expect(capturedDataCallback.current).not.toBeNull()
capturedDataCallback.current?.('hello\r\n')
expect(pane.terminal.write).not.toHaveBeenCalledWith('hello\r\n')
for (const fn of pendingTimeouts) {
fn()
}
expect(pane.terminal.write).toHaveBeenCalledWith('hello\r\n')
} finally {
globalThis.setTimeout = originalSetTimeout
}
})
it('keeps visually rich hidden PTY bytes on the live xterm path', async () => {
it('blanks hidden local PTY bytes instead of keeping them live', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
@@ -3306,21 +3264,18 @@ describe('connectPanePty', () => {
await flushAsyncTicks(6)
expect(capturedDataCallback.current).not.toBeNull()
vi.useFakeTimers()
try {
const hiddenTuiChunk = '\x1b[2J\x1b[H╭ table 😀 ╮\r\n'
capturedDataCallback.current?.(hiddenTuiChunk)
capturedDataCallback.current?.('hello\r\n')
expect(pane.terminal.write).not.toHaveBeenCalledWith(hiddenTuiChunk)
vi.advanceTimersByTime(50)
expect(pane.terminal.write).toHaveBeenCalledWith(hiddenTuiChunk)
expect(window.api.pty.getMainBufferSnapshot).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
expect(pane.terminal.write).toHaveBeenCalledWith(
HIDDEN_RESTORE_CLEAR_SEQUENCE,
expect.any(Function)
)
expect(pane.terminal.write).not.toHaveBeenCalledWith('hello\r\n')
expect(pane.terminal.write).not.toHaveBeenCalledWith('hello\r\n', expect.any(Function))
expect(window.api.pty.getMainBufferSnapshot).not.toHaveBeenCalled()
})
it('keeps split hidden synchronized output frames on the live xterm path', async () => {
it('blanks visually rich hidden PTY bytes instead of parsing them live', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
@@ -3340,23 +3295,53 @@ describe('connectPanePty', () => {
await flushAsyncTicks(6)
expect(capturedDataCallback.current).not.toBeNull()
vi.useFakeTimers()
try {
const startChunk = '\x1b[?2026h'
const plainRowChunk = '| Sam Syntax | Compiler | Online |\r\n'
const endChunk = 'LONG_TABLE_SCROLL_RESTORE_marker\r\n\x1b[?2026l'
const hiddenTuiChunk = '\x1b[2J\x1b[H╭ table 😀 ╮\r\n'
capturedDataCallback.current?.(hiddenTuiChunk)
capturedDataCallback.current?.(startChunk)
capturedDataCallback.current?.(plainRowChunk)
capturedDataCallback.current?.(endChunk)
expect(pane.terminal.write).toHaveBeenCalledWith(
HIDDEN_RESTORE_CLEAR_SEQUENCE,
expect.any(Function)
)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hiddenTuiChunk)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hiddenTuiChunk, expect.any(Function))
expect(window.api.pty.getMainBufferSnapshot).not.toHaveBeenCalled()
})
expect(pane.terminal.write).not.toHaveBeenCalledWith(plainRowChunk)
vi.advanceTimersByTime(50)
expect(pane.terminal.write).toHaveBeenCalledWith(`${startChunk}${plainRowChunk}${endChunk}`)
expect(window.api.pty.getMainBufferSnapshot).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
it('blanks split hidden synchronized output frames once instead of parsing them live', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-id')
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
})
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps({
isVisibleRef: { current: false }
})
connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks(6)
expect(capturedDataCallback.current).not.toBeNull()
const startChunk = '\x1b[?2026h'
const plainRowChunk = '| Sam Syntax | Compiler | Online |\r\n'
const endChunk = 'LONG_TABLE_SCROLL_RESTORE_marker\r\n\x1b[?2026l'
capturedDataCallback.current?.(startChunk)
capturedDataCallback.current?.(plainRowChunk)
capturedDataCallback.current?.(endChunk)
const clearWrites = pane.terminal.write.mock.calls.filter(
([data]) => data === HIDDEN_RESTORE_CLEAR_SEQUENCE
)
expect(clearWrites).toHaveLength(1)
expect(pane.terminal.write).not.toHaveBeenCalledWith(plainRowChunk)
expect(pane.terminal.write).not.toHaveBeenCalledWith(`${startChunk}${plainRowChunk}${endChunk}`)
expect(window.api.pty.getMainBufferSnapshot).not.toHaveBeenCalled()
})
it('queues visible split-pane PTY bytes when the pane is not active', async () => {
@@ -4265,7 +4250,7 @@ describe('connectPanePty', () => {
binding.dispose()
})
it('writes ordinary hidden output live instead of proactively restoring a snapshot', async () => {
it('restores ordinary hidden local output from a main snapshot when visible', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-id')
const capturedDataCallback: {
@@ -4285,7 +4270,7 @@ describe('connectPanePty', () => {
data: `snapshot-with-${hidden}`,
cols: 100,
rows: 30,
seq: hidden.length + live.length
seq: hidden.length
})
const pane = createPane(1)
@@ -4297,6 +4282,11 @@ describe('connectPanePty', () => {
await flushAsyncTicks(6)
capturedDataCallback.current?.(hidden, { seq: hidden.length, rawLength: hidden.length })
expect(pane.terminal.write).toHaveBeenCalledWith(
HIDDEN_RESTORE_CLEAR_SEQUENCE,
expect.any(Function)
)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hidden)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hidden, expect.any(Function))
;(deps.isVisibleRef as { current: boolean }).current = true
@@ -4306,23 +4296,28 @@ describe('connectPanePty', () => {
})
await flushAsyncTicks(20)
expect(getMainBufferSnapshot).not.toHaveBeenCalled()
expect(pane.terminal.write).toHaveBeenCalledWith(hidden)
expect(getMainBufferSnapshot).toHaveBeenCalledWith('pty-id', { scrollbackRows: 5000 })
expect(pane.terminal.write).toHaveBeenCalledWith(
`snapshot-with-${hidden}`,
expect.any(Function)
)
expect(pane.terminal.write).toHaveBeenCalledWith(live, expect.any(Function))
disposable.dispose()
})
it('writes ordinary hidden remote runtime output live instead of restoring a snapshot', async () => {
it('restores ordinary hidden remote runtime output from a transport snapshot', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('remote:env-1@@terminal-1')
const capturedDataCallback: {
current: ((data: string, meta?: { seq?: number; rawLength?: number }) => void) | null
} = { current: null }
const hidden = 'hidden remote output\r\n'
const live = 'visible remote output\r\n'
transport.serializeBuffer = vi.fn().mockResolvedValue({
data: 'remote snapshot\r\n',
cols: 120,
rows: 40,
seq: 40,
seq: hidden.length,
source: 'headless'
})
transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
@@ -4340,9 +4335,12 @@ describe('connectPanePty', () => {
const disposable = connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks(6)
const hidden = 'hidden remote output\r\n'
const live = 'visible remote output\r\n'
capturedDataCallback.current?.(hidden, { seq: hidden.length, rawLength: hidden.length })
expect(pane.terminal.write).toHaveBeenCalledWith(
HIDDEN_RESTORE_CLEAR_SEQUENCE,
expect.any(Function)
)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hidden)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hidden, expect.any(Function))
;(deps.isVisibleRef as { current: boolean }).current = true
@@ -4353,13 +4351,13 @@ describe('connectPanePty', () => {
await flushAsyncTicks(20)
expect(getMainBufferSnapshot).not.toHaveBeenCalled()
expect(transport.serializeBuffer).not.toHaveBeenCalled()
expect(pane.terminal.write).toHaveBeenCalledWith(hidden)
expect(transport.serializeBuffer).toHaveBeenCalledWith({ scrollbackRows: 5000 })
expect(pane.terminal.write).toHaveBeenCalledWith('remote snapshot\r\n', expect.any(Function))
expect(pane.terminal.write).toHaveBeenCalledWith(live, expect.any(Function))
disposable.dispose()
})
it('keeps inactive split-pane hidden output live instead of deferring snapshot restore', async () => {
it('defers inactive split-pane hidden restore instead of parsing hidden output live', async () => {
const { resetHiddenOutputRestoreSchedulerForTests } =
await import('./hidden-output-restore-scheduler')
let disposable: { dispose: () => void } | null = null
@@ -4383,7 +4381,7 @@ describe('connectPanePty', () => {
data: 'inactive snapshot\r\n',
cols: 100,
rows: 30,
seq: 64
seq: 'hidden inactive output\r\n'.length
})
const pane = createPane(1)
@@ -4397,6 +4395,11 @@ describe('connectPanePty', () => {
const live = 'visible inactive output\r\n'
expect(capturedDataCallback.current).not.toBeNull()
capturedDataCallback.current?.(hidden, { seq: hidden.length, rawLength: hidden.length })
expect(pane.terminal.write).toHaveBeenCalledWith(
HIDDEN_RESTORE_CLEAR_SEQUENCE,
expect.any(Function)
)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hidden)
;(deps.isVisibleRef as { current: boolean }).current = true
capturedDataCallback.current?.(live, {
seq: hidden.length + live.length,
@@ -4411,8 +4414,11 @@ describe('connectPanePty', () => {
await new Promise((resolve) => setTimeout(resolve, 30))
await flushAsyncTicks(20)
expect(getMainBufferSnapshot).not.toHaveBeenCalled()
expect(pane.terminal.write).toHaveBeenCalledWith(hidden)
expect(getMainBufferSnapshot).toHaveBeenCalledWith('pty-id', { scrollbackRows: 5000 })
expect(pane.terminal.write).toHaveBeenCalledWith(
'inactive snapshot\r\n',
expect.any(Function)
)
expect(pane.terminal.write).toHaveBeenCalledWith(live, expect.any(Function))
} finally {
disposable?.dispose()
@@ -4478,17 +4484,19 @@ describe('connectPanePty', () => {
}
})
it('does not retry remote snapshots for ordinary hidden runtime output', async () => {
it('retries a deferred remote snapshot for ordinary hidden runtime output', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('remote:env-1@@terminal-1')
const capturedDataCallback: {
current: ((data: string, meta?: { seq?: number; rawLength?: number }) => void) | null
} = { current: null }
const hidden = 'hidden remote output\r\n'
const firstLive = 'first visible output\r\n'
transport.serializeBuffer = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce({
data: 'remote recovered snapshot\r\n',
cols: 120,
rows: 40,
seq: 80,
seq: hidden.length,
source: 'headless'
})
transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
@@ -4503,9 +4511,11 @@ describe('connectPanePty', () => {
const disposable = connectPanePty(pane as never, manager as never, deps as never)
await flushAsyncTicks(6)
const hidden = 'hidden remote output\r\n'
const firstLive = 'first visible output\r\n'
capturedDataCallback.current?.(hidden, { seq: hidden.length, rawLength: hidden.length })
expect(pane.terminal.write).toHaveBeenCalledWith(
HIDDEN_RESTORE_CLEAR_SEQUENCE,
expect.any(Function)
)
;(deps.isVisibleRef as { current: boolean }).current = true
capturedDataCallback.current?.(firstLive, {
@@ -4514,7 +4524,7 @@ describe('connectPanePty', () => {
})
await flushAsyncTicks(20)
expect(transport.serializeBuffer).not.toHaveBeenCalled()
expect(transport.serializeBuffer).toHaveBeenCalledTimes(1)
expect(pane.terminal.write).not.toHaveBeenCalledWith(
expect.stringContaining('Orca skipped hidden terminal output'),
expect.any(Function)
@@ -4527,7 +4537,11 @@ describe('connectPanePty', () => {
await new Promise((resolve) => setTimeout(resolve, 80))
await flushAsyncTicks(20)
expect(transport.serializeBuffer).not.toHaveBeenCalled()
expect(transport.serializeBuffer).toHaveBeenCalledTimes(2)
expect(pane.terminal.write).toHaveBeenCalledWith(
'remote recovered snapshot\r\n',
expect.any(Function)
)
expect(pane.terminal.write).toHaveBeenCalledWith(firstLive, expect.any(Function))
disposable.dispose()
})
@@ -4564,7 +4578,12 @@ describe('connectPanePty', () => {
await flushAsyncTicks(6)
capturedDataCallback.current?.(hidden, { seq: hidden.length, rawLength: hidden.length })
expect(pane.terminal.write).not.toHaveBeenCalled()
expect(pane.terminal.write).toHaveBeenCalledWith(
HIDDEN_RESTORE_CLEAR_SEQUENCE,
expect.any(Function)
)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hidden)
expect(pane.terminal.write).not.toHaveBeenCalledWith(hidden, expect.any(Function))
;(deps.isVisibleRef as { current: boolean }).current = true
capturedDataCallback.current?.(live, {
@@ -4714,6 +4733,9 @@ describe('connectPanePty', () => {
})
await flushAsyncTicks(2)
expect(clearBufferCallback.current).not.toBeNull()
const clearWritesBeforeExplicitClear = pane.terminal.write.mock.calls.filter(
([data]) => data === HIDDEN_RESTORE_CLEAR_SEQUENCE
).length
clearBufferCallback.current?.({ ptyId: 'pty-id' })
snapshot.resolve({
@@ -4726,10 +4748,10 @@ describe('connectPanePty', () => {
expect(pane.terminal.clear).toHaveBeenCalled()
expect(pane.terminal.write).not.toHaveBeenCalledWith(live, expect.any(Function))
expect(pane.terminal.write).not.toHaveBeenCalledWith(
'\x1b[2J\x1b[3J\x1b[H',
expect.any(Function)
)
const clearWritesAfterExplicitClear = pane.terminal.write.mock.calls.filter(
([data]) => data === HIDDEN_RESTORE_CLEAR_SEQUENCE
).length
expect(clearWritesAfterExplicitClear).toBe(clearWritesBeforeExplicitClear)
disposable.dispose()
})
@@ -1332,6 +1332,12 @@ export function connectPanePty(
const onPtySpawn = (ptyId: string): void => {
setPanePtyFitBinding(ptyId)
if (!isRemoteRuntimePtyId(ptyId)) {
window.api.pty.setVisibleRendererPty?.(
ptyId,
shouldWritePtyOutputForeground(deps.isVisibleRef.current)
)
}
deps.syncPanePtyLayoutBinding(pane.id, ptyId)
deps.updateTabPtyId(deps.tabId, ptyId)
// Why: Command Code has no prompt-start hook. Seed the visible working row
@@ -1691,6 +1697,15 @@ export function connectPanePty(
? createRemoteRuntimePtyTransport(runtimeEnvironmentId, transportOptions)
: createIpcPtyTransport(transportOptions)
deps.paneTransportsRef.current.set(pane.id, transport)
{
const ptyId = transport.getPtyId()
if (ptyId && !isRemoteRuntimePtyId(ptyId)) {
window.api.pty.setVisibleRendererPty?.(
ptyId,
shouldWritePtyOutputForeground(deps.isVisibleRef.current)
)
}
}
const conptyDeviceAttributesDisposable = isNativeWindowsConpty
? installConptyDeviceAttributesHandler({
parser: pane.terminal.parser,
@@ -2054,6 +2069,7 @@ export function connectPanePty(
callbacks: {
onData: dataCallback,
onReplayData: replayDataCallback,
onRendererOutputSkipped: handleMainSkippedRendererOutput,
onError: reportError
}
})
@@ -2182,6 +2198,7 @@ export function connectPanePty(
const shouldSnapshotHiddenCodexOutput = shouldKeepHiddenStartupRendererQueriesLive(paneStartup)
let hiddenStartupRendererQueryPending = ''
let hiddenRendererStateDirty = false
let hiddenRendererBlankedForRestore = false
function canUseMainBufferSnapshot(ptyId: string | null): ptyId is string {
return Boolean(ptyId) && !isRemoteRuntimePtyId(ptyId)
@@ -2411,11 +2428,7 @@ export function connectPanePty(
}
function shouldSkipHiddenRendererOutput(foreground: boolean, data: string): boolean {
if (
foreground ||
!shouldSnapshotHiddenCodexOutput ||
!canUseHiddenOutputSnapshot(transport.getPtyId())
) {
if (foreground || !canUseHiddenOutputSnapshot(transport.getPtyId())) {
return false
}
// Why: CPR/DECRQM replies depend on ordered terminal state. Keep the rare
@@ -2527,6 +2540,7 @@ export function connectPanePty(
function skipHiddenRendererOutput(data: string): void {
writeHiddenStartupRendererQueries(data)
respondToSkippedMode2031Subscribe(data)
blankStaleRendererForHiddenRestore()
markHiddenOutputRestoreNeeded()
hiddenRendererStateDirty = true
if (hiddenOutputRestoreInFlight) {
@@ -2535,6 +2549,15 @@ export function connectPanePty(
recordHiddenRendererSkip(data.length)
}
function handleMainSkippedRendererOutput(): void {
blankStaleRendererForHiddenRestore()
markHiddenOutputRestoreNeeded()
hiddenRendererStateDirty = true
if (hiddenOutputRestoreInFlight) {
hiddenOutputRestoreFreshSnapshotNeeded = true
}
}
function queueLiveChunkDuringRestore(data: string, meta?: PtyDataMeta): void {
if (!data) {
return
@@ -2673,6 +2696,7 @@ export function connectPanePty(
clearPendingLiveChunksDuringRestore()
hiddenStartupRendererQueryPending = ''
hiddenRendererStateDirty = false
hiddenRendererBlankedForRestore = false
hiddenOutputRestoreNeeded = false
hiddenOutputRestorePtyId = null
hiddenOutputRestoreGeneration += 1
@@ -2706,6 +2730,17 @@ export function connectPanePty(
})
}
function blankStaleRendererForHiddenRestore(): void {
if (hiddenRendererBlankedForRestore || !canUseHiddenOutputSnapshot(transport.getPtyId())) {
return
}
// Why: once hidden bytes are skipped, the renderer xterm is stale. Clear
// it once so refocus shows a blank restore window instead of old output.
discardTerminalOutput(pane.terminal)
writeReplayData('\x1b[2J\x1b[3J\x1b[H')
hiddenRendererBlankedForRestore = true
}
function captureScrollStateForSnapshotReplay(): ScrollState | null {
const buf = pane.terminal.buffer?.active
if (!buf) {
@@ -2756,6 +2791,7 @@ export function connectPanePty(
writeReplayData(snapshot.data)
writeReplayData(POST_REPLAY_LIVE_SNAPSHOT_RESET)
hiddenRendererStateDirty = false
hiddenRendererBlankedForRestore = false
recordTerminalOutput(pane.terminal)
const currentPtyId = transport.getPtyId()
if (currentPtyId && !getFitOverrideForPty(currentPtyId)) {
@@ -3298,6 +3334,7 @@ export function connectPanePty(
callbacks: {
onData: dataCallback,
onReplayData: replayDataCallback,
onRendererOutputSkipped: handleMainSkippedRendererOutput,
onError: (message) => {
if (isSshSessionExpiredError(message)) {
expiredReattachError = true
@@ -3454,6 +3491,7 @@ export function connectPanePty(
callbacks: {
onData: dataCallback,
onReplayData: replayDataCallback,
onRendererOutputSkipped: handleMainSkippedRendererOutput,
onError: (message) => {
if (isSshSessionExpiredError(message)) {
expiredReattachError = true
@@ -3542,6 +3580,7 @@ export function connectPanePty(
callbacks: {
onData: dataCallback,
onReplayData: replayDataCallback,
onRendererOutputSkipped: handleMainSkippedRendererOutput,
onError: reportError
}
})
@@ -3597,6 +3636,7 @@ export function connectPanePty(
callbacks: {
onData: dataCallback,
onReplayData: replayDataCallback,
onRendererOutputSkipped: handleMainSkippedRendererOutput,
onError: reportError
}
})
@@ -3650,6 +3690,12 @@ export function connectPanePty(
unregisterDocumentVisibilityRecovery?.()
unregisterDocumentVisibilityRecovery = null
clearPanePtyFitBinding()
{
const ptyId = transport.getPtyId()
if (ptyId && !isRemoteRuntimePtyId(ptyId)) {
window.api.pty.setVisibleRendererPty?.(ptyId, false)
}
}
discardTerminalOutput(pane.terminal)
unregisterE2ePtyDataInjection()
if (agentTaskCompleteSettingsUnsubscribe !== null) {
@@ -28,6 +28,7 @@ export type PtyBufferSnapshot = {
}
export const ptyDataHandlers = new Map<string, (data: string, meta?: PtyDataMeta) => void>()
export const ptyRendererOutputSkippedHandlers = new Map<string, () => void>()
/** Sidecar subscriptions that observe PTY data without owning the primary
* handler. Used by features that need to react to the live byte stream
* (e.g. agent-paste-draft watching for DECSET 2004 / bracketed-paste-
@@ -83,6 +84,7 @@ let ptyDispatcherAttached = false
export function unregisterPtyDataHandlers(ptyIds: string[]): void {
for (const id of ptyIds) {
ptyDataHandlers.delete(id)
ptyRendererOutputSkippedHandlers.delete(id)
ptyReplayHandlers.delete(id)
ptyTeardownHandlers.get(id)?.()
ptyTeardownHandlers.delete(id)
@@ -142,6 +144,9 @@ export function ensurePtyDispatcher(): void {
}
}
})
window.api.pty.onRendererOutputSkipped((payload) => {
ptyRendererOutputSkippedHandlers.get(payload.id)?.()
})
}
export function subscribeToPtyExit(ptyId: string, watcher: (code: number) => void): () => void {
@@ -260,6 +265,7 @@ export function registerEagerPtyBuffer(
// reference). After attach() replaces the handler this becomes a no-op.
if (ptyDataHandlers.get(ptyId) === dataHandler) {
ptyDataHandlers.delete(ptyId)
ptyRendererOutputSkippedHandlers.delete(ptyId)
ptyReplayHandlers.delete(ptyId)
}
if (ptyExitHandlers.get(ptyId) === exitHandler) {
@@ -304,6 +310,7 @@ export type PtyTransport = {
* the replay guard — otherwise xterm auto-replies to embedded query
* sequences leak into the shell. See replay-guard.ts. */
onReplayData?: (data: string) => void
onRendererOutputSkipped?: () => void
onStatus?: (shell: string) => void
onError?: (message: string, errors?: string[]) => void
onExit?: (code: number) => void
@@ -325,6 +332,7 @@ export type PtyTransport = {
onData?: (data: string, meta?: PtyDataMeta) => void
/** See note on connect.callbacks.onReplayData. */
onReplayData?: (data: string) => void
onRendererOutputSkipped?: () => void
onStatus?: (shell: string) => void
onError?: (message: string, errors?: string[]) => void
onExit?: (code: number) => void
@@ -11,6 +11,7 @@ import {
} from '../../../../shared/agent-detection'
import {
ptyDataHandlers,
ptyRendererOutputSkippedHandlers,
ptyReplayHandlers,
ptyExitHandlers,
ptyTeardownHandlers,
@@ -461,6 +462,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
function unregisterPtyHandlers(id: string): void {
ptyDataHandlers.delete(id)
ptyRendererOutputSkippedHandlers.delete(id)
ptyReplayHandlers.delete(id)
ptyExitHandlers.delete(id)
ptyTeardownHandlers.delete(id)
@@ -468,6 +470,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
function unregisterPtyDataAndStatusHandlers(id: string): void {
ptyDataHandlers.delete(id)
ptyRendererOutputSkippedHandlers.delete(id)
ptyReplayHandlers.delete(id)
}
@@ -501,6 +504,9 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
meta
)
})
ptyRendererOutputSkippedHandlers.set(id, () => {
storedCallbacks.onRendererOutputSkipped?.()
})
}
function clearAccumulatedState(): void {
@@ -109,6 +109,19 @@ function reportActiveRendererPtyForPane(
}
}
function reportVisibleRendererPtys(
paneTransports: Map<number, PtyTransport>,
visible: boolean
): void {
for (const transport of paneTransports.values()) {
const ptyId = transport.getPtyId()
if (!ptyId || ptyId.startsWith('remote:')) {
continue
}
window.api.pty.setVisibleRendererPty?.(ptyId, visible)
}
}
type UseTerminalPaneLifecycleDeps = {
tabId: string
worktreeId: string
@@ -432,6 +445,11 @@ export function useTerminalPaneLifecycle({
send()
}
useEffect(() => {
reportVisibleRendererPtys(paneTransportsRef.current, isActive && isVisible)
return () => reportVisibleRendererPtys(paneTransportsRef.current, false)
}, [isActive, isVisible, paneTransportsRef])
// Initialize PaneManager instance once
useEffect(() => {
const container = containerRef.current
+7 -1
View File
@@ -2328,6 +2328,7 @@ function createPtyApi(): NonNullable<Partial<PreloadApi>['pty']> {
ackColdRestore: () => {},
ackData: () => {},
setActiveRendererPty: () => {},
setVisibleRendererPty: () => {},
hasChildProcesses: () => Promise.resolve(false),
getForegroundProcess: () => Promise.resolve(null),
getCwd: () => Promise.resolve('~'),
@@ -2347,12 +2348,17 @@ function createPtyApi(): NonNullable<Partial<PreloadApi>['pty']> {
peakMaxPendingCharsByPty: 0,
peakRendererInFlightChars: 0,
peakMaxRendererInFlightCharsByPty: 0,
ackGatedFlushSkipCount: 0
ackGatedFlushSkipCount: 0,
hiddenHeadlessPtyCount: 0,
deferredHeadlessPtyCount: 0,
deferredHeadlessChars: 0,
maxDeferredHeadlessCharsByPty: 0
}),
resetRendererDeliveryDebug: () => Promise.resolve(),
onData: () => noopUnsubscribe,
onReplay: () => noopUnsubscribe,
onExit: () => noopUnsubscribe,
onRendererOutputSkipped: () => noopUnsubscribe,
onSerializeBufferRequest: () => noopUnsubscribe,
onClearBufferRequest: () => noopUnsubscribe,
sendSerializedBuffer: () => {},
@@ -0,0 +1,171 @@
import type { Page } from '@stablyai/playwright-test'
export type TerminalLivenessClassification =
| 'no-active-pane'
| 'no-pty-binding'
| 'pty-backend-not-echoing'
| 'xterm-buffer-not-updating'
| 'terminal-layer-healthy'
export type TerminalLivenessProbe = {
marker: string
elapsedMs: number | null
worktreeId: string | null
tabId: string | null
pane: {
exists: boolean
paneId: number | null
leafId: string | null
ptyId: string | null
serializedTail: string
serializedContainsMarker: boolean
textareaFocused: boolean
canvasCount: number
xtermElementConnected: boolean
}
store: {
ptyIdsForTab: string[]
activeTabType: string | null
}
mainBuffer: {
available: boolean
containsMarker: boolean
tail: string
}
renderingDiagnostics: unknown[]
schedulerDebug: unknown | null
}
export function classifyTerminalLivenessProbe(
probe: TerminalLivenessProbe
): TerminalLivenessClassification {
if (!probe.pane.exists) {
return 'no-active-pane'
}
if (!probe.pane.ptyId || !probe.store.ptyIdsForTab.includes(probe.pane.ptyId)) {
return 'no-pty-binding'
}
if (!probe.mainBuffer.available || !probe.mainBuffer.containsMarker) {
return 'pty-backend-not-echoing'
}
if (!probe.pane.serializedContainsMarker) {
return 'xterm-buffer-not-updating'
}
return 'terminal-layer-healthy'
}
type ProbeOptions = {
marker?: string
commandTimeoutMs?: number
pollIntervalMs?: number
}
const DEFAULT_COMMAND_TIMEOUT_MS = 2_000
const DEFAULT_POLL_INTERVAL_MS = 50
function makeMarker(): string {
return `ORCA_TERMINAL_LIVENESS_${Date.now()}_${Math.random().toString(16).slice(2)}`
}
export async function probeActiveTerminalLiveness(
page: Page,
options: ProbeOptions = {}
): Promise<TerminalLivenessProbe> {
const marker = options.marker ?? makeMarker()
const initial = await readActiveTerminalLivenessSnapshot(page, marker)
if (!initial.pane.ptyId) {
return initial
}
const start = performance.now()
await page.evaluate(
({ ptyId, marker }) => {
window.api.pty.write(ptyId, `printf '\\n${marker}\\n'\r`)
},
{ ptyId: initial.pane.ptyId, marker }
)
const timeoutMs = options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS
let latest = await readActiveTerminalLivenessSnapshot(page, marker)
while (performance.now() - start < timeoutMs) {
if (latest.mainBuffer.containsMarker && latest.pane.serializedContainsMarker) {
return { ...latest, elapsedMs: performance.now() - start }
}
await page.waitForTimeout(pollIntervalMs)
latest = await readActiveTerminalLivenessSnapshot(page, marker)
}
return { ...latest, elapsedMs: null }
}
export async function readActiveTerminalLivenessSnapshot(
page: Page,
marker: string
): Promise<TerminalLivenessProbe> {
return page.evaluate(async (marker) => {
const store = window.__store ?? null
const state = store?.getState?.() ?? null
const worktreeId = state?.activeWorktreeId ?? null
const tabs = worktreeId ? (state?.tabsByWorktree?.[worktreeId] ?? []) : []
const preferredTabId =
state?.activeTabType === 'terminal'
? (state.activeTabId ?? null)
: worktreeId
? (state?.activeTabIdByWorktree?.[worktreeId] ?? null)
: null
const tabId =
preferredTabId && tabs.some((tab) => tab.id === preferredTabId)
? preferredTabId
: (tabs[0]?.id ?? null)
const manager = tabId ? (window.__paneManagers?.get(tabId) ?? null) : null
const activePane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
const ptyId = activePane?.container?.dataset?.ptyId ?? null
const serialized = activePane?.serializeAddon?.serialize?.({ scrollback: 200 }) ?? ''
const textarea = activePane?.container?.querySelector?.('.xterm-helper-textarea') ?? null
const diagnostics = manager?.getRenderingDiagnostics?.() ?? []
const schedulerDebug = window.__terminalOutputSchedulerDebug?.snapshot?.() ?? null
let mainBufferAvailable = false
let mainBufferTail = ''
if (ptyId) {
try {
const snapshot = await window.api.pty.getMainBufferSnapshot(ptyId, {
scrollbackRows: 200
})
mainBufferAvailable = Boolean(snapshot)
mainBufferTail = snapshot?.data?.slice(-4000) ?? ''
} catch {
mainBufferAvailable = false
}
}
return {
marker,
elapsedMs: null,
worktreeId,
tabId,
pane: {
exists: Boolean(activePane),
paneId: activePane?.id ?? null,
leafId: activePane?.leafId ?? null,
ptyId,
serializedTail: serialized.slice(-4000),
serializedContainsMarker: serialized.includes(marker),
textareaFocused: document.activeElement === textarea,
canvasCount: activePane?.container?.querySelectorAll?.('canvas')?.length ?? 0,
xtermElementConnected: Boolean(activePane?.terminal?.element?.isConnected)
},
store: {
ptyIdsForTab: tabId ? (state?.ptyIdsByTabId?.[tabId] ?? []) : [],
activeTabType: state?.activeTabType ?? null
},
mainBuffer: {
available: mainBufferAvailable,
containsMarker: mainBufferTail.includes(marker),
tail: mainBufferTail
},
renderingDiagnostics: diagnostics,
schedulerDebug
}
}, marker)
}
@@ -0,0 +1,400 @@
import type { Page } from '@stablyai/playwright-test'
import { randomUUID } from 'node:crypto'
import { rmSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { test, expect } from './helpers/orca-app'
import {
ensureTerminalVisible,
getActiveWorktreeId,
getAllWorktreeIds,
switchToWorktree,
waitForActiveWorktree,
waitForSessionReady
} from './helpers/store'
import {
focusActiveTerminalInput,
sendToTerminal,
splitActiveTerminalPane,
waitForActivePanePtyId,
waitForActiveTerminalManager,
waitForPaneIdentitySnapshot
} from './helpers/terminal'
import {
classifyTerminalLivenessProbe,
probeActiveTerminalLiveness,
type TerminalLivenessClassification
} from './helpers/terminal-liveness-diagnostics'
type BackgroundPressureSnapshot = {
probeIndex: number
elapsedMs: number | null
worktreeId: string | null
tabId: string | null
paneCount: number
pressurePaneCount: number
pressureOutputMiB: number
appRendererMemoryMiB: number | null
appTotalMemoryMiB: number | null
classification: TerminalLivenessClassification
mainBufferContainsMarker: boolean
xtermContainsMarker: boolean
hasWebgl: boolean
webglDisabledAfterContextLoss: boolean
schedulerQueuedChars: number | null
schedulerPeakQueuedChars: number | null
mainPendingChars: number | null
mainRendererInFlightChars: number | null
hiddenHeadlessPtyCount: number | null
deferredHeadlessPtyCount: number | null
deferredHeadlessChars: number | null
maxDeferredHeadlessCharsByPty: number | null
activePtyId: string | null
}
const DEFAULT_PANE_COUNT = 8
const DEFAULT_PRESSURE_MIB_PER_PANE = 4
const DEFAULT_PROBE_COUNT = 4
function readPositiveIntEnv(name: string, fallback: number): number {
const value = process.env[name]
if (!value) {
return fallback
}
const parsed = Number.parseInt(value, 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback
}
function pressureOutputScript(runId: string): string {
return `
const paneIndex = process.argv[2] ?? '0'
const targetChars = Number(process.argv[3] ?? '0')
const chunkBody = '#'.repeat(8192)
let written = 0
process.stdout.write('ORCA_BG_PRESSURE_START_${runId}_' + paneIndex + '\\n')
function writeMore() {
let canContinue = true
while (canContinue && written < targetChars) {
const frame = String(written).padStart(8, '0')
const chunk = '\\x1b[?2026h\\x1b[1;1Hbackground pane=' + paneIndex + ' frame=' + frame + ' ' + chunkBody + '\\x1b[?2026l\\n'
written += chunk.length
canContinue = process.stdout.write(chunk)
}
if (written < targetChars) {
process.stdout.once('drain', writeMore)
return
}
process.stdout.write('ORCA_BG_PRESSURE_DONE_${runId}_' + paneIndex + '\\n')
}
writeMore()
`
}
async function ensurePaneCount(
page: Page,
paneCount: number
): Promise<Awaited<ReturnType<typeof waitForPaneIdentitySnapshot>>> {
let snapshot = await waitForPaneIdentitySnapshot(page, 1)
while (snapshot.panes.length < paneCount) {
await splitActiveTerminalPane(page, snapshot.panes.length % 2 === 0 ? 'horizontal' : 'vertical')
snapshot = await waitForPaneIdentitySnapshot(page, snapshot.panes.length + 1)
}
return snapshot
}
async function focusPane(page: Page, tabId: string, leafId: string): Promise<void> {
await page.evaluate(
({ tabId, leafId }) => {
const manager = window.__paneManagers?.get(tabId)
const pane = manager?.getPanes?.().find((candidate) => candidate.leafId === leafId)
if (!manager || !pane) {
throw new Error(`Unable to focus pane ${tabId}:${leafId}`)
}
manager.setActivePane(pane.id, { focus: true })
},
{ tabId, leafId }
)
}
async function resetDebugCounters(page: Page): Promise<void> {
await page.evaluate(async () => {
window.__terminalOutputSchedulerDebug?.reset?.()
await window.api.pty.resetRendererDeliveryDebug()
})
}
async function readResourceManagerAppMemory(page: Page): Promise<{
appRendererMemoryMiB: number | null
appTotalMemoryMiB: number | null
}> {
return page.evaluate(async () => {
try {
const snapshot = await window.api.memory.getSnapshot()
return {
appRendererMemoryMiB: Math.round(snapshot.app.renderer.memory / 1024 / 1024),
appTotalMemoryMiB: Math.round(snapshot.app.memory / 1024 / 1024)
}
} catch {
return { appRendererMemoryMiB: null, appTotalMemoryMiB: null }
}
})
}
async function readMainPressureDebug(page: Page): Promise<{
mainPendingChars: number | null
mainRendererInFlightChars: number | null
hiddenHeadlessPtyCount: number | null
deferredHeadlessPtyCount: number | null
deferredHeadlessChars: number | null
maxDeferredHeadlessCharsByPty: number | null
}> {
return page.evaluate(async () => {
const snapshot = await window.api.pty.getRendererDeliveryDebugSnapshot()
return {
mainPendingChars: snapshot?.pendingChars ?? null,
mainRendererInFlightChars: snapshot?.rendererInFlightChars ?? null,
hiddenHeadlessPtyCount: snapshot?.hiddenHeadlessPtyCount ?? null,
deferredHeadlessPtyCount: snapshot?.deferredHeadlessPtyCount ?? null,
deferredHeadlessChars: snapshot?.deferredHeadlessChars ?? null,
maxDeferredHeadlessCharsByPty: snapshot?.maxDeferredHeadlessCharsByPty ?? null
}
})
}
function readRenderingState(probe: Awaited<ReturnType<typeof probeActiveTerminalLiveness>>): {
hasWebgl: boolean
webglDisabledAfterContextLoss: boolean
} {
const diagnostic = probe.renderingDiagnostics[0] as
| { hasWebgl?: boolean; webglDisabledAfterContextLoss?: boolean }
| undefined
return {
hasWebgl: diagnostic?.hasWebgl === true,
webglDisabledAfterContextLoss: diagnostic?.webglDisabledAfterContextLoss === true
}
}
function readSchedulerState(probe: Awaited<ReturnType<typeof probeActiveTerminalLiveness>>): {
schedulerQueuedChars: number | null
schedulerPeakQueuedChars: number | null
} {
const scheduler = probe.schedulerDebug as {
queuedChars?: unknown
peakQueuedChars?: unknown
} | null
return {
schedulerQueuedChars: typeof scheduler?.queuedChars === 'number' ? scheduler.queuedChars : null,
schedulerPeakQueuedChars:
typeof scheduler?.peakQueuedChars === 'number' ? scheduler.peakQueuedChars : null
}
}
test.describe('Terminal liveness during background pane pressure @headful', () => {
test('keeps the active terminal classified while sibling panes stream output', async ({
orcaPage,
testRepoPath
}, testInfo) => {
test.skip(
process.env.ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE !== '1',
'Set ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE=1 to run the background terminal pressure probe'
)
test.setTimeout(240_000)
await waitForSessionReady(orcaPage)
await waitForActiveWorktree(orcaPage)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
await waitForActivePanePtyId(orcaPage, 30_000)
const paneCount = readPositiveIntEnv('ORCA_E2E_TERMINAL_BACKGROUND_PANES', DEFAULT_PANE_COUNT)
const pressureMiB = readPositiveIntEnv(
'ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE_MIB_PER_PANE',
DEFAULT_PRESSURE_MIB_PER_PANE
)
const probeCount = readPositiveIntEnv(
'ORCA_E2E_TERMINAL_BACKGROUND_PROBES',
DEFAULT_PROBE_COUNT
)
const livenessTimeoutMs = readPositiveIntEnv('ORCA_E2E_TERMINAL_LIVENESS_TIMEOUT_MS', 2_000)
const pressureOutputChars = pressureMiB * 1024 * 1024
const runId = randomUUID()
const scriptPath = path.join(testRepoPath, `.orca-bg-pressure-${runId}.mjs`)
writeFileSync(scriptPath, pressureOutputScript(runId))
const snapshots: BackgroundPressureSnapshot[] = []
try {
const layout = await ensurePaneCount(orcaPage, paneCount)
const [activePane, ...pressurePanes] = layout.panes
if (!activePane?.ptyId) {
throw new Error('Active pane has no PTY')
}
await focusPane(orcaPage, layout.tabId, activePane.leafId)
await focusActiveTerminalInput(orcaPage)
await resetDebugCounters(orcaPage)
await Promise.all(
pressurePanes.map((pane, paneIndex) => {
if (!pane.ptyId) {
throw new Error(`Pressure pane ${pane.leafId} has no PTY`)
}
return sendToTerminal(
orcaPage,
pane.ptyId,
`node ${JSON.stringify(scriptPath)} ${paneIndex} ${pressureOutputChars}\r`
)
})
)
for (let probeIndex = 1; probeIndex <= probeCount; probeIndex += 1) {
await orcaPage.waitForTimeout(250)
await focusPane(orcaPage, layout.tabId, activePane.leafId)
const probe = await probeActiveTerminalLiveness(orcaPage, {
marker: `ORCA_BG_LIVENESS_${probeIndex}_${Date.now()}`,
commandTimeoutMs: livenessTimeoutMs
})
const memory = await readResourceManagerAppMemory(orcaPage)
const mainPressure = await readMainPressureDebug(orcaPage)
const rendering = readRenderingState(probe)
const scheduler = readSchedulerState(probe)
snapshots.push({
probeIndex,
elapsedMs: probe.elapsedMs === null ? null : Math.round(probe.elapsedMs * 10) / 10,
worktreeId: probe.worktreeId,
tabId: probe.tabId,
paneCount: layout.panes.length,
pressurePaneCount: pressurePanes.length,
pressureOutputMiB: pressureMiB,
...memory,
classification: classifyTerminalLivenessProbe(probe),
mainBufferContainsMarker: probe.mainBuffer.containsMarker,
xtermContainsMarker: probe.pane.serializedContainsMarker,
...rendering,
...scheduler,
...mainPressure,
activePtyId: probe.pane.ptyId
})
}
} finally {
await sendToTerminal(orcaPage, await waitForActivePanePtyId(orcaPage), '\x03').catch(
() => undefined
)
rmSync(scriptPath, { force: true })
}
const summary = JSON.stringify(snapshots)
process.stdout.write(`\n[terminal-background-pressure] ${summary}\n`)
testInfo.annotations.push({ type: 'terminal-background-pressure', description: summary })
expect(snapshots.map((snapshot) => snapshot.classification)).toEqual(
Array.from({ length: probeCount }, () => 'terminal-layer-healthy')
)
})
test('keeps active workspace terminal classified while another workspace streams output', async ({
orcaPage,
testRepoPath
}, testInfo) => {
test.skip(
process.env.ORCA_E2E_TERMINAL_CROSS_WORKSPACE_PRESSURE !== '1',
'Set ORCA_E2E_TERMINAL_CROSS_WORKSPACE_PRESSURE=1 to run the cross-workspace pressure probe'
)
test.setTimeout(240_000)
await waitForSessionReady(orcaPage)
const firstWorktreeId = await waitForActiveWorktree(orcaPage)
const allWorktreeIds = await getAllWorktreeIds(orcaPage)
const secondWorktreeId = allWorktreeIds.find((id) => id !== firstWorktreeId)
test.skip(!secondWorktreeId, 'Cross-workspace pressure probe needs the seeded second worktree')
if (!secondWorktreeId) {
return
}
const paneCount = readPositiveIntEnv('ORCA_E2E_TERMINAL_BACKGROUND_PANES', DEFAULT_PANE_COUNT)
const pressureMiB = readPositiveIntEnv(
'ORCA_E2E_TERMINAL_BACKGROUND_PRESSURE_MIB_PER_PANE',
DEFAULT_PRESSURE_MIB_PER_PANE
)
const probeCount = readPositiveIntEnv(
'ORCA_E2E_TERMINAL_BACKGROUND_PROBES',
DEFAULT_PROBE_COUNT
)
const livenessTimeoutMs = readPositiveIntEnv('ORCA_E2E_TERMINAL_LIVENESS_TIMEOUT_MS', 2_000)
const pressureOutputChars = pressureMiB * 1024 * 1024
const runId = randomUUID()
const scriptPath = path.join(testRepoPath, `.orca-cross-pressure-${runId}.mjs`)
writeFileSync(scriptPath, pressureOutputScript(runId))
const snapshots: BackgroundPressureSnapshot[] = []
try {
await switchToWorktree(orcaPage, secondWorktreeId)
await expect
.poll(() => getActiveWorktreeId(orcaPage), { timeout: 10_000 })
.toBe(secondWorktreeId)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
await waitForActivePanePtyId(orcaPage, 30_000)
const hiddenLayout = await ensurePaneCount(orcaPage, paneCount)
await resetDebugCounters(orcaPage)
await Promise.all(
hiddenLayout.panes.map((pane, paneIndex) => {
if (!pane.ptyId) {
throw new Error(`Pressure pane ${pane.leafId} has no PTY`)
}
return sendToTerminal(
orcaPage,
pane.ptyId,
`node ${JSON.stringify(scriptPath)} ${paneIndex} ${pressureOutputChars}\r`
)
})
)
await switchToWorktree(orcaPage, firstWorktreeId)
await expect
.poll(() => getActiveWorktreeId(orcaPage), { timeout: 10_000 })
.toBe(firstWorktreeId)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
await waitForActivePanePtyId(orcaPage, 30_000)
for (let probeIndex = 1; probeIndex <= probeCount; probeIndex += 1) {
await orcaPage.waitForTimeout(250)
const probe = await probeActiveTerminalLiveness(orcaPage, {
marker: `ORCA_CROSS_BG_LIVENESS_${probeIndex}_${Date.now()}`,
commandTimeoutMs: livenessTimeoutMs
})
const memory = await readResourceManagerAppMemory(orcaPage)
const mainPressure = await readMainPressureDebug(orcaPage)
const rendering = readRenderingState(probe)
const scheduler = readSchedulerState(probe)
snapshots.push({
probeIndex,
elapsedMs: probe.elapsedMs === null ? null : Math.round(probe.elapsedMs * 10) / 10,
worktreeId: probe.worktreeId,
tabId: probe.tabId,
paneCount: hiddenLayout.panes.length + 1,
pressurePaneCount: hiddenLayout.panes.length,
pressureOutputMiB: pressureMiB,
...memory,
classification: classifyTerminalLivenessProbe(probe),
mainBufferContainsMarker: probe.mainBuffer.containsMarker,
xtermContainsMarker: probe.pane.serializedContainsMarker,
...rendering,
...scheduler,
...mainPressure,
activePtyId: probe.pane.ptyId
})
}
} finally {
rmSync(scriptPath, { force: true })
}
const summary = JSON.stringify(snapshots)
process.stdout.write(`\n[terminal-cross-workspace-pressure] ${summary}\n`)
testInfo.annotations.push({ type: 'terminal-cross-workspace-pressure', description: summary })
expect(snapshots.map((snapshot) => snapshot.classification)).toEqual(
Array.from({ length: probeCount }, () => 'terminal-layer-healthy')
)
expect(snapshots.every((snapshot) => snapshot.worktreeId === firstWorktreeId)).toBe(true)
})
})
@@ -0,0 +1,335 @@
import type { Page, TestInfo } from '@stablyai/playwright-test'
import { expect } from '@stablyai/playwright-test'
import { randomUUID } from 'node:crypto'
import { existsSync, rmSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { test } from './helpers/orca-app'
import {
ensureTerminalVisible,
getActiveWorktreeId,
getAllWorktreeIds,
switchToWorktree,
waitForActiveWorktree,
waitForSessionReady
} from './helpers/store'
import {
getTerminalContent,
sendToTerminal,
waitForActiveTerminalManager,
waitForPaneIdentitySnapshot
} from './helpers/terminal'
type RestoreFrameSample = {
index: number
timestampMs: number
elapsedMs: number
active: boolean
hasPane: boolean
paneVisible: boolean
hasBaseline: boolean
hasFinalMarker: boolean
lastBurstLine: number | null
textLength: number
baseY: number | null
viewportY: number | null
cursorY: number | null
preview: string
}
type RestoreFrameRecorder = {
done: boolean
samples: RestoreFrameSample[]
}
type RestoreFrameRecorderWindow = Window & {
__hiddenRestoreFrameRecorder?: RestoreFrameRecorder
}
const HIDDEN_BURST_LINE_COUNT = 1000
const FRAME_SAMPLE_COUNT = 18
function hiddenBurstLine(runId: string, line: number): string {
return `HIDDEN_RESTORE_${runId}_${String(line).padStart(4, '0')}`
}
function writeHiddenBurstScript(
scriptPath: string,
donePath: string,
runId: string,
lineCount: number
): void {
const lines = Array.from({ length: lineCount }, (_, index) => hiddenBurstLine(runId, index + 1))
writeFileSync(
scriptPath,
[
"const { writeFileSync } = require('node:fs')",
`const lines = ${JSON.stringify(lines)}`,
"process.stdout.write(`${lines.join('\\n')}\\n`, () => {",
` writeFileSync(${JSON.stringify(donePath)}, 'done')`,
'})'
].join('\n')
)
}
async function startRestoreFrameRecorder(
page: Page,
targetWorktreeId: string,
runId: string,
baselineMarker: string,
finalMarker: string
): Promise<void> {
await page.evaluate(
({ targetWorktreeId, runId, baselineMarker, finalMarker, sampleCount }) => {
const target = window as RestoreFrameRecorderWindow
const recorder: RestoreFrameRecorder = { done: false, samples: [] }
target.__hiddenRestoreFrameRecorder = recorder
let observedTargetWorkspace = false
let sampleIndex = 0
const startedAt = performance.now()
const linePrefix = `HIDDEN_RESTORE_${runId}_`
const readLastBurstLine = (text: string): number | null => {
let last: number | null = null
let index = text.indexOf(linePrefix)
while (index >= 0) {
const start = index + linePrefix.length
const parsed = Number(text.slice(start, start + 4))
if (Number.isInteger(parsed)) {
last = parsed
}
index = text.indexOf(linePrefix, start)
}
return last
}
const isElementVisible = (element: HTMLElement | null | undefined): boolean => {
if (!element) {
return false
}
const rect = element.getBoundingClientRect()
if (rect.width <= 0 || rect.height <= 0) {
return false
}
let current: HTMLElement | null = element
while (current) {
const style = window.getComputedStyle(current)
if (
style.display === 'none' ||
style.visibility === 'hidden' ||
Number(style.opacity) === 0
) {
return false
}
current = current.parentElement
}
return true
}
const collectSample = (): void => {
const timestampMs = performance.now()
const store = window.__store
const state = store?.getState()
const active = state?.activeWorktreeId === targetWorktreeId
observedTargetWorkspace ||= active
if (active || observedTargetWorkspace) {
const tabId =
state?.activeTabType === 'terminal'
? state.activeTabId
: targetWorktreeId
? (state?.activeTabIdByWorktree?.[targetWorktreeId] ?? null)
: null
const manager = tabId ? window.__paneManagers?.get(tabId) : null
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
const text = pane?.serializeAddon?.serialize?.() ?? ''
const buffer = pane?.terminal?.buffer?.active
recorder.samples.push({
index: sampleIndex,
timestampMs,
elapsedMs: timestampMs - startedAt,
active,
hasPane: Boolean(pane),
paneVisible: isElementVisible(pane?.container),
hasBaseline: text.includes(baselineMarker),
hasFinalMarker: text.includes(finalMarker),
lastBurstLine: readLastBurstLine(text),
textLength: text.length,
baseY: typeof buffer?.baseY === 'number' ? buffer.baseY : null,
viewportY: typeof buffer?.viewportY === 'number' ? buffer.viewportY : null,
cursorY: typeof buffer?.cursorY === 'number' ? buffer.cursorY : null,
preview: text.slice(-240)
})
sampleIndex += 1
}
if (sampleIndex >= sampleCount) {
recorder.done = true
return
}
requestAnimationFrame(collectSample)
}
requestAnimationFrame(collectSample)
},
{ targetWorktreeId, runId, baselineMarker, finalMarker, sampleCount: FRAME_SAMPLE_COUNT }
)
}
async function readRestoreFrameRecorder(page: Page): Promise<RestoreFrameRecorder> {
return page.evaluate(() => {
return (
(window as RestoreFrameRecorderWindow).__hiddenRestoreFrameRecorder ?? {
done: false,
samples: []
}
)
})
}
async function attachRestoreFrameSamples(
testInfo: TestInfo,
samples: RestoreFrameSample[]
): Promise<void> {
const samplesPath = testInfo.outputPath('hidden-restore-frame-samples.json')
writeFileSync(samplesPath, `${JSON.stringify(samples, null, 2)}\n`)
await testInfo.attach('hidden-restore-frame-samples.json', {
path: samplesPath,
contentType: 'application/json'
})
}
test.describe('Hidden terminal restore catch-up artifacts', () => {
test('blanks stale renderer content before showing a 1000-line hidden burst restored', async ({
orcaPage,
testRepoPath
}, testInfo) => {
await waitForSessionReady(orcaPage)
const firstWorktreeId = await waitForActiveWorktree(orcaPage)
const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find(
(id) => id !== firstWorktreeId
)
test.skip(!secondWorktreeId, 'hidden restore catch-up guard needs a second worktree')
if (!secondWorktreeId) {
return
}
await switchToWorktree(orcaPage, secondWorktreeId)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
const hiddenSnapshot = await waitForPaneIdentitySnapshot(orcaPage, 1)
const hiddenPane = hiddenSnapshot.panes[0]
if (!hiddenPane?.ptyId) {
throw new Error('hidden restore catch-up pane did not bind a PTY')
}
const runId = randomUUID()
const baselineMarker = `VISIBLE_BEFORE_HIDDEN_RESTORE_${runId}`
await sendToTerminal(
orcaPage,
hiddenPane.ptyId,
`printf '%s\\n' ${JSON.stringify(baselineMarker)}\r`
)
await expect
.poll(() => getTerminalContent(orcaPage, 20_000), {
timeout: 10_000,
message: 'baseline terminal content did not render before hiding'
})
.toContain(baselineMarker)
await switchToWorktree(orcaPage, firstWorktreeId)
await expect
.poll(() => getActiveWorktreeId(orcaPage), {
timeout: 10_000,
message: 'first worktree did not become active before hidden burst'
})
.toBe(firstWorktreeId)
const scriptPath = path.join(testRepoPath, `.orca-hidden-restore-burst-${runId}.cjs`)
const donePath = path.join(testRepoPath, `.orca-hidden-restore-burst-${runId}.done`)
const firstLine = hiddenBurstLine(runId, 1)
const finalMarker = hiddenBurstLine(runId, HIDDEN_BURST_LINE_COUNT)
writeHiddenBurstScript(scriptPath, donePath, runId, HIDDEN_BURST_LINE_COUNT)
await orcaPage.evaluate(() => window.api.pty.resetRendererDeliveryDebug())
await sendToTerminal(orcaPage, hiddenPane.ptyId, `node ${JSON.stringify(scriptPath)}\r`)
await expect
.poll(() => existsSync(donePath), {
timeout: 10_000,
message: 'hidden 1000-line burst script did not finish'
})
.toBe(true)
await expect
.poll(
async () => {
const snapshot = await orcaPage.evaluate(() =>
window.api.pty.getRendererDeliveryDebugSnapshot()
)
return snapshot.deferredHeadlessChars
},
{
timeout: 10_000,
message: 'hidden burst did not exercise deferred headless restore path'
}
)
.toBeGreaterThan(20_000)
await startRestoreFrameRecorder(orcaPage, secondWorktreeId, runId, baselineMarker, finalMarker)
await switchToWorktree(orcaPage, secondWorktreeId)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
await expect
.poll(() => readRestoreFrameRecorder(orcaPage).then((recorder) => recorder.done), {
timeout: 10_000,
message: 'hidden restore frame recorder did not collect visible samples'
})
.toBe(true)
const recorder = await readRestoreFrameRecorder(orcaPage)
await attachRestoreFrameSamples(testInfo, recorder.samples)
const visibleSamples = recorder.samples.filter((sample) => sample.active && sample.paneVisible)
expect(visibleSamples.length).toBeGreaterThanOrEqual(6)
const staleSamples = visibleSamples.filter(
(sample) => sample.hasBaseline && !sample.hasFinalMarker && sample.lastBurstLine === null
)
expect(staleSamples, JSON.stringify(staleSamples, null, 2)).toEqual([])
const partialCatchupSamples = visibleSamples.filter(
(sample) => sample.lastBurstLine !== null && sample.lastBurstLine !== HIDDEN_BURST_LINE_COUNT
)
expect(partialCatchupSamples, JSON.stringify(partialCatchupSamples, null, 2)).toEqual([])
const firstRestoredFrameIndex = visibleSamples.findIndex(
(sample) => sample.hasFinalMarker && sample.lastBurstLine === HIDDEN_BURST_LINE_COUNT
)
expect(firstRestoredFrameIndex).toBeGreaterThanOrEqual(0)
const preRestoreSamples = visibleSamples.slice(0, firstRestoredFrameIndex)
const nonBlankPreRestoreSamples = preRestoreSamples.filter(
(sample) => sample.textLength > 128 || sample.lastBurstLine !== null || sample.hasFinalMarker
)
expect(nonBlankPreRestoreSamples, JSON.stringify(nonBlankPreRestoreSamples, null, 2)).toEqual(
[]
)
const postRestoreIncompleteSamples = visibleSamples
.slice(firstRestoredFrameIndex)
.filter(
(sample) => !sample.hasFinalMarker || sample.lastBurstLine !== HIDDEN_BURST_LINE_COUNT
)
expect(
postRestoreIncompleteSamples,
JSON.stringify(postRestoreIncompleteSamples, null, 2)
).toEqual([])
const finalContent = await getTerminalContent(orcaPage, 200_000)
expect(finalContent).toContain(firstLine)
expect(finalContent).toContain(finalMarker)
expect(finalContent).not.toContain('Orca skipped hidden terminal output')
rmSync(scriptPath, { force: true })
rmSync(donePath, { force: true })
})
})