Skip to content

perf(terminal): let main skip parsing visible local daemon terminals - #27086

Closed
outof-place wants to merge 8 commits into
stablyai:mainfrom
outof-place:perf/lazy-main-terminal-model
Closed

outof-place wants to merge 8 commits into
stablyai:mainfrom
outof-place:perf/lazy-main-terminal-model

Conversation

@outof-place

@outof-place outof-place commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • it runs on a local terminal daemon;
  • it is shown in a mounted pane, and the hidden-delivery gate does not cover it;
  • no remote, mobile or preview viewer is attached;
  • no agent is running in it;
  • its daemon serves settled snapshots.

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 pane is hidden;
    • a viewer subscribes;
    • a screen rule reads the screen;
    • a snapshot is requested;
    • the terminal stops meeting the conditions above.

    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.

    • The gate starts dropping bytes, and main starts answering queries, at the first chunk that begins at or after the snapshot's sequence number.
    • Main never owes a reply for a byte its emulator skipped.
    • The handoff ends after 2 s at most.
    • A hidden view can still drop a chunk it was handed: a restore is latched, a restored snapshot already covers the chunk, or a snapshot apply discards unparsed writes. It then still answers the chunk's queries, the way the existing pending-cap and overflow drops do. As there, a CPR answered this way reports the view's current cursor: it keeps the program alive, but it isn't exact.
  • 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 terminalMainModelDormancy defaults 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's process.cpuUsage() until main goes quiet. Runs alternated between a clean upstream/main build (e273ec3) and this branch:

Pane upstream/main This PR Change
Visible, agent-TUI frames (n=16 each) 78.8 ms/MB (p25–p75 63.5–88.1) 59.2 ms/MB (50.2–67.7) −19.6 ms/MB (−25%)
Hidden, agent-TUI frames (n=12 each) 54.1 ms/MB (53.1–70.0) 59.6 ms/MB (55.4–69.6) no measurable change; main keeps its emulator

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:

  • Seed from the renderer plus a buffer of raw chunks. [Feature]: Parse local daemon terminal output in main only when main needs the model #27023 first proposed this. The renderer's sequence number only advances on foreground writes. A pane that has just been hidden can already hold background writes past that number, so the renderer cannot give an exact boundary. The daemon's settled snapshot is exact at its own sequence number and needs no buffer.
  • Seed from the daemon, but drop the hidden pane's bytes right away. Bytes in flight between the snapshot and main would then be dropped for the renderer and skipped by main. Nobody would answer their queries. Keeping the gate open until main catches up closes that hole.
  • Let the daemon answer hidden queries. That is phase 2 of [Feature]: Parse local daemon terminal output in main only when main needs the model #27023 and needs a capability-negotiated wire change. This PR changes nothing on the wire.

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:

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. The kind field 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:

    • the dormancy state machine: grace period, wake, handoff, catch-up deadline, failed seed, generation reset;
    • splitting a chunk at the snapshot boundary;
    • gate suppression during the handoff;
    • the hidden-mark and handoff listeners;
    • restore routing over IPC, with its fallback;
    • the settled-snapshot capability for each protocol version, in the adapter, the router and the degraded provider.
  • Runtime tests (main-terminal-model-dormancy.spec.ts), using a fake daemon emulator:

    • the model is rebuilt exactly, with no duplicated bytes, for in-flight and straddling chunks;
    • the gate stays open until main catches up, and main gives the right CPR reply afterwards;
    • alternate-screen state is tracked while dormant;
    • the model is rebuilt when a viewer subscribes;
    • main keeps parsing for agents, panes without a renderer, and daemons without settled snapshots;
    • after a failed rebuild, main falls back to its existing partial-model path.
  • E2E, headless (terminal-main-model-dormancy.spec.ts):

    • main goes dormant during a 3000-line visible flood;
    • the pane is then hidden, prints 400 lines and sends a CPR query;
    • the reply reports the bottom row;
    • on reveal, all 400 lines are present, and so is line 0 of the earlier flood.
  • Handoff E2E, headless (same file), quiet and with output in flight:

    • the script sends 60 rounds of CPR, DA1 and DSR 5n, one every 40 ms;
    • the dormant pane is hidden mid-run and revealed 1 s later;
    • every round must get exactly one reply of each kind, with the right cursor.

    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/providers and the renderer's terminal pane and pane manager, on the full stack: 26,784 pass. The 18 failures fail the same way on a clean upstream/main in this environment: 16 spawn a real zsh (repro-13767, shell-ready) and 2 are in run-terminal-shell-alone.node-pty.test.ts.

  • pnpm tc and the changed-code quality gate (ORCA_CODE_QUALITY_BASE=upstream/main pnpm run check:code-quality:changed) pass. The full pnpm test, pnpm lint and pnpm build were 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:

  1. main-terminal-model-dormancy.ts, the state machine.
  2. orca-runtime-main-terminal-model-dormancy.ts: when the model may go dormant, and how it is rebuilt.
  3. The gate handoff in pty-hidden-delivery-gate.ts.
  4. The seed-coverage slicing in trackHeadlessTerminalData.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Trade-offs

  • Merge risk. Main stops parsing some terminals, so a mistake would show up as a wrong or missing reply to a terminal query, a reader seeing no screen, or a reveal that loses bytes. Mitigations:
    • kill switch: the hidden setting terminalMainModelDormancy: false keeps every model live, as today;
    • narrow scope: only local daemon terminals with settled snapshots (protocol v36 or later), and never SSH, relay, agent, parked or hidden panes;
    • tests: the dormancy state machine and handoff in unit and runtime tests, the 60-round CPR/DA1/DSR handoff E2E quiet and under output, the reveal E2E, the mixed-version snapshot check against Orca 1.4.223's daemon, and the regression and SSH E2E sets above.
  • CPU. Main −25% on a visible flood (78.8 → 59.2 ms/MB, n=16), no change for hidden panes. Each wake costs one daemon snapshot and one seed write: about 3 ms and 1.5 ms of CPU for a 1,000-row seed of 70–108 K characters (micro-benchmark, 120 columns), plus the local socket round trip. Minimizing the window wakes every dormant visible pane at once.
  • Memory. A dormant model frees main's emulator: 8.4–8.9 MiB for a full one (120 columns, 5,000 rows of scrollback after a 16 MiB stream), measured with --expose-gc as 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.
  • Latency. A read that finds the model dormant waits for the rebuild: the snapshot request and the seed write. The seed gives up after 2 s, and main then falls back to its existing partial-model path. While a hidden pane's rebuilt model catches up, its renderer keeps answering its queries for at most 2 s.
  • Depth. A rebuilt model starts from 1,000 rows of daemon history, so reads served by main's emulator see at most that. Mobile and preview already cap at 1,000, and full-depth restores come from the daemon.
  • Disk. None.
  • Maintenance. +653/−28 lines in 31 source files and +944 lines of tests. New concepts: the dormancy state machine, the model handoff in the hidden-delivery gate, the settled-snapshot provider capability (no wire change: it reads the negotiated protocol version), the in-process model reader API, and renderer query salvage at every path that drops a view-owned chunk.
  • Verdict: substantial: a quarter of main's CPU under visible output, and several MiB of main memory per idle visible terminal. The costs are a rebuild of a few milliseconds on the next read, a shallower rebuilt model, and a state machine to maintain.

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

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

🤖 Generated with Claude Code

…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]>
@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →Review in Change Stack →

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The change adds protocol v36 settled-buffer snapshot capability checks and a configurable main terminal model dormancy lifecycle. Eligible models can be dropped after five seconds of idleness and rebuilt from provider snapshots when demand returns. Seed coverage filters live bytes already included in a snapshot. Hidden PTY bytes can be delivered to sidecars without rendering, while model handoff changes the delivery gate. The change adds unit, runtime, IPC, renderer, and end-to-end tests.





Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to b814b

The reported handoff issue may leave in-flight terminal queries unanswered. Resolve that concern and strengthen the dormancy tests before merging.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 36.92% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 65 functions across 64 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly and concisely identifies the primary performance change: allowing the main process to skip parsing eligible visible local daemon terminals.
Description check Passed The description is detailed and covers the required sections, including the user impact, implementation, rationale, linked issue, visual proof, testing, risks, compatibility, and checklist. It also do…

  • Fix all pre-merge checks with AI
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@outof-place
outof-place force-pushed the perf/lazy-main-terminal-model branch from e41169b to ddaa5c6 Compare October 10, 2026 01:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ts
  • src/main/ipc/pty-hidden-delivery-gate.ts
  • src/main/ipc/pty-ipc-hidden-delivery-gate.test.ts
  • src/main/ipc/pty/delivery/payload.ts
  • src/main/ipc/pty/runtime/controller.ts
  • src/main/ipc/pty/session.ts
  • src/main/runtime/main-terminal-model-dormancy.test.ts
  • src/main/runtime/main-terminal-model-dormancy.ts
  • src/main/runtime/orca-runtime-main-terminal-model-dormancy.ts
  • src/main/runtime/orca-runtime-tests/main-terminal-model-dormancy.spec.ts
  • src/main/runtime/runtime-pty-controller-contract.ts
  • src/main/runtime/terminal-model-query-authority.test.ts
  • src/main/runtime/terminal-model-query-authority.ts
  • src/main/runtime/terminal-query-responder.test.ts
  • src/preload/api/pty-api.ts
  • src/preload/api/pty-bridge-stream-and-serialization.ts
  • src/renderer/src/components/terminal-pane/pty-dispatcher-sidecar-only.test.ts
  • src/renderer/src/components/terminal-pane/pty-dispatcher.ts
  • src/renderer/src/components/terminal-pane/pty-sidecar-only-delivery.ts
  • tests/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.

Comment on lines +204 to +206
state.seedCoverageSeq = snapshot.seq
state.outputSequence = Math.max(state.outputSequence, snapshot.seq)
return owns() ? snapshot.seq : null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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/runtime

Repository: 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/runtime

Repository: 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 || true

Repository: 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/renderer

Repository: 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/renderer

Repository: 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.

outof-place and others added 3 commits October 10, 2026 05:57
…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]>
outof-place and others added 4 commits October 10, 2026 07:32
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]>
@outof-place
outof-place force-pushed the perf/lazy-main-terminal-model branch from ddaa5c6 to b814bec Compare October 10, 2026 06:14

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
tests/e2e/terminal-main-model-dormancy.spec.ts (2)

147-148: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Synchronize 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 lift

Add 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.ts
  • src/main/ipc/pty-ipc-hidden-delivery-flip-replies.test.ts
  • src/main/ipc/pty-pending-data-drain-contract.ts
  • src/main/ipc/pty/delivery/accept.ts
  • src/main/ipc/pty/delivery/exit.ts
  • src/main/ipc/pty/delivery/flush.ts
  • src/main/ipc/pty/delivery/payload.ts
  • src/main/ipc/pty/delivery/pending-delivery-stamp.ts
  • src/main/ipc/pty/delivery/pending.ts
  • src/main/ipc/pty/ipc/resize-visibility.ts
  • src/main/runtime/terminal-model-query-authority.ts
  • src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-reconciliation.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/hidden-output-restore-drain.ts
  • src/renderer/src/components/terminal-pane/pty-connection/hidden-output-restore-snapshot.ts
  • src/renderer/src/components/terminal-pane/pty-connection/live-data-callback.ts
  • src/renderer/src/components/terminal-pane/pty-connection/write-pty-output-to-xterm.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-output-queue-backlog.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-output-queue-registry.ts
  • src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-discarded-queries.test.ts
  • tests/e2e/terminal-main-model-dormancy.spec.ts
  • tests/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.

@nwparker

Copy link
Copy Markdown
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants