Skip to content

perf(terminal): let the daemon answer hidden local terminals' queries - #27123

Closed
outof-place wants to merge 11 commits into
stablyai:mainfrom
outof-place:perf/daemon-query-responder
Closed

outof-place wants to merge 11 commits into
stablyai:mainfrom
outof-place:perf/daemon-query-responder

Conversation

@outof-place

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

Copy link
Copy Markdown
Contributor

ELI5

Terminal programs sometimes ask the terminal a question, for example "where is my cursor?", and wait for the answer. When a pane is hidden, nobody on screen can answer, so Orca's main process keeps its own copy of the terminal just to answer those questions. The terminal daemon already keeps an identical copy. With this PR, main asks the daemon to answer for hidden panes, and main can then drop its own copy, as #27086 lets it do for visible panes.

What Changed

Before: #27033 made main the only party that answers a view-gated (hidden) pane's terminal queries. To do that, main had to keep parsing every hidden pane's bytes, including panes that print a lot (builds, logs, dev servers).

After: for a hidden local daemon pane, the daemon's own emulator answers the queries, and main's emulator for that pane can go dormant. Answers do not change: the daemon uses the same emulator class and the same responder modules as main:

  • xterm core: DA1, DA2, DSR 5n, CPR 6n/?6n, DECRQM, DECRQSS, XTVERSION, kitty CSI ? u;
  • view attributes: OSC 4/10/11/12 and ?996n, answered from the attributes main now pushes to the daemon;
  • per-agent reply policy and the native-Windows ConPTY DA1 override.

Replies go through Session.write, so the existing startup-ingress dedupe and the shell-ready queue apply to them unchanged.

The mechanism:

  • Capability. Daemon protocol v45 adds two control notifications, setTerminalViewAttributes and setSessionQueryResponder, and one stream event, sessionQueryResponderMarker. Main sends the notifications only to a v45 daemon. Sessions on an older preserved daemon keep main as the responder.

  • Exactly one responder per byte. resolveTerminalQueryResponder returns view, main or daemon for each live chunk, at ingestion. It replaces the boolean check from perf(terminal): send hidden sidecar bytes past the view so throttled renderers can't pace agents #27033.

    • The daemon queues its marker on the client's stream, in order with the data, at the byte where it started or stopped answering.
    • Main moves the gate only when the marker arrives. Every byte is therefore answered by exactly one party.
  • Hiding a pane. Main sends the request. Until the daemon's true marker arrives, main's emulator keeps answering. If main's emulator is already dormant, the view stays ungated and answers instead. After the marker, the daemon answers, and main's emulator may go dormant under the rules from perf(terminal): let main skip parsing visible local daemon terminals #27086.

  • Revealing a pane. Main sends the take-back. The view stays gated until the daemon's false marker arrives, because the daemon still answers until that point. The reveal restore is deferred to that marker, so the restore snapshot covers every byte the view skipped.

  • Taking replies back while hidden. Main takes the queries back and wakes its emulator when any of these happens:

    • an agent starts;
    • a remote view attaches;
    • an in-process model reader registers;
    • the kill switch flips.

    If main's emulator is dormant, main wakes it first and sends the take-back only once it has caught up, so the daemon answers until then and main answers from an exact model right after the false marker. A remote viewer takes over at once, since main won't answer for it.

  • No confirmation. If the true marker does not arrive within 2 s, main takes the role back and keeps answering for that PTY generation. A daemon reattach drops delegations; the adapter reports that as a false marker, and main asks again.

  • Kill switch. The hidden setting terminalDaemonQueryAuthority defaults to on.

These PTYs keep main as the responder for hidden panes, as today:

  • SSH and relay PTYs;
  • the in-process local provider;
  • daemons older than v45, and degraded daemon routes;
  • agent panes;
  • panes without a mounted renderer.

Why

Hidden panes include background builds, logs and dev servers, which can print a lot, and #27033 pinned main's emulator to all of them. Main's emulator runs on the main thread, alongside IPC and keystroke forwarding (#27023). The daemon parses every byte anyway, so letting it answer costs it almost nothing extra.

