Skip to content

fix(terminal): keep each PTY query's reply owner across a visibility flip - #27129

Closed
outof-place wants to merge 5 commits into
stablyai:mainfrom
outof-place:perf/pty-responder-stamp
Closed

outof-place wants to merge 5 commits into
stablyai:mainfrom
outof-place:perf/pty-responder-stamp

Conversation

@outof-place

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

Copy link
Copy Markdown
Contributor

Stacked on #27033. This PR contains that PR's commit, so please review only the commits after it (fix(terminal): keep each PTY query's reply owner across a visibility flip, refactor(terminal): stamp each pending chunk with its delivery mode, and a one-line cleanup). I'll rebase once #27033 lands.

ELI5

When a program in a terminal asks the terminal a question (for example "where is the cursor?"), exactly one side must answer: the visible terminal pane, or Orca's main process when the pane is hidden. Orca picks the answerer when the output arrives, but it could change its mind if the pane was hidden or shown before that output was delivered. Then the question got no answer, or two. Now the choice made on arrival sticks.

What Changed

Before: if a pane was hidden while a query was still queued in main, the program never got a reply. If a hidden pane was shown while a query was queued, the program got two replies. Agent CLIs and TUIs send these queries at startup and on resize, which is when users switch tabs. A missing reply makes them wait for a timeout, and a duplicate shows up as stray input.

Mechanism:

  • One function now owns how main delivers a PTY's bytes to the renderer: rendererPtyViewDelivery returns 'parse', 'sidecarsOnly' or 'drop'. The existing drop and sidecar-only predicates and the query responder (shouldModelAnswerHiddenPtyQueries) all read it. Main's model owns a chunk's replies unless its delivery is 'parse'.
  • Each pending entry now records the delivery mode it was ingested under (ingestedDelivery, absent for 'parse'). Delivery follows that record instead of deciding the owner again at flush time. A later mode, such as a native view that main feeds, can be added to the same function and stamp without another ownership rule.
  • An entry never mixes reply owners. When the owner changes before new bytes join an entry (settlePendingDeliveryStamp):
    • The view stops parsing: the queries the view still owed are handed to it, and the entry takes the new mode.
    • The view parses again: the queued bytes go to sidecars only, and the next bytes start a fresh entry.
    • A change between two non-parse modes (for example a sidecar leaving while the pane stays hidden) keeps the owner, so nothing is handed back.
  • Bytes the view was supposed to answer but will now skip (dropped, or sent to sidecars only) have their queries sent to the view first (sendSkippedViewQueries). This reuses the existing pending-cap path: extractDroppedPtyQueryBytes plus the renderer's salvageRendererQueriesFromDiscardedRestoreData.
  • Bytes ingested while gated never reach the view's parser, even after a reveal. They go to sidecars only, and the view repaints from main's model as it already does for gated output.

Why

  • Making the delivery decision at send time can't work: the reply owner is fixed at ingestion, because that's when main's model either forwards its replies or discards them.
  • I considered having main's model answer late for dropped bytes. That would mean capturing replies per chunk in the emulator and releasing them on drop, which is a much larger change to the runtime.
  • I also considered forcing the queued bytes through to the hidden view. The hidden view drops large stragglers once its restore is latched, so the reply could still be lost.
  • Handing the view only the query bytes already exists for pending-cap drops, keeps the stream shape the renderer expects, and stays bounded (DROPPED_QUERY_SALVAGE_MAX_CHARS).

Trade-offs

Measured on macOS (M4 Max) at load average ~400 from parallel builds, so absolute times are inflated; the ratios are what matter.

Merge risk: medium (delivery core), contained.

  • Scope: main-side delivery only (accept.ts, flush.ts, payload.ts, pending.ts, exit.ts, the hide path in resize-visibility.ts, the gate and the query-authority predicate). No renderer or wire change; sidecarOnly and droppedOutput are existing payload fields.
  • Kill switch: with terminalHiddenDeliveryGate off, rendererPtyViewDelivery always returns 'parse', no entry is ever stamped, and delivery behaves exactly as before this PR.
  • Tests: 6 new unit tests (5 fail without the change), 2 new e2e tests (0/0 and 2/2 replies before, 1/1 after), and the existing hidden-delivery e2e set.

User-facing costs, both ways:

before after
A query queued across a hide no reply (the program waits for its timeout) one reply
A query queued across a reveal two replies (the second shows up as stray input) one reply
Per ingested chunk (hot path) the gate check: 5.8 ns the delivery-mode check: 20.3 ns (+14.5 ns, measured), plus one Map lookup to compare stamps (not measured separately)
A flip while bytes are queued the queued bytes are dropped or sent as-is one query scan of the queued entry: 1.45 ms for 256 KB, the size at which main pauses the PTY; at most 4,096 query chars are sent to the view
A reveal while gated bytes are queued those bytes reach the view's parser they go to sidecars only and the view restores from main's model once: the same restore a gated PTY already pays on reveal
Memory — one optional field on a PTY's pending entry (at most one entry per PTY); nothing retained after the entry drains
Disk, IPC — unchanged

Flips with queued bytes are rare: the bytes have to be waiting behind a full renderer window or a batch timer at that exact moment. So the scan and the extra restore are paid seldom, and only by panes that would otherwise get a wrong number of replies.

Maintenance cost: one new concept: each pending entry carries the delivery mode it was ingested under, and an entry never mixes reply owners. rendererPtyViewDelivery becomes the single place that decides delivery, which later delivery modes can extend instead of adding parallel predicates. +218/−23 production lines and +436 test lines.

Verdict: free win: it fixes lost and duplicated terminal replies for +14.5 ns per chunk (plus one Map lookup), and a one-off scan on the rare flip that has bytes queued.

Linked Issue

Fixes #27128

Visual Proof

N/A: no visual change. The change is in which side answers terminal queries; the e2e test below counts the replies a program actually reads.

Testing

  • New e2e tests/e2e/terminal-query-reply-visibility-flip.spec.ts. It holds the renderer's delivery credit with the existing e2e ACK gate so the query stays queued, flips the pane, and counts replies to one CSI 6n and one CSI c:

    • hidden before the flush: 0 and 0 before this change, 1 and 1 after.
    • shown before the flush (with a sidecar): 2 and 2 before, 1 and 1 after.
  • Related hidden-delivery e2e, all passing headless (ORCA_BACKGROUND_LAUNCH=1, macOS): terminal-hidden-sidecar-pacing, terminal-hidden-tui-visual-restore, terminal-hidden-view-parking (including 25 park/reveal cycles), terminal-codex-hidden-startup-background, automation-hidden-terminal-first-mount. 13 of 13 pass.

  • New unit tests in pty-ipc-hidden-delivery-flip-replies.test.ts (6) cover both flip directions, through the flush path and through the append path, plus a mode change that keeps the owner. The 5 flip tests fail without the change.

  • pnpm tc, the changed-code quality gate, and 5983 tests under src/main/ipc and the terminal runtime pass.

  • I manually tested these changes locally (not done: verified only through the headless e2e and unit tests listed above, no interactive session)

  • Automated tests added/updated, or explained why not below

What ran locally (macOS, headless): pnpm tc; pnpm run check:code-quality:changed against #27033's head; oxlint and oxfmt --check on the changed files; pnpm run check:max-lines-ratchet; vitest on src/main/ipc plus the terminal runtime suites (5983 tests); the 2 new e2e tests plus the 11 related hidden-delivery e2e tests listed above (rerun after the delivery-mode refactor: 13 of 13). Not run locally: the full pnpm lint, the full pnpm test, and pnpm build beyond the e2e build; CI covers those.

AI Disclosure

Written with Claude Opus 5.5 (Claude Code), reviewed and verified by the author.

Review

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.

Notes

  • Security: no new IPC or inputs.
  • Cross-platform: platform-independent main-process delivery code.
  • SSH: projection admissions follow the same transfer paths as the existing drops.
  • Mobile/remote views: the stamp covers only the local renderer view.
  • Performance: no extra work on the hot path beyond one gate check per ingested chunk. A flip with queued bytes costs one query scan of the queued entry, as a pending-cap drop does.
  • Backwards compatibility: no wire change; sidecarOnly and droppedOutput are existing payload fields.

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): only pnpm typecheck and the subsets above ran locally; the rest is left to CI

🤖 Generated with Claude Code

outof-place and others added 2 commits October 10, 2026 01:40
…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]>
…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]>
@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →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: 677d66b7-3316-4b12-9b59-0b7955623e12

📥 Commits

Reviewing files that changed from the base of the PR and between 8d45934 and 5e82dfa.


📒 Files selected for processing (1)
  • 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; 2 remain after this review.



📝 Walkthrough

Walkthrough

Hidden PTY delivery now distinguishes data parsed by the view, delivered only to sidecars, or dropped. Pending data retains its delivery mode across visibility and delivery-interest changes. The main model answers queries for data the view will not parse. The renderer routes sidecar-only data to sidecars and acknowledges its character count. Tests cover query replies during visibility changes and hidden-pane delivery pacing.


Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 5e82d

Queued terminal queries retain one reply owner through visibility changes, and the tests cover both flip directions. No actionable merge-blocking risk was established in the reviewed changes.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 37.84% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 24 files. 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 describes the primary change: preserving PTY query reply ownership across terminal visibility changes.
Description check Passed The description is detailed and mostly complete. It includes the user impact, implementation approach, rationale, linked issue, visual-proof explanation, testing results, AI disclosure, scope consider…
Linked Issues check Passed Issue #27128 requires exactly one reply for each queued terminal query in both visibility-flip directions. The delivery stamp records the ingestion mode, settles pending entries when the mode changes,…
Out of Scope Changes check Passed The pending-entry metadata, hidden-delivery predicates, query salvage, sidecarOnly payload handling, renderer sidecar dispatch, and related tests support issue #27128. The renderer changes provide t…

  • 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: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4eb87a6f-3c54-42bd-aa7a-1f09c2c07b26
📥 Commits

Reviewing files that changed from the base of the PR and between 3563270 and c76a98f.

📒 Files selected for processing (23)
  • src/main/ipc/pty-hidden-delivery-gate.test.ts
  • src/main/ipc/pty-hidden-delivery-gate.ts
  • src/main/ipc/pty-ipc-hidden-delivery-flip-replies.test.ts
  • src/main/ipc/pty-ipc-hidden-delivery-gate.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-view-gate-stamp.ts
  • src/main/ipc/pty/delivery/pending.ts
  • src/main/ipc/pty/ipc/resize-visibility.ts
  • src/main/ipc/pty/session.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
  • 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.

Comment on lines 43 to 49
return (
isTerminalModelQueryAuthorityEnabled(opts.settings) &&
!opts.hasRemoteViewSubscriber &&
shouldDropHiddenRendererPtyData(opts.ptyId, opts.settings)
isHiddenRendererPtyViewGated(opts.ptyId, opts.settings)
)
}

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:

sed -n '60,130p' src/main/ipc/pty/delivery/payload.ts
sed -n '85,115p' src/main/ipc/pty/delivery/accept.ts
git show 9d94a20f84d10641f217b9539b0aefeff8d9b1ed:src/main/runtime/terminal-model-query-authority.ts | sed -n '30,55p'
git show 9d94a20f84d10641f217b9539b0aefeff8d9b1ed:src/main/ipc/pty-hidden-delivery-gate.ts | sed -n '85,130p'

Repository: stablyai/orca

Length of output: 6829


🏁 Script executed:

set -e
printf '%s\n' '--- current payload functions ---'
nl -ba src/main/ipc/pty/delivery/payload.ts | sed -n '55,155p'
printf '%s\n' '--- current ingestion/call sites ---'
rg -n -F --glob '*.ts' -- 'sendPtyDataToRenderer(' src/main src/renderer || test "$?" -eq 1
rg -n -F --glob '*.ts' -- 'shouldModelAnswerHiddenPtyQueries' src/main || test "$?" -eq 1
printf '%s\n' '--- authority current and base ---'
nl -ba src/main/runtime/terminal-model-query-authority.ts | sed -n '1,90p'
git show 9d94a20f84d10641f217b9539b0aefeff8d9b1ed:src/main/runtime/terminal-model-query-authority.ts | nl -ba | sed -n '1,90p'
printf '%s\n' '--- relevant base-to-head diff ---'
git diff --find-renames 9d94a20f84d10641f217b9539b0aefeff8d9b1ed c76a98fd0d65626cb15e89a5dc45489d8aa228e0 -- src/main/ipc/pty/delivery/payload.ts src/main/runtime/terminal-model-query-authority.ts src/main/runtime/pty* src/main/runtime/rpc src/renderer/src/components/terminal-pane/pty-connection

Repository: stablyai/orca

Length of output: 21523


🏁 Script executed:

set -e
nl -ba src/main/ipc/pty/delivery/payload.ts | sed -n '55,155p'
printf '%s\n' '--- authority refs ---'
rg -n -F --glob '*.ts' -- 'shouldModelAnswerHiddenPtyQueries' src/main || test "$?" -eq 1
printf '%s\n' '--- local and remote reply symbols ---'
rg -n -F --glob '*.ts' -- 'salvageRendererQueriesFromDiscardedRestoreData' src/renderer src/main || test "$?" -eq 1
rg -n -i --glob '*.ts' -- 'multiplex|remote.*query|query.*remote|sendDesktopQueryReplyImmediate' src/main/runtime src/renderer/src/components/terminal-pane/pty-connection || test "$?" -eq 1
printf '%s\n' '--- base/head diff stat and targeted diff ---'
git diff --stat 9d94a20f84d10641f217b9539b0aefeff8d9b1ed c76a98fd0d65626cb15e89a5dc45489d8aa228e0
git diff 9d94a20f84d10641f217b9539b0aefeff8d9b1ed c76a98fd0d65626cb15e89a5dc45489d8aa228e0 -- src/main/ipc/pty/delivery/payload.ts src/main/runtime/terminal-model-query-authority.ts

Repository: stablyai/orca

Length of output: 41765


🏁 Script executed:

set -e
printf '%s\n' '--- local callback ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/live-data-callback.ts | sed -n '1,90p'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/hidden-startup-renderer-query-write.ts | sed -n '95,155p'
printf '%s\n' '--- authority and ingestion ---'
nl -ba src/main/runtime/terminal-model-query-authority.ts | sed -n '35,60p'
rg -n -F --glob '*.ts' -- 'shouldModelAnswerHiddenPtyQueries' src/main
printf '%s\n' '--- remote stream definitions and pause branches ---'
rg -n -i --glob '*.ts' -- 'remote|multiplex|paused|pause' src/main/runtime/rpc/methods/terminal src/main/runtime | head -160
printf '%s\n' '--- exact base/head changes ---'
git diff 9d94a20f84d10641f217b9539b0aefeff8d9b1ed c76a98fd0d65626cb15e89a5dc45489d8aa228e0 -- src/main/runtime/terminal-model-query-authority.ts src/main/ipc/pty/delivery/payload.ts src/main/ipc/pty/delivery/accept.ts src/main/runtime/rpc/methods/terminal src/renderer/src/components/terminal-pane/pty-connection

Repository: stablyai/orca

Length of output: 40210


🏁 Script executed:

set -e
printf '%s\n' '--- remote initialization complete block ---'
nl -ba src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts | sed -n '90,175p'
printf '%s\n' '--- pending multiplex output implementation ---'
rg -n -F --glob '*.ts' -- 'function appendPendingMultiplexOutput' src/main/runtime/rpc/methods/terminal || test "$?" -eq 1
rg -n -F --glob '*.ts' -- 'appendPendingMultiplexOutput' src/main/runtime/rpc/methods/terminal || test "$?" -eq 1
nl -ba src/main/runtime/rpc/methods/terminal/terminal-stream-replay.ts | sed -n '1,220p'
printf '%s\n' '--- output pause/resume and pending drain ---'
rg -n -i --glob '*.ts' -- 'outputPaused|flush.*pending|pending.*output|drain.*pending' src/main/runtime/rpc/methods/terminal || test "$?" -eq 1

Repository: stablyai/orca

Length of output: 29479


🏁 Script executed:

set -e
nl -ba src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts | sed -n '100,165p'
printf '%s\n' '--- replay implementation ---'
nl -ba src/main/runtime/rpc/methods/terminal/terminal-stream-replay.ts | sed -n '1,240p'
printf '%s\n' '--- all replay consumers ---'
rg -n -C 5 -i --glob '*.ts' -- 'pendingOutput|appendPendingMultiplexOutput|flush.*pending|drain.*pending|outputPaused' src/main/runtime/rpc/methods/terminal

Repository: stablyai/orca

Length of output: 42374


Do not yield query authority to a paused remote stream.

When the local view is hidden and viewGatedAtIngestion is true, sendPtyDataToRenderer skips sendSkippedViewQueries and sends only sidecarOnly data. The local renderer does not salvage that payload because it is not marked droppedOutput.

At the same time, shouldModelAnswerHiddenPtyQueries yields for any registered remote subscriber. The paused multiplex callback then returns without forwarding the bytes. CSI 6n and CSI c therefore receive no reply.

Make remote query authority depend on active output consumption. When the registered remote stream is paused, main must retain query authority or route the extracted queries to the local salvage path.

outof-place and others added 2 commits October 10, 2026 06:25
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]>
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]>
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.

Terminal queries lose their reply, or get two, when the pane's visibility flips while the query is queued

1 participant