Skip to content

fix(terminal): answer queries a multiplex viewer's initial snapshot covers - #27312

Closed
outof-place wants to merge 3 commits into
stablyai:mainfrom
outof-place:fix/multiplex-attach-query-gap
Closed

outof-place wants to merge 3 commits into
stablyai:mainfrom
outof-place:fix/multiplex-attach-query-gap

Conversation

@outof-place

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

Copy link
Copy Markdown
Contributor

ELI5

When a remote viewer opens a terminal just as a program in it asks the terminal a question ("where is the cursor?"), the question could fall into a gap where neither Orca nor the viewer answered it, and the program waited for its own timeout (5 s for orb). Orca now answers questions that fall into that gap.

What Changed

  • initializeMultiplexStream records, just before the stream registers as a remote view subscriber, whether main's model was answering this PTY's queries (runtime.modelAnswersTerminalQueries, the same per-chunk decision onPtyData makes). The flag is stored on the stream as modelHeldQueryAuthority.
  • publishMultiplexInitialSnapshot already splits the output it buffered during the attach at the snapshot's seq: what the snapshot covers is dropped and the rest goes out live. Now, when modelHeldQueryAuthority is set, answerQueriesCoveredBySnapshot first extracts the queries from the covered part. It uses the extractor the hidden-pane salvage uses (extractHiddenStartupRendererQueryData, which now also returns the queries in output order as orderedQueryData), and hands them to runtime.answerTerminalQueriesFromModel in that order.
  • answerTerminalQueriesFromModel writes the query bytes once more on the PTY model's write chain, with forwardQueryReplies: true. Main's model has already parsed that output, so the replies reflect the screen after it. Queries don't change terminal state, so the second write only produces the replies.

Before: a query in output taken in between the stream's registration and its snapshot got no reply. After: main answers it once. Output after the snapshot reaches the viewer live, and the viewer answers it, as before. If the stream took reply authority from another remote view rather than from main, nothing changes, because that view saw the output live.

Why

The gap is between two steps that both have to stay: the view must hold reply authority from registration on, so main doesn't answer output the view will also answer live. And the snapshot has to come after the viewport update. Answering the covered queries at the one point that knows exactly which output the snapshot covers keeps each query's reply single.

Alternatives considered:

  • Register the view subscriber only after the snapshot. Output buffered between the snapshot's seq and the registration would then be answered by main, and again by the viewer when it arrives live.
  • Let the viewer answer the end of the seed. The snapshot is serialized screen state and holds no query bytes. A viewer guessing from it can't tell whether main already answered.
  • Make the snapshot carry "pending query" flags. That needs a capability and client changes for a case the host can settle on its own.

For a cursor-position query, the reply uses the cursor after the covered output, not at the instant of the query. A program waiting for its answer hasn't moved the cursor, so this is the position it asked for. The same approximation is already used where hidden-pane queries are salvaged.

Linked Issue

Fixes #27311

Visual Proof

N/A: no UI change. The effect is a program that gets its reply instead of waiting for its timeout. The unit tests below pin the window.

Testing

  • terminal-multiplex-snapshot-covered-queries.test.ts (new) holds the snapshot while output arrives:

    • a DSR inside the snapshot's range is handed to main;
    • an OSC 11 straddling the boundary and a DA1 after it reach the viewer live;
    • nothing is handed over when another view held the authority, or when the covered output has no query;
    • a cursor-position query, an OSC 11 and DA1 in the covered output reach main in that order. Programs send DA1 last as an "all replies are in" sentinel, so the order matters.
    • Without the change, the first test fails; without the ordering fix, the last one does.
  • terminal-query-responder.test.ts (one new case), on the real OrcaRuntimeService and emulator: output taken in while a remote view holds authority stays unanswered, and answerTerminalQueriesFromModel then gives exactly the DA1 and cursor-position replies.

  • Ran locally (macOS arm64), all passing:

    • node node_modules/typescript/bin/tsc --noEmit -p config/tsconfig.node.json and -p config/tsconfig.tc.web.json (what tc:node / tc:web run);
    • pnpm run audit:anti-slop;
    • pnpm exec oxlint and pnpm exec oxfmt --write on the changed files;
    • pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=4 src/main/runtime/rpc src/main/runtime/terminal-query-responder.test.ts src/main/ipc/pty src/main/daemon/daemon-server src/renderer/src/components/terminal-pane tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts: 1045 files, 9941 tests.
  • Three test files with their own runtime stubs got the new method.

  • End to end, automated (a harness, not a person): a build with this fix ran against real OrbStack VMs, where orb showed the stall. Over 13 rounds it timed each start through the terminal stream: 0 of 69 starts waited near 5 s, against 2 of 42 (about 5.2 s each) before the fix. That is 51 shell prompts at 70–198 ms and 18 Claude first frames at 275–622 ms. One more start, the first after the VM templates were rebuilt, showed no prompt for 30 s; that is a VM issue, not this stall. Details are in a comment below. A synthetic repro (a program asking in a tight loop while a viewer attaches) never landed a query inside the ~1 ms window in 24 attempts, so these runs are the end-to-end evidence.

  • I manually tested these changes locally

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

AI Disclosure

Claude Code (Claude Opus 5.5) wrote this change, its tests and this description, and ran the checks above, working for @outof-place.

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

  • Cross-platform: platform-neutral; the decision and the emulator are the same on all hosts.
  • SSH: remote PTYs go through the same multiplex path, and the model only answers where it already would.
  • Mobile and backwards compatibility: no wire change.
  • Performance: one string scan of the buffered output the snapshot covers, once per attach.

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

…overs

A multiplex stream takes terminal-query reply authority from main's model
when it registers (registerRemoteTerminalViewSubscriber), and sends its
initial snapshot later, after the viewport update and the serialize. Output
main took in between went into its model unanswered, because a remote view
now held the authority, and the snapshot covers it, so the viewer never
saw those bytes live either. A program that asked for the cursor position
or a color in that window waited for its own timeout (orb waits 5 s).

The stream now records whether main's model held the authority it took.
If it did, publishing the initial snapshot extracts the queries from the
buffered output the snapshot covers and lets main's model answer them
(answerTerminalQueriesFromModel: the query bytes written again on the
model's write chain with replies forwarded; queries leave its state as it
was). Output after the snapshot still goes to the viewer live, and the
viewer answers it, so each query gets one reply. A stream that took the
authority from another view leaves the covered output alone, as that view
saw it live.

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: 012b15d4-6096-4446-9b38-48f935c6319e


📥 Commits

Reviewing files that changed from the base of the PR and between ab8a19f and 3dec3b6.



📒 Files selected for processing (3)
  • src/main/runtime/rpc/methods/terminal/terminal-snapshot-covered-queries.ts
  • src/main/runtime/rpc/terminal-multiplex-snapshot-covered-queries.test.ts
  • src/shared/terminal-reply-query-extraction.ts


🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/runtime/rpc/terminal-multiplex-snapshot-covered-queries.test.ts
  • src/main/runtime/rpc/methods/terminal/terminal-snapshot-covered-queries.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

Walkthrough

The runtime now reports whether the model answers a PTY’s terminal queries and can queue query data for the headless PTY. Multiplex stream initialization records whether the model held query authority. When the initial snapshot does not overflow, snapshot processing extracts queries from pending output covered by the snapshot and sends nonempty query data to the model if the model held authority. Tests cover authority changes and snapshot-covered output.



Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to 3dec3

During multiplex attach, a cursor-position query followed by cursor movement before the initial snapshot can receive the later position, potentially confusing applications that rely on the reply. Resolve this protocol-correctness issue before merging.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 41.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 14 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 Issue #27311 is an active direct coding requirement. initializeMultiplexStream records whether main held query authority before the remote subscriber registers. Snapshot handling extracts queries fr…
Out of Scope Changes check Passed The changes remain within issue #27311. The runtime methods, stream authority state, snapshot recovery, ordered query extraction, test-runtime updates, and focused regression tests support exactly-onc…
Description check Passed The description is complete and directly explains the user impact, implementation, rationale, alternatives, linked issue, testing, compatibility considerations, and checklist status. It marks visual p…
Title check Passed The title clearly and concisely describes the main change: answering terminal queries covered by a multiplex viewer's initial snapshot.

  • 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: d2fdf3d0-9af6-4de6-9723-40f6521ee336
📥 Commits

Reviewing files that changed from the base of the PR and between 853c25d and 9132f3e.

📒 Files selected for processing (11)
  • src/main/runtime/orca-runtime-maybe-hydrate-headless-from-renderer.ts
  • src/main/runtime/rpc/methods/terminal/terminal-multiplex-initial-snapshot.ts
  • src/main/runtime/rpc/methods/terminal/terminal-multiplex-stream-initialization.ts
  • src/main/runtime/rpc/methods/terminal/terminal-snapshot-covered-queries.ts
  • src/main/runtime/rpc/methods/terminal/terminal-stream-types.ts
  • src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts
  • src/main/runtime/rpc/terminal-multiplex-resync-replay-trim.test.ts
  • src/main/runtime/rpc/terminal-multiplex-snapshot-covered-queries.test.ts
  • src/main/runtime/rpc/terminal-multiplex-test-harness.ts
  • src/main/runtime/rpc/terminal-requested-snapshot-unavailability.test.ts
  • src/main/runtime/terminal-query-responder.test.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 +183 to +185
const completion = state.writeChain.then(() =>
state.emulator.write(queryData, { forwardQueryReplies: true })
)

@coderabbitai coderabbitai Bot Oct 10, 2026 •

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 | 🟠 Major | 🏗️ Heavy lift

Answer stateful queries at their original output position.

If buffered output contains \x1b[6n, then moves the cursor before snapshot publication, this write answers the cursor-position query using the later cursor position. Two queries separated by a cursor move can therefore receive the same incorrect reply. Capture replies as the original output is parsed, or preserve the emulator state at each query position before forwarding replies.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Leaving this as is, on purpose. The covered window runs from the stream's registration to its initial snapshot, about a millisecond. A program that sent a cursor-position query is blocked reading the reply, so it moves no cursor inside that window, and the cursor after the covered output is the one it asked about. Only a program that sends two queries around a cursor move within that millisecond, without waiting for either reply, would get the later position for both.

An exact answer at each query's position would need main's model to keep reply authority until the snapshot and hand it to the viewer atomically at the snapshot's seq. The snapshot is serialized asynchronously, so that is a bigger change than this fix. The PR description states the approximation; the hidden-pane query salvage already makes the same one.

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.

@outof-place Thanks for clarifying the intended approximation. For a program that waits for each query reply before moving the cursor, the replay uses the expected cursor position. The finding applies to queries interleaved with cursor changes without waiting for replies.

I accept leaving that edge case outside this fix. Would you like a follow-up issue for exact per-query replies with an atomic authority handoff at the snapshot sequence?


✏️ Learnings added
Learnt from: outof-place
Repo: stablyai/orca PR: 27312
File: src/main/runtime/orca-runtime-maybe-hydrate-headless-from-renderer.ts:183-185
Timestamp: 2026-10-11T12:21:17.118Z
Learning: In stablyai/orca, src/main/runtime/orca-runtime-maybe-hydrate-headless-from-renderer.ts intentionally implements answerTerminalQueriesFromModel by replaying snapshot-covered queries against the model's current state. This is an accepted approximation, consistent with hidden-pane query salvage. Exact stateful replies for queries interleaved with cursor changes without waiting for replies are outside this recovery's scope. An exact implementation needs coordinated query-reply authority handoff at the asynchronously serialized snapshot's output sequence.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

The paired-runtime remount test and the cross-version wire host stub build
their own runtime for terminal.multiplex; without the two methods the
covered-query answer needs, stream setup threw before the host could refuse
the write, so the remount never happened.

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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Preserve query data across the second overflow. · terminal-multiplex-initial-snapshot.ts:137-150

src/main/runtime/rpc/methods/terminal/terminal-multiplex-initial-snapshot.ts:137-150
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve query data across the second overflow.

When the retry overflows again, publishMultiplexInitialSnapshot clears stream.pendingOutput. The later model recovery and viewer replay are both skipped for initialOutputOverflowed. A retained query can therefore receive no reply.

The renderer's resync request carries only scrollbackRows, and the recovery snapshot restores screen state. It does not restore or reissue the discarded query bytes. Preserve query data separately from the truncated output path, then answer covered queries with the captured model authority and deliver post-snapshot queries to the viewer.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b4b9d11e-d2c6-418a-8b60-8424a84b1324
📥 Commits

Reviewing files that changed from the base of the PR and between 9132f3e and ab8a19f.

📒 Files selected for processing (2)
  • tests/e2e/cross-version-wire/host-terminal-runtime-stub.ts
  • tests/e2e/paired-runtime-rejected-input-remount.unit.test.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.

answerQueriesCoveredBySnapshot joined the extracted queries by kind (stateless, stateful, OSC color), so
a cursor-position query followed by DA1 was answered DA1 first. Programs that send DA1 as an "all replies
are in" sentinel then read the other query as unsupported. The extractor now also returns every query in
output order (`orderedQueryData`), and the covered-query answer uses it. Its other callers are unchanged.

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

Copy link
Copy Markdown
Contributor Author

On the outside-diff note about the second overflow in terminal-multiplex-initial-snapshot.ts: an overflow means more than TERMINAL_MULTIPLEX_PENDING_MAX_BYTES arrived during the attach. By then appendPendingMultiplexOutput has already dropped the oldest chunks (trimPendingOutputToBudget), queries included. Answering the queries in what is left would still miss some, and a program waiting on a reply isn't the one producing that much output. So the overflow path keeps its existing behaviour (truncated snapshot, no replay). Salvaging queries from every trimmed chunk would be a separate change.

@outof-place

Copy link
Copy Markdown
Contributor Author

Rechecked with this fix on a build with OrbStack machines and warm templates. A harness ran 13 rounds and measured, through the terminal stream, the time to the first shell prompt and to Claude's first frame.

  • Shell in a worktree machine: 26/26 reached the prompt, 70–162 ms.
  • Shell in a sandbox machine: 25/26, 70–198 ms. The one miss was the first round after the templates were rebuilt, with no prompt for 30 s. That is not the ~5 s query stall.
  • Claude in the sandbox: first frame in 275–622 ms over 18 timed starts. The other 8 drew but weren't timed by the probe.
  • Result: 0 of 69 starts near 5 s, versus 2 of 42 stalls (~5.2 s) before the fix.

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 go unanswered when they arrive while a multiplex viewer attaches

1 participant