Measured with a headless E2E on a minified build. Each run hides a pane, cats a 16 MiB agent-TUI fixture into it, and records main's process.cpuUsage() until main goes quiet. I interleaved runs with the kill switch on and off on the same build: n=10 each, on a loaded host (load average 55–65 on 16 cores when checked in the same session; not recorded per run).

Hidden pane terminalDaemonQueryAuthority off on (this PR)
Main CPU, median (p25–p75) 47.2 ms/MB (44.8–51.9) 33.8 ms/MB (33.0–34.8)
Daemon answering at the end of the run 0 PTYs 1 PTY

That is −13.4 ms/MB (−28%). The daemon's keep-tail thinning applies to both arms, because a hidden session is backgrounded.

Alternatives considered:

  • Main answers, and stays dormant until a query arrives. Main cannot know a query is coming before it has parsed the bytes. A dormant model would answer late or from the wrong cursor position.
  • The daemon answers without markers. In-flight bytes would be answered twice, or not at all, around every hide and reveal. The in-order marker is what makes the hand-over exact.
  • Delegating every PTY, visible ones included. A visible pane's renderer already answers its queries. Delegating it would buy nothing.

Stacked on #27086

This branch sits on #27086 (main model dormancy), which sits on #27129 and #27033. The diff here includes their commits until they land.

Linked Issue

Part of #27023 (phase 2). The wire design was posted there first: #27023 (comment)

Visual Proof

N/A: no UI or behavior change. Query replies, output and reveal restores stay the same, and the new E2E test checks all three.

Testing

  • Daemon tests:

    • Session answers only while delegated;
    • an attach drops a delegation;
    • the reply policy and the pushed palette apply;
    • the daemon-server test checks that markers land between the data in byte order;
    • the real adapter-to-daemon test covers delegation, the reattach take-back, and the absence of any request to an older daemon.
  • Main-side tests:

    • the delivery gate's daemon handoff, the confirmed state, and the deferred reveal restore;
    • the delegation state machine: confirm timeout, late markers, dropped delegations, generation reset;
    • the one responder function;
    • view-attribute pushes to the daemon;
    • an IPC test that a revealed pane stays gated until the false marker and then gets exactly one restore.
  • Runtime tests:

    • a hidden pane is delegated; main answers until the marker, stays silent after it, and its emulator goes dormant;
    • a pane whose emulator is already dormant keeps its view answering until the marker;
    • main answers again after a take-back;
    • a dormant pane's take-back waits until main's rebuilt model has caught up;
    • a reveal does not wake main;
    • readers and remote viewers take the role back;
    • an older daemon keeps main as the responder.
  • E2E, headless:

    • a hidden pane whose emulator went dormant prints 400 lines and sends a CPR query;
    • exactly one reply arrives, and it reports the bottom row;
    • the reveal shows all 400 lines;
    • the delivery snapshot shows the daemon answering while the pane is hidden, and not after the reveal.
  • Handoff E2E (from perf(terminal): let main skip parsing visible local daemon terminals #27086), with the daemon answering and with main answering (kill switch off), quiet and with output in flight. It runs 60 rounds of CPR, DA1 and DSR 5n across hiding and revealing a dormant pane, and checks for exactly one reply of each kind with the right cursor. All runs exact: 12 of 12 for the dormancy file with --repeat-each=2 before the rebase onto fix(terminal): keep each PTY query's reply owner across a visibility flip #27129's latest head, and 12 of 12 after it.

  • Regression E2E, headless: 13 spec files, 26 tests:

    • hidden sidecar pacing, hidden-pane TUI restore and inline TUI reveal convergence (including tab and worktree flapping);
    • hidden-pane fit for mobile subscribers, a remote viewer on a parked pane, and parked-pane reveal for a paired client;
    • hidden view parking (25 park and reveal cycles), hidden child TUI mode reset and duplicate renderer reveal;
    • OSC colour queries, Codex hidden startup and first mount of a hidden automation terminal.

    Three full runs passed 26 of 26. A run between the first two, under the same parallel load, failed two tests: one park and reveal cycle missed its frame, and the flapping fixture stopped streaming. Both passed when run alone, and in every later run.

  • After the rebase onto fix(terminal): keep each PTY query's reply owner across a visibility flip #27129's latest head: the dormancy, visibility-flip, sidecar-pacing, OSC colour query, hidden view parking and hidden-pane TUI restore files passed 36 of 36 with --repeat-each=2.

  • check:daemon-protocol-crossing: upgrading from v1.4.223 (protocol 41) adopts live terminals.

  • 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.

  • Unit suites for src/main/daemon, src/main/ipc, src/main/runtime, src/main/providers and the renderer's terminal pane and pane manager: 26,784 pass. The 18 failures fail the same way on the base commit in this environment: 16 spawn a real zsh (repro-13767, shell-ready) and 2 are in run-terminal-shell-alone.node-pty.test.ts.

  • I manually tested these changes locally (not done: only the 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 and tests. A human (outof-place) directed the work.

Review

Suggested reading order:

  1. resolveTerminalQueryResponder in terminal-model-query-authority.ts, the one responder function.
  2. The daemon handoff and the confirmed state in pty-hidden-delivery-gate.ts.
  3. daemon-query-responder-delegation.ts, the main-side state machine.
  4. The daemon side: Session.setQueryResponder, SessionOutputPlane.setQueryResponder, and the marker in daemon-session-background-routing.ts.

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. This changes the daemon protocol and who answers a hidden pane's terminal queries. A mistake would show up as a query answered twice or not at all, or a reveal restored at the wrong byte. Mitigations:
    • capability negotiation: the new requests go only to a v45 daemon, and older daemons and mains keep today's behavior (check:daemon-protocol-crossing covers an upgrade from protocol 41);
    • kill switch: the hidden setting terminalDaemonQueryAuthority: false keeps main as the responder;
    • scope: local daemon panes only, never degraded routes, SSH, relay, agent panes, panes with a remote viewer, or panes an in-process reader holds;
    • tests: daemon, delegation, gate and runtime tests, a real adapter-to-daemon test, and the hidden-pane and handoff E2Es above, with the daemon answering and with the kill switch off.
  • CPU. Main −28% on a hidden flood (47.2 → 33.8 ms/MB, n=10). Daemon CPU is flat: in the same kind of A/B in perf(terminal): let main's model rest for agents that read no screen #27185, which differs on the daemon side only in which side answers, daemon CPU was 36.9 vs 35.6 ms/MB (n=10). The daemon parses every byte either way, and a reply is a few bytes per query.
  • Memory. Main's model may now rest for a hidden pane too, freeing 8.4–8.9 MiB per full model (120 columns, 5,000 rows of scrollback), measured in a micro-benchmark with --expose-gc as heap plus array buffers. The daemon keeps one responder flag per session and one copy of the pushed view attributes (palette, cursor style, color scheme) for all sessions, not per session. In perf(terminal): let main's model rest for agents that read no screen #27185's A/B, the daemon's RSS after a hidden flood was lower with the daemon answering (130 vs 190 MiB); a likely reason is that it buffers less while main keeps up, and RSS is a high-water mark.
  • Latency. Revealing a delegated pane waits for the daemon's in-order take-back marker before the reveal restore runs: one daemon round trip on the local socket. Taking the role back from a hidden pane waits until main's woken model has caught up, and the daemon answers until then.
  • Disk. None.
  • Maintenance. +784/−77 lines in 39 source files and +1,033 lines of tests. The protocol bump to v45 is a lasting cost: two new requests (setSessionQueryResponder, setTerminalViewAttributes) and a new stream event (sessionQueryResponderMarker) that every later daemon and main must keep speaking, with mixed-version behavior to test. Main gains a second responder path and a delegation state machine (confirm timeout, give-up, generation reset). The in-flight double-answer window for remote viewers is a known follow-up (Notes).
  • Verdict: substantial: about a quarter of main's CPU for hidden output, which is where most terminal bytes are in a busy workspace, plus main's model memory for hidden panes. The cost is a protocol bump that must stay compatible, and a second responder path.

Notes

  • Follow-up: remote viewers. When a remote view attaches to a delegated pane, main takes the role back right away. Bytes the daemon has already emitted, but main has not yet received, could be answered by both the daemon and the new remote view. The window covers only those in-flight bytes on the local daemon socket. Mobile replies arrive after a network round trip, so filtering them until the marker would not close it; the design comment on [Feature]: Parse local daemon terminal output in main only when main needs the model #27023 is corrected accordingly. Closing it needs a seq-exact hand-over, where the daemon answers from a given byte, and I'm tracking that as a follow-up.
  • Wire compatibility. Old mains never send the new notifications, so a v45 daemon never answers for them. New mains send them only to a v45 daemon. The marker is a new stream event, so an old main never receives one.
  • Cross-platform. The daemon installs the ConPTY DA1 override when main marks a native-Windows PTY. SSH, relay and folder workspaces are unaffected.

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 →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f9c4ba38-ddac-4758-bb98-8734ccf39062

📥 Commits

Reviewing files that changed from the base of the PR and between bff7c7f and 92a1f34.


📒 Files selected for processing (2)
  • src/shared/local-build-compatibility-contract.json
  • src/shared/local-build-compatibility-contract.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.



📝 Walkthrough

Walkthrough

The change adds daemon query-responder delegation and main terminal-model dormancy. It introduces protocol 45 responder markers and settled-snapshot capability checks. Runtime code can drop idle models and rebuild them from provider snapshots while reconciling live output. Hidden-view delivery now distinguishes renderer gating from sidecar delivery, and responder markers coordinate restoration. New settings, provider APIs, IPC payload fields, tests, and end-to-end coverage support these paths.


Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 92a1f

A reattached hidden terminal can miss query replies, and generation resets or repeated backlog drops can leave stale query behavior or lose replies. Resolve these bounded terminal issues before merging.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 35.05% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 97 functions across 72 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the main performance change: hidden local terminal queries are answered by the daemon.
Description check Passed The description is comprehensive and follows the required template. It explains the change, motivation, compatibility behavior, testing, trade-offs, linked issue, AI usage, and checklist status.
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.

Full details: Docstring Coverage

Explanation

Docstring coverage is 35.05% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 97 functions across 72 files. (1 skipped: 1 unsupported.)


  • 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.

@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: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 10af7c2e-943f-4850-a85d-a128762673d2
📥 Commits

Reviewing files that changed from the base of the PR and between 4ec973f and 7c9aa6264266e9db3f7403215883dd62cbc9ada5.

📒 Files selected for processing (77)
  • src/main/daemon/daemon-foreground-confirmation-protocol.test.ts
  • src/main/daemon/daemon-protocol-version.ts
  • src/main/daemon/daemon-pty-adapter-protocol-compatibility.test.ts
  • src/main/daemon/daemon-pty-adapter-query-responder.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-connection-lifecycle.ts
  • src/main/daemon/daemon-pty-owner-query-protocol.ts
  • src/main/daemon/daemon-pty-router-test-fixture.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/daemon-pty-runtime-state.ts
  • src/main/daemon/daemon-query-responder-routing.test.ts
  • src/main/daemon/daemon-request-router.ts
  • src/main/daemon/daemon-session-background-routing.ts
  • src/main/daemon/daemon-stream-events.ts
  • src/main/daemon/daemon-view-attributes.ts
  • src/main/daemon/degraded-daemon-pty-provider.test.ts
  • src/main/daemon/degraded-daemon-pty-provider.ts
  • src/main/daemon/headless-emulator.ts
  • src/main/daemon/session-output-pipeline.ts
  • src/main/daemon/session-output-plane.ts
  • src/main/daemon/session-query-responder.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-host-session-inspection-operations.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/types.ts
  • src/main/ipc/pty-buffer-snapshot-dispatch.test.ts
  • src/main/ipc/pty-hidden-delivery-gate.test.ts
  • src/main/ipc/pty-hidden-delivery-gate.ts
  • src/main/ipc/pty-ipc-daemon-query-responder.test.ts
  • src/main/ipc/pty-ipc-hidden-delivery-gate.test.ts
  • src/main/ipc/pty-ipc-provider-fixtures.ts
  • src/main/ipc/pty/delivery/debug.ts
  • src/main/ipc/pty/delivery/payload.ts
  • src/main/ipc/pty/delivery/wire-session.ts
  • src/main/ipc/pty/ipc/snapshot.ts
  • src/main/ipc/pty/ipc/terminal-view-attributes-ipc.test.ts
  • src/main/ipc/pty/ipc/terminal-view-attributes-ipc.ts
  • src/main/ipc/pty/provider/bind-listeners.ts
  • src/main/ipc/pty/provider/registry.ts
  • src/main/ipc/pty/runtime/controller.ts
  • src/main/ipc/pty/session.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/providers/pty-provider-events.ts
  • src/main/runtime/daemon-query-responder-delegation.test.ts
  • src/main/runtime/daemon-query-responder-delegation.ts
  • src/main/runtime/main-terminal-model-dormancy.test.ts
  • src/main/runtime/main-terminal-model-dormancy.ts
  • src/main/runtime/orca-runtime-attach-remote-terminal-source-range-consumer.ts
  • src/main/runtime/orca-runtime-fit-override-listeners.ts
  • src/main/runtime/orca-runtime-main-terminal-model-dormancy.ts
  • src/main/runtime/orca-runtime-maybe-hydrate-headless-from-renderer.ts
  • src/main/runtime/orca-runtime-on-pty-data.ts
  • src/main/runtime/orca-runtime-on-pty-exit.ts
  • src/main/runtime/orca-runtime-serialize-headless-terminal-buffer.ts
  • src/main/runtime/orca-runtime-serialize-main-terminal-buffer.ts
  • src/main/runtime/orca-runtime-tests/main-terminal-model-dormancy.spec.ts
  • src/main/runtime/orca-runtime-verify-orchestration-compatibility-caller.ts
  • src/main/runtime/orca-runtime-visible-snapshot-preview.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/runtime-pty-controller-contract.ts
  • src/main/runtime/runtime-store-contract.ts
  • src/main/runtime/runtime-terminal-state-records.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-session-control.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
  • src/renderer/src/web/preload-api/web-terminal-api.ts
  • src/shared/default-global-settings.ts
  • src/shared/global-settings-types.ts
  • tests/e2e/terminal-hidden-sidecar-pacing.spec.ts
  • tests/e2e/terminal-main-model-dormancy.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Comment on lines 114 to +116
attachClient(client: Omit<AttachedClient, 'token'>): symbol {
// Why: a delegation outlives a quit main; the attaching one starts as responder and delegates again.
this.answersQueries = false

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
rg -nP -C4 'attachClient\(' src/main/daemon --glob '!**/*.test.ts'

Repository: stablyai/orca

Length of output: 3241


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- session-output-plane.ts ---'
nl -ba src/main/daemon/session-output-plane.ts | sed -n '1,240p'
printf '%s\n' '--- terminal-host-session-create.ts ---'
nl -ba src/main/daemon/terminal-host-session-create.ts | sed -n '1,230p'
printf '%s\n' '--- responder and attach references ---'
rg -n -F --glob '*.ts' --glob '!**/*.test.ts' -e 'sessionQueryResponderMarker' -e 'releaseQueryResponderSessions' -e 'setQueryResponder(' -e 'createOrAttach' src/main

Repository: stablyai/orca

Length of output: 28330


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- session attach/detach and responder methods ---'
nl -ba src/main/daemon/session.ts | sed -n '170,225p'
nl -ba src/main/daemon/daemon-pty-adapter.ts | sed -n '1,90p'
nl -ba src/main/daemon/daemon-pty-connection-lifecycle.ts | sed -n '1,135p'
printf '%s\n' '--- background routing marker path ---'
nl -ba src/main/daemon/daemon-session-background-routing.ts | sed -n '1,125p'
printf '%s\n' '--- all detachAllClients references ---'
rg -n -F --glob '*.ts' --glob '!**/*.test.ts' 'detachAllClients' src/main

Repository: stablyai/orca

Length of output: 17837


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- main-side responder calls and attach flow ---'
rg -n -F --glob '*.ts' --glob '!**/*.test.ts' -e 'setSessionQueryResponder(' -e 'queryResponderMarker' -e 'createOrAttach(' src/main
printf '%s\n' '--- changed hunk versus supplied merge base ---'
git diff --unified=12 9d94a20f84d10641f217b9539b0aefeff8d9b1ed 7c9aa6264266e9db3f7403215883dd62cbc9ada5 -- src/main/daemon/session-output-plane.ts src/main/daemon/terminal-host-session-create.ts src/main/daemon/session.ts

Repository: stablyai/orca

Length of output: 13938


Emit a false responder marker when an existing session is reattached.

createOrAttachTerminalSession detaches all clients and then calls attachClient for an existing session. attachClient sets answersQueries to false, but this path emits no sessionQueryResponderMarker. Main can still believe that the daemon answers queries, so neither side answers subsequent queries.

When an existing attach clears delegation, enqueue an ordered responder: false marker. Do not rely only on fresh-connection cleanup.

Comment on lines +92 to +98
forget(ptyId: string): void {
const entry = this.entries.get(ptyId)
if (entry) {
this.clearTimer(entry)
this.entries.delete(ptyId)
}
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Check whether exit/respawn paths clear daemonHandoffPtys elsewhere.
rg -nP -C3 'daemonHandoffPtys\.(delete|clear)|setHiddenDeliveryDaemonHandoff\(' src/main

Repository: stablyai/orca

Length of output: 5901


🏁 Script executed:

set -e
printf '%s\n' '--- daemon-query-responder-delegation.ts ---'
nl -ba src/main/runtime/daemon-query-responder-delegation.ts | sed -n '1,180p'
printf '%s\n' '--- runtime host binding ---'
nl -ba src/main/runtime/orca-runtime-main-terminal-model-dormancy.ts | sed -n '80,145p'
printf '%s\n' '--- hidden delivery gate cleanup and relevant predicates ---'
nl -ba src/main/ipc/pty-hidden-delivery-gate.ts | sed -n '1,175p'
nl -ba src/main/ipc/pty-hidden-delivery-gate.ts | sed -n '230,310p'
printf '%s\n' '--- delegation call sites ---'
rg -n -F --glob '*.ts' -- 'daemonQueryResponderDelegation.' src/main

Repository: stablyai/orca

Length of output: 23629


🏁 Script executed:

set -e
printf '%s\n' '--- PTY exit handler ---'
nl -ba src/main/runtime/orca-runtime-on-pty-exit.ts | sed -n '100,165p'
printf '%s\n' '--- clearHiddenRendererPtyDeliveryState callers ---'
rg -n -F --glob '*.ts' -- 'clearHiddenRendererPtyDeliveryState(' src/main
printf '%s\n' '--- lifecycle generation definitions and updates ---'
rg -n -F --glob '*.ts' -- 'getPtyLifecycleGeneration' src/main
rg -n -F --glob '*.ts' -- 'lifecycleGeneration' src/main/runtime src/main/ipc
printf '%s\n' '--- provider PTY teardown references ---'
rg -n -F --glob '*.ts' -- 'clearProviderPtyState' src/main

Repository: stablyai/orca

Length of output: 26888


🏁 Script executed:

set -e
printf '%s\n' '--- provider state cleanup ---'
nl -ba src/main/ipc/pty/provider/state-cleanup.ts | sed -n '1,80p'
printf '%s\n' '--- lifecycle-generation storage and mutations ---'
rg -n -C4 -F --glob '*.ts' -- 'ptyLifecycleGenerationById' src/main/runtime
printf '%s\n' '--- generation mutation operators ---'
rg -n -P -C3 --glob '*.ts' 'ptyLifecycleGenerationById[^\\n]*(\\+\\+|\\+=|set\\(|delete\\()' src/main/runtime
printf '%s\n' '--- PTY exit registration/callers ---'
rg -n -C4 --glob '*.ts' -e 'onPtyExit' -e 'register.*Pty.*Exit' src/main/runtime src/main/ipc/pty

Repository: stablyai/orca

Length of output: 14946


🏁 Script executed:

set -e
printf '%s\n' '--- provider state cleanup ---'
nl -ba src/main/ipc/pty/provider/state-cleanup.ts | sed -n '1,80p'
printf '%s\n' '--- lifecycle-generation storage and mutations ---'
rg -n -C4 -F --glob '*.ts' -- 'ptyLifecycleGenerationById' src/main/runtime
printf '%s\n' '--- generation mutation operators ---'
rg -n -P -C3 --glob '*.ts' 'ptyLifecycleGenerationById[^\n]*(\+\+|\+=|set\(|delete\()' src/main/runtime
printf '%s\n' '--- PTY exit registration/callers ---'
rg -n -C4 --glob '*.ts' -e 'onPtyExit' -e 'register.*Pty.*Exit' src/main/runtime src/main/ipc/pty

Repository: stablyai/orca

Length of output: 41969


🏁 Script executed:

set -e
printf '%s\n' '--- generation advancement callers ---'
rg -n -C6 -F --glob '*.ts' -- 'advancePtyLifecycleGeneration(' src/main
printf '%s\n' '--- PTY spawn hooks ---'
rg -n -C8 --glob '*.ts' -e 'onPtySpawned' -e 'registerPty\(' src/main/runtime/orca-runtime-on-pty-spawned.ts src/main/runtime src/main/ipc/pty | head -n 240
printf '%s\n' '--- cleanup tail and spawn registration ---'
nl -ba src/main/ipc/pty/provider/state-cleanup.ts | sed -n '80,145p'
rg -n -C6 -F --glob '*.ts' -- 'clearProviderPtyState(id)' src/main/ipc/pty/provider

Repository: stablyai/orca

Length of output: 32273


🏁 Script executed:

set -e
printf '%s\n' '--- provider sequence reset block ---'
nl -ba src/main/runtime/orca-runtime-record-agent-prompt-lifecycle-state.ts | sed -n '108,155p'
printf '%s\n' '--- delegation tests ---'
nl -ba src/main/runtime/daemon-query-responder-delegation.test.ts | sed -n '1,260p'

Repository: stablyai/orca

Length of output: 8394


🏁 Script executed:

set -e
rg -n -C8 -F --glob '*.ts' -- 'disposeHeadlessTerminal' src/main/runtime
rg -n -C4 -F --glob '*.ts' -- 'setHiddenDeliveryDaemonHandoff' src/main/runtime src/main/ipc

Repository: stablyai/orca

Length of output: 33526


Clear the handoff latch when forgetting a requested generation.

A provider sequence reset can invalidate the entry without running PTY teardown. currentEntry() then calls forget(), which currently removes the entry but leaves the hidden-delivery daemon handoff pending. The hidden view can therefore continue answering and parsing bytes for the new generation.

Suggested fix
--- "a/src/main/runtime/daemon-query-responder-delegation.ts"
+++ "b/src/main/runtime/daemon-query-responder-delegation.ts"
@@ -89,13 +89,16 @@
     }
   }
 
   forget(ptyId: string): void {
     const entry = this.entries.get(ptyId)
     if (entry) {
       this.clearTimer(entry)
+      if (entry.requested) {
+        this.host.setHandoffPending(ptyId, false)
+      }
       this.entries.delete(ptyId)
     }
   }
 
   private request(ptyId: string, entry: DelegationEntry): void {
     if (entry.gaveUp || !this.sendTracked(ptyId, entry, true)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
forget(ptyId: string): void {
const entry = this.entries.get(ptyId)
if (entry) {
this.clearTimer(entry)
this.entries.delete(ptyId)
}
}
forget(ptyId: string): void {
const entry = this.entries.get(ptyId)
if (entry) {
this.clearTimer(entry)
if (entry.requested) {
this.host.setHandoffPending(ptyId, false)
}
this.entries.delete(ptyId)
}
}

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 6 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]>
which keeps that model parsing every hidden pane. A v45 daemon now answers
them instead: main delegates with setSessionQueryResponder, the daemon
flags its emulator writes and queues an in-order sessionQueryResponderMarker
on the client stream, and main flips the delivery gate only at that marker.

resolveTerminalQueryResponder picks exactly one of view, main or daemon per
live chunk. Until the daemon confirms, main's live model keeps answering (the
view does only when main's model is already dormant); after a take-back the
view stays gated, and its reveal restore is deferred, until the daemon's
false marker. Main takes the role back (and wakes its model) for agents,
remote viewers, model readers, the kill switch, unconfirmed requests and
daemon reattaches. Main pushes the renderer's view attributes so OSC 4/12,
?996n and cursor replies match. Old daemons, degraded routes, SSH, relay
and agent panes keep main as the responder. Kill switch:
terminalDaemonQueryAuthority.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… caught up

When a hidden, delegated PTY stops qualifying (an agent starts, a reader
registers, the kill switch flips), main takes its queries back. If main's
model was dormant, the take-back used to land before the rebuilt model had
caught up. The hidden view then had to answer in between, and a view with a
latched restore does not parse.

Main now wakes its model first and sends the take-back only once that model
has caught up. The daemon keeps answering until then, so main answers from
an exact model the moment the daemon lets go. A remote viewer still takes
over at once, since main will not answer for it.

The handoff E2E now runs with the daemon answering and with main answering.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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: e5b07f78-f496-42cc-bbc7-7b0d096f8981
📥 Commits

Reviewing files that changed from the base of the PR and between 7c9aa6264266e9db3f7403215883dd62cbc9ada5 and bff7c7f.

📒 Files selected for processing (26)
  • 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/daemon-query-responder-delegation.test.ts
  • src/main/runtime/daemon-query-responder-delegation.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/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; 7 remain after this review.

break
}
}
const droppedData = shouldNotify ? queuedTerminalOutputData(entry) : ''

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Find callers of replaceBacklogWithWarning and where backgroundBacklogDropped resets.
rg -n -C4 'replaceBacklogWithWarning\s*\(|backgroundBacklogDropped\s*=' src/renderer/src/lib/pane-manager

Repository: stablyai/orca

Length of output: 5955


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- backlog module ---'
nl -ba src/renderer/src/lib/pane-manager/pane-terminal-output-queue-backlog.ts
printf '%s\n' '--- writer relevant blocks ---'
nl -ba src/renderer/src/lib/pane-manager/pane-terminal-output-writer.ts | sed -n '1,280p'
printf '%s\n' '--- all state references in pane-manager ---'
rg -n -C5 -F -- 'backgroundBacklogDropped' src/renderer/src/lib/pane-manager

Repository: stablyai/orca

Length of output: 23759


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- callback consumers ---'
rg -n -C6 -F -- 'onBackgroundBacklogDropped' src
printf '%s\n' '--- flusher ---'
nl -ba src/renderer/src/lib/pane-manager/pane-terminal-output-flusher.ts
printf '%s\n' '--- recovery symbol references ---'
rg -n -C5 'requestRegisteredTerminalBacklogRecovery|background backlog|backlog recovery' src/renderer/src/lib

Repository: stablyai/orca

Length of output: 28805


Salvage query bytes on every backlog replacement.

backgroundBacklogDropped stays true until the queue entry is discarded. A later write can exceed the cap before that happens. The later replacement captures no bytes and does not call onBackgroundBacklogDropped.

Split the first-drop restore notification from query salvage. Pass the discarded bytes to the salvage path on every replacement.

…tract

This PR raises PROTOCOL_VERSION to 45, so the packaged local-build
contract has to name 45 as the daemon protocol and list it as
attachable. local-build-compatibility-contract.test.ts failed without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor

Closing as not planned. The proposal explicitly admits a remote-attach handover window in which both the daemon and remote viewer can answer an already-emitted query, injecting duplicate replies as program input. It also inherits model rebuild/history trade-offs and adds a responder protocol/state machine. Real CPU savings do not meet our zero-negative-trade-off and low-risk bar here.

@nwparker nwparker closed this Oct 11, 2026
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