Repository navigation
perf(terminal): let main skip parsing visible local daemon terminals - #27086
outof-place wants to merge 8 commits into
Conversation
…renderers can't pace agents A hidden pane whose PTY a raw-byte sidecar watches (background-launched and automation agents) kept the hidden-delivery gate off for the whole PTY, so its hidden xterm parsed every byte and main paced the producer to that parse. The parse runs on renderer timers, which Chromium throttles for hidden pages (one wake-up a minute after ~5 minutes), so a flooding agent slowed to tens of KB/s and blocked on its own writes. Delivery interest now only decides who receives the bytes, not whether the view is gated. For a hidden PTY with interest, main sends chunks flagged sidecarOnly. The renderer hands them to sidecars only and credits them on receipt. The view skips them like a gated drop and restores from the model on reveal, and main answers the PTY's terminal queries meanwhile. Co-Authored-By: Claude Opus 5.5 <[email protected]>
📝 Walkthrough
Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to The reported handoff issue may leave in-flight terminal queries unanswered. Resolve that concern and strengthen the dormancy tests before merging. Pre-merge checks |
|
e41169b to
ddaa5c6
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
b2b12d3b-2cd5-4e38-924e-4a32fe48b2fe
📥 Commits
Reviewing files that changed from the base of the PR and between e41169bd4a233f428bb6ced1170f588f288b2a88 and ddaa5c6144b1f9a18f0a46a9adccae952b433d25.
📒 Files selected for processing (20)
src/main/ipc/pty-hidden-delivery-gate.test.tssrc/main/ipc/pty-hidden-delivery-gate.tssrc/main/ipc/pty-ipc-hidden-delivery-gate.test.tssrc/main/ipc/pty/delivery/payload.tssrc/main/ipc/pty/runtime/controller.tssrc/main/ipc/pty/session.tssrc/main/runtime/main-terminal-model-dormancy.test.tssrc/main/runtime/main-terminal-model-dormancy.tssrc/main/runtime/orca-runtime-main-terminal-model-dormancy.tssrc/main/runtime/orca-runtime-tests/main-terminal-model-dormancy.spec.tssrc/main/runtime/runtime-pty-controller-contract.tssrc/main/runtime/terminal-model-query-authority.test.tssrc/main/runtime/terminal-model-query-authority.tssrc/main/runtime/terminal-query-responder.test.tssrc/preload/api/pty-api.tssrc/preload/api/pty-bridge-stream-and-serialization.tssrc/renderer/src/components/terminal-pane/pty-dispatcher-sidecar-only.test.tssrc/renderer/src/components/terminal-pane/pty-dispatcher.tssrc/renderer/src/components/terminal-pane/pty-sidecar-only-delivery.tstests/e2e/terminal-hidden-sidecar-pacing.spec.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| state.seedCoverageSeq = snapshot.seq | ||
| state.outputSequence = Math.max(state.outputSequence, snapshot.seq) | ||
| return owns() ? snapshot.seq : null |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Find how getPtyOutputSequence is defined, and where outputSequence advances in onPtyData.
rg -nP -C6 '\bgetPtyOutputSequence\s*\(' src/main/runtime
rg -nP -C4 'outputSequence\s*(\+=|=)' src/main/runtime/orca-runtime-on-pty-data.ts
rg -nP -C6 'seedCoverageSeq' src/main/runtimeRepository: stablyai/orca
Length of output: 41738
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- dormancy helper ---'
nl -ba src/main/runtime/main-terminal-model-dormancy.ts | sed -n '1,230p'
printf '%s\n' '--- runtime dormancy ---'
nl -ba src/main/runtime/orca-runtime-main-terminal-model-dormancy.ts | sed -n '1,240p'
printf '%s\n' '--- live ingestion / chunk handling ---'
nl -ba src/main/runtime/orca-runtime-maybe-hydrate-headless-from-renderer.ts | sed -n '160,235p'
nl -ba src/main/runtime/orca-runtime-on-pty-data.ts | sed -n '1,100p'
printf '%s\n' '--- handoff symbols ---'
rg -n -F -- 'setHiddenDeliveryModelHandoff' src/main/runtimeRepository: stablyai/orca
Length of output: 29160
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- seed coverage helper ---'
nl -ba src/main/runtime/main-terminal-model-dormancy.ts | sed -n '223,290p'
printf '%s\n' '--- provider snapshot serializer ---'
rg -n -F -- 'serializeProviderTerminalBuffer' src/main/runtime src/main/providers src/main/ipc || true
rg -n -F -- 'serializeRendererTerminalBuffer' src/main/runtime
printf '%s\n' '--- hidden delivery gate ---'
nl -ba src/main/ipc/pty-hidden-delivery-gate.ts | sed -n '1,280p'
printf '%s\n' '--- relevant snapshot sequence checks ---'
rg -n -P -C8 'snapshot\.seq|outputSequenceBefore|outputSequenceAfter|serializeProviderTerminalBuffer' src/main/runtime/orca-runtime-serialize-provider-terminal-buffer.ts src/main/runtime/orca-runtime-serialize-main-terminal-buffer.ts src/main/runtime/rpc src/main/providers 2>/dev/null || trueRepository: stablyai/orca
Length of output: 22457
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- provider serializer implementation ---'
nl -ba src/main/runtime/orca-runtime-serialize-terminal-buffer-from-available-state.ts | sed -n '100,180p'
rg -n -P -C8 'serializeProviderTerminalBuffer|PtyProviderBufferSnapshot|seq:' src/main/runtime/orca-runtime-serialize-provider-terminal-buffer.ts src/main/runtime src/main/providers 2>/dev/null || true
printf '%s\n' '--- hidden-delivery consumers ---'
rg -n -P -C8 'shouldDropHiddenRendererPtyData|shouldDeliverHiddenRendererPtyDataToSidecarsOnly|isHiddenRendererPtyViewGated|modelHandoff' src/main src/rendererRepository: stablyai/orca
Length of output: 45665
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- provider serializer implementation ---'
nl -ba src/main/runtime/orca-runtime-serialize-terminal-buffer-from-available-state.ts | sed -n '100,180p'
printf '%s\n' '--- provider snapshot definitions and consumers ---'
rg -n -P -C10 'serializeProviderTerminalBuffer|PtyProviderBufferSnapshot|snapshot\.seq' src/main/runtime src/main/providers src/shared 2>/dev/null || true
printf '%s\n' '--- hidden delivery consumers ---'
rg -n -P -C10 'shouldDropHiddenRendererPtyData|shouldDeliverHiddenRendererPtyDataToSidecarsOnly|isHiddenRendererPtyViewGated|setHiddenDeliveryModelHandoff' src/main src/rendererRepository: stablyai/orca
Length of output: 42523
Keep the handoff open until queued delivery reaches the snapshot sequence.
getPtyOutputSequence is the arrival counter, not state.outputSequence; line 205 does not change the value used by seedSettled. However, onPtyData advances that counter before it publishes renderer data and queues the model write. If the snapshot covers a chunk that is still queued for delivery, seedSettled can close the handoff first. The delivery flush can then drop the chunk, while chunkDataAfterSeed returns an empty string and the rebuilt model does not reparse it. A query in that chunk can receive no reply.
Close the handoff only after the delivery/model-applied high-water mark reaches seedSeq. Do not use the PTY arrival counter as that completion signal.
…flip Main decides who answers a terminal query when it ingests the chunk: the pane's view while the view parses, main's model while the view is gated. Delivery decided again at send time, so a flip while the chunk was still queued broke that: - Queued while visible, then hidden before the flush: the gate dropped the bytes (or sent them to sidecars only), the view never parsed them, and main had not answered. The program waited for a reply that never came. - Queued while gated, then revealed before the flush: main had answered, and the now-visible view parsed the bytes and answered again. Each pending entry now carries the gate state it was ingested under, and an entry never mixes states. Bytes the view was to answer but will skip have their queries handed to the view the way a pending-cap drop already does. Bytes ingested gated go to sidecars only even after a reveal, and the view restores from main. Co-Authored-By: Claude Opus 5.5 <[email protected]>
rendererPtyViewDelivery now owns how main delivers a PTY's bytes to the
renderer ('parse', 'sidecarsOnly' or 'drop'). The drop and sidecar-only
predicates and the query responder read it, and every pending entry
records the mode it was ingested under instead of a gated bit. Main's
model owns the replies of any mode other than 'parse', so a later mode
such as parse-once's native-view skip slots into the same function and
the same stamp without another ownership rule.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The e2e holds the renderer's delivery credit while it fills main's window. Under heavy load the old 8 KB pacing could stretch the hold past main's 10 s ack-silence heal, which writes the window off and drains the queue the test needs. The filler now writes 16 KB per tick, still far below the queue size at which main pauses the PTY, and the probe writes its reply counts atomically. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Main fed every PTY byte into its own HeadlessEmulator, even for a visible pane whose renderer and daemon already parse the same bytes. For a visible local daemon terminal with no viewer, agent or gate drop, main now drops that emulator after 5 s without demand. A hide, a viewer, a screen read or a snapshot rebuilds it from the daemon's settled snapshot (protocol v36+), skipping live bytes the snapshot covers. The hidden-delivery gate stays open until the rebuilt model catches up, so main never owes a query reply for a byte it skipped. Restores of such terminals read the daemon at full depth. Phase 1 of #27023. Kill switch: terminalMainModelDormancy. Co-Authored-By: Claude Opus 5.5 <[email protected]>
An in-process consumer that reads main's emulator, or relies on main
answering a PTY's queries, can now hold the model live with
acquireTerminalOutputReader(ptyId, { kind: 'model' }) and release it when
done. A pin holds across a PTY respawn and releasing it restarts the
dormancy grace period. The reader kind leaves room for a later bytes-only
reader that does not need main's emulator.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Main hands a chunk to the view only when the view answers its queries; main answers none of them. The renderer still discarded such bytes without replies in several places: - a hidden view with a restore latched; - backlog bytes a restored snapshot already covers, fully or in part, both on arrival and in the restore queue's drain; - a seq gap that forces a fresh restore; - an unmappable hidden filter; - unparsed writes a snapshot apply or a backlog cap discards. A program that sent CPR or DA there waited forever. This mostly hits the dormancy handoff, where a hidden view answers until main's rebuilt model catches up, and the reveal restore after it. Every discard path now salvages the bytes' queries, the way the pending-cap and restore-queue overflow drops already do. As there, CPR reports the cursor where the view is, which keeps the program alive rather than being exact. The E2E test runs rounds of CPR, DA1 and DSR 5n across hiding and revealing a dormant pane, quiet and with output in flight. It checks for exactly one reply each, with the right cursor. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ddaa5c6 to
b814bec
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
tests/e2e/terminal-main-model-dormancy.spec.ts (2)
147-148: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftSynchronize the dormancy and hidden-query states.
The six-second waits do not establish that main dropped its model. The scripts also start before the tab changes, so a slow launch or output poll can move their queries outside the hidden interval. These tests can pass without exercising the model handoff. Observe dormancy directly, and coordinate script progress with the completed tab change instead of elapsed time. Based on learnings: fixed sleeps do not synchronize an asynchronous background action; use an explicit condition or synchronization hook.
Also applies to: 153-154, 196-198, 204-205
Source: Learnings
168-168: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftAdd a user-observable assertion for each terminal result.
Both final checks read
ManagedPane.serializeAddon. A correct buffer can therefore pass while the terminal pane fails to display its output. Keep the buffer checks for scrollback, but also verify the affected pane through a DOM-observable result. As per coding guidelines: “E2E Assertions Must Target the DOM, Not the Store”; the final assertion must prove what the user sees.Also applies to: 220-220
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
aae88828-d947-43f5-873b-7a366f7f7119
📥 Commits
Reviewing files that changed from the base of the PR and between ddaa5c6144b1f9a18f0a46a9adccae952b433d25 and b814bec.
📒 Files selected for processing (21)
src/main/ipc/pty-hidden-delivery-gate.tssrc/main/ipc/pty-ipc-hidden-delivery-flip-replies.test.tssrc/main/ipc/pty-pending-data-drain-contract.tssrc/main/ipc/pty/delivery/accept.tssrc/main/ipc/pty/delivery/exit.tssrc/main/ipc/pty/delivery/flush.tssrc/main/ipc/pty/delivery/payload.tssrc/main/ipc/pty/delivery/pending-delivery-stamp.tssrc/main/ipc/pty/delivery/pending.tssrc/main/ipc/pty/ipc/resize-visibility.tssrc/main/runtime/terminal-model-query-authority.tssrc/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-reconciliation.test.tssrc/renderer/src/components/terminal-pane/pty-connection/hidden-output-restore-drain.tssrc/renderer/src/components/terminal-pane/pty-connection/hidden-output-restore-snapshot.tssrc/renderer/src/components/terminal-pane/pty-connection/live-data-callback.tssrc/renderer/src/components/terminal-pane/pty-connection/write-pty-output-to-xterm.tssrc/renderer/src/lib/pane-manager/pane-terminal-output-queue-backlog.tssrc/renderer/src/lib/pane-manager/pane-terminal-output-queue-registry.tssrc/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-discarded-queries.test.tstests/e2e/terminal-main-model-dormancy.spec.tstests/e2e/terminal-query-reply-visibility-flip.spec.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.
|
Closing as not planned under our performance bar. Destroying main terminal models saves parsing CPU but introduces snapshot/replay waits, a shallower rebuilt history, and failure paths that can substitute that partial model for fuller history. This is a terminal lifecycle/ownership redesign with explicit behavior costs, not a low-risk free optimization. Separate terminal correctness issues remain valid and should be fixed independently. |
ELI5
When a plain terminal is on screen, three programs used to read every byte it prints: the terminal daemon, the visible pane, and Orca's main process. Main's copy only matters in a few situations. Now main stops reading a visible terminal it has no use for, and rebuilds its copy from the daemon when it needs it again.
What Changed
Before: main fed every byte of every terminal into its own terminal emulator. That included a visible pane, where the renderer and the daemon already parse the same bytes.
After: main can stop parsing a local terminal. Five seconds after its last demand, main drops its emulator, if the terminal meets all of these:
Main still scans each chunk for titles, working directory, agent status, the output tail and alternate-screen state. Users see no difference.
The mechanism:
Rebuild on demand. Main rebuilds its emulator from the daemon's snapshot whenever something needs it:
The rebuild holds up to 1000 rows. Live chunks the snapshot already covers are skipped, or split at the snapshot's sequence number.
Hidden-pane handoff. While the rebuilt emulator catches up, the hidden-delivery gate keeps sending the hidden pane's bytes to its renderer. The renderer answers their terminal queries, as it did before the gate existed.
Settled snapshots. A daemon's snapshot is settled from protocol v36: it waits for its emulator to finish parsing. Earlier snapshots can claim bytes their image does not show yet. A new provider capability,
canProvideSettledBufferSnapshot, gates the feature on v36 or later.Restores. Once main has dropped a terminal's emulator, restoring a hidden pane uses the daemon's full-depth snapshot. This is the same path keep-tail thinning already uses. If the daemon snapshot fails, the restore falls back to main's emulator.
Kill switch. The hidden setting
terminalMainModelDormancydefaults to on.These terminals keep today's always-on main emulator: SSH and relay terminals, the local provider without a daemon, degraded routes, daemons older than v36, agent panes, parked panes and hidden panes.
Why
Main's emulator runs synchronously on the main thread. It competes with IPC, keystroke forwarding and every other terminal (see #27023).
I measured with headless E2E on a minified build. Each run
cats 16 MiB into a pane and records main'sprocess.cpuUsage()until main goes quiet. Runs alternated between a cleanupstream/mainbuild (e273ec3) and this branch:With the kill switch off, this branch measured 70.8 ms/MB (66.9–79.2, n=10) in the same batch, in line with upstream. CPU profiles agree. With the kill switch off, main's emulator takes 178 ms per 16 MiB (
tryWriteSync); with it on, the emulator does not appear. The dormant alternate-screen scan costs about 29 ms per 16 MiB (about 1.8 ms/MB). The host was heavily loaded, so single runs vary widely; compare the interleaved medians.Alternatives considered:
Stacked on #27033 and #27129
This branch sits on #27129 (each pending chunk keeps the reply owner it was ingested under), which sits on #27033 (hidden sidecar-only delivery). #27129 settles chunks still queued when the handoff flips the gate: they go to whichever side owned them at ingestion, so ingest-time and send-time decisions can't disagree. All three branches change the hidden-delivery gate:
isHiddenRendererPtyViewGated, not only the drop. While it lasts, a hidden pane's bytes go fully to its view, sidecar-only PTYs included. Main stays silent for those bytes, so exactly one side answers.The diff here includes the #27033 and #27129 commits until they land.
In-process model readers
acquireTerminalOutputReader(ptyId, { kind: 'model' })returns a release. An in-process consumer that reads main's emulator, or relies on main answering the PTY's queries, uses it to keep that emulator live. A downstream native terminal view is one such consumer. The pin holds across a respawn of the same id. Releasing it restarts the grace period. Thekindfield leaves room for a later bytes-only reader.Linked Issue
Part of #27023 (phase 1 of 3; phases 2 and 3 stay open there)
Visual Proof
N/A: no UI or behavior change. Output, scrollback and terminal query replies stay the same, and the new E2E test checks all three.
Testing
Unit tests:
Runtime tests (
main-terminal-model-dormancy.spec.ts), using a fake daemon emulator:E2E, headless (
terminal-main-model-dormancy.spec.ts):Handoff E2E, headless (same file), quiet and with output in flight:
Before the renderer fix, 1 run in 4 lost a whole round (59 of each). Instrumented runs traced the losses to queued hidden writes discarded at the reveal's snapshot apply and to restore-queue chunks the snapshot covered. After the fix: 8 of 8 runs exact, and 12 of 12 with the rest of the file. After the rebase onto fix(terminal): keep each PTY query's reply owner across a visibility flip #27129's latest head, the file passed again with perf(terminal): let the daemon answer hidden local terminals' queries #27123 on top (12 of 12,
--repeat-each=2).Renderer unit tests: queries are answered for a hidden chunk dropped behind a latched restore, for backlog bytes a restored snapshot covers (fully or in part), and for covered chunks in the restore queue. The scheduler hands discarded unparsed bytes to the caller.
Regression E2E, headless, on this PR with perf(terminal): let the daemon answer hidden local terminals' queries #27123 on top: hidden-pane TUI restore, inline TUI reveal convergence, hidden view parking, sidecar pacing, OSC color queries, query replies across a visibility flip, duplicate-PTY reveal, hidden child-TUI kill-mode reset, Codex hidden startup, hidden-pane fit for mobile subscribers, remote viewers on a parked pane, paired remote parked-pane reveal, first mount of a hidden automation terminal. 26 of 26 pass.
SSH through the relay (Docker-backed E2E,
ORCA_E2E_SSH_DOCKER=1): cold activation restore, reconnect pane restore, input write queue. All 5 tests pass.Live mixed-version check: the branch client talked to the daemon shipped in Orca 1.4.223, which negotiates protocol v41, and to this branch's daemon at v44. I took snapshots while 60,000 coloured lines streamed, then replayed the stream up to each snapshot's own sequence number. The screens matched in 34/34 snapshots on v41 and 40/40 on v44.
Unit suites for
src/main/runtime,src/main/ipc,src/main/daemon,src/main/providersand the renderer's terminal pane and pane manager, on the full stack: 26,784 pass. The 18 failures fail the same way on a cleanupstream/mainin this environment: 16 spawn a real zsh (repro-13767,shell-ready) and 2 are inrun-terminal-shell-alone.node-pty.test.ts.pnpm tcand the changed-code quality gate (ORCA_CODE_QUALITY_BASE=upstream/main pnpm run check:code-quality:changed) pass. The fullpnpm test,pnpm lintandpnpm buildwere left to CI.I manually tested these changes locally (not done: only the scripted checks, E2E runs and tests listed above ran)
Automated tests added/updated, or explained why not below
AI Disclosure
Implemented with Claude Opus 5.5 via Claude Code: design, code, tests and measurements. A human (outof-place) directed the work.
Review
Suggested reading order:
main-terminal-model-dormancy.ts, the state machine.orca-runtime-main-terminal-model-dormancy.ts: when the model may go dormant, and how it is rebuilt.pty-hidden-delivery-gate.ts.trackHeadlessTerminalData.Agent skill upstream boundary
Trade-offs
terminalMainModelDormancy: falsekeeps every model live, as today;--expose-gcas heap plus array buffers. A rebuilt model holds the 1,000-row seed, 0.4–1.0 MiB. Each wake allocates the snapshot string once, 70–108 K characters.Notes
There are no wire, schema or settings UI changes. Cross-platform behavior is unchanged: the feature is platform-neutral. SSH and relay terminals keep main's emulator, because their providers offer no settled snapshot.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)🤖 Generated with Claude Code