Skip to content

fix(terminal): answer a query in its own turn when the kernel is quiet (#13892) - #13998

Closed
nwparker wants to merge 2 commits into
mainfrom
nwparker/fix-13892-sync-echo-check
Closed

nwparker wants to merge 2 commits into
mainfrom
nwparker/fix-13892-sync-echo-check

Conversation

@nwparker

@nwparker nwparker commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

fish asks the terminal "what colour is your background?" and, a moment later, "are you
there?". Orca used to hold the colour answer back for a fraction of a second (to avoid a
different bug) while sending the "are you there?" answer immediately. fish uses that second
answer as its signal that the prompt is done, so it handed the terminal to the program you
just launched — and the colour answer arrived a beat later, straight into that program's
stdin. Now Orca checks, without leaving the current turn, whether holding back is even
necessary; when it isn't, it answers immediately and nothing can overtake it.

What Changed

  1. config/patches/[email protected] (extends the existing patch; no new file target,
    no new module, no new prebuild artifact):

    • src/unix/pty.cc: new PtyEchoState exported as echoState — tcgetattr(fd) ->
      1 (ECHO set) / 0 (clear) / -1 (bad arg or error). <termios.h> was already
      reachable in this file (it uses struct termios and tcsetattr), so nothing was added.
    • lib/unixTerminal.js (and src/unixTerminal.ts for consistency): readEchoState(),
      guarded on typeof pty.echoState === 'function'. Typings untouched — step 2 reads it
      defensively, exactly as readPtySlavePath reads ptsName today.
  2. src/shared/pty-slave-line-discipline-echo.ts: PtySlaveEchoSyncProbe and
    createPtySlaveEchoSyncProbe(pty, platform) — undefined on win32 or when
    readEchoState is absent; 1 -> 'echoing', 0 -> 'quiet', anything else (including a
    throw or -1) -> 'unknown'.

  3. src/shared/pty-startup-reply-delivery.ts: the sync probe is a 4th ctor param. In
    answer(), after the !defersWrite(...) early return and before the
    MAX_TRACKED_REPLIES branch:

    if (this.pendingWrites.length === 0 && this.echoSyncProbe?.() === 'quiet') {
      return this.writeReply(reply, onFailed, true)
    }

    Three load-bearing properties: pendingWrites.length === 0 preserves ORDER (a reply
    arriving behind a held one queues instead of jumping, which also makes this mutually
    exclusive with the MAX_TRACKED_REPLIES branch); kernelEchoImpossible = true matches
    what today's 'quiet' verdict passes, so the readline/BEL projection stays armed and only
    the kernel caret projection is skipped; and it fails OPEN — no probe, 'unknown' or
    'echoing' is today's behavior byte for byte.

  4. Wired at the three sites that already build the async probe: local provider, daemon
    session (via a new optional echoSyncProbe on SubprocessHandle, produced in
    pty-subprocess.ts next to slavePath, because the daemon's pty object lives there), and
    the relay pty handler.

  5. Tests plus CI registration — both the shell_contracts run list and the shard
    --exclude list in pr.yml, and pr-workflow-parallelism.test.mjs so the registration
    itself is guarded — and the repro harness under tests/tools/.

Why

The earlier "deadline flush" framing was WRONG

The first hypothesis was that the 200 ms probe deadline flushes the reply into a tty that is
still cooked. That is factually wrong, and it was disproven with a native tcgetattr probe
sampling the slave's ECHO bit at the moment each query is observed: echoAtObserve=0 for
all 13 queries across 3 runs
— the tty is NEVER echoing when a query is observed. The
200 ms hold is pure PROBE LATENCY: the async probe is execFile('stty'), a subprocess per
poll. The leak also reproduces at a 5.0 ms and a 15.6 ms defer. So the real rule is:
any deferral past the query's own event-loop turn is sufficient to lose the race, because
DA1 (fish's read sentinel) is written in that same turn and overtakes the held OSC reply.
Every "fix the deadline branch" design is therefore dead, and so are these, all measured and
rejected:

  • Order-preserving FIFO — binds DA1 to the stty fork. DA1 defer p90 102-172 ms with 8
    panes, max 228-309 ms, and fish BLOCKS on DA1 every prompt. Also failed to close the bug.
  • Drop-on-expiry — fixes only 83%, and silently destroys answers a slow-to-raw querier is
    blocked on, i.e. reintroduces [Bug]: Raw OSC 10/11 color-query replies leak as text in Linux agent pane (opencode) #12112's shape. Breaks 4 existing tests that encode "the wait
    always ends in a write".
  • Renderer-ordering — premise factually wrong: isCoalescibleInput already excludes
    replyOnly items.
  • Do-nothing — this is stdin corruption of the next child process.

What the native patch does, and how it degrades

A POSIX pty master's mode ioctls are redirected to the slave, so tcgetattr on the master
fd Orca already owns reads the slave's ECHO bit with no fork and no extra fd. Verified by
direct C on macOS (master ECHO tracks the slave: 0 after clear, 1 after set) at 0.331
microseconds/op, and on Linux in gcc:13.

Degradation is the important half:

  • A kernel that does not redirect would expose the master's own termios, whose ECHO
    defaults SET. That reads as 'echoing', i.e. today's deferral. It fails SAFE, never to a
    false 'quiet'.
  • Unpatched or prebuilt node-pty (an older relay host, a stale node_modules) —
    readEchoState is absent, createPtySlaveEchoSyncProbe returns undefined, the
    echoSyncProbe option is simply not passed, and delivery is byte-for-byte what ships
    today. No wire change and no capability negotiation: echoSyncProbe is a host-local
    function reference that is never serialized, and PtyStartupIngressIntent — the thing that
    actually crosses the client/host boundary — is untouched. A new client against an old host
    and an old client against a new host both keep working; per host, whoever owns the pty
    decides locally with what its own node-pty offers.
  • Windows / ConPTY — createPtySlaveEchoSyncProbe returns undefined on win32, and
    defersWrite() already returns early for windows-conpty before the fast path is reached.
    Entirely unaffected; src/unix/pty.cc is not even compiled there.

Measured result

main this PR
canonical harness leaked=true, childStdin "ESC]11;rgb:1e1e/1e1e/1e1e ESC\ hello\n" leaked=false, childStdin "hello\n", 4 consecutive runs
reply-order inversions present 0
max echo-safe defer 201-217 ms 0.1-0.2 ms
DA1 defer p90 102-172 ms under the rejected FIFO design 0 ms p50/p90/max
8 concurrent panes leaks 0 leaks 8/8, DA1 max 0 ms
#12112 (cooked querier) answered answered identically — the sync probe returns 'echoing' at raw-delays 5/50/150/250/500 ms, so the fast path never fires

It matches the pure-ordering ceiling (--bypass-echo-safe) exactly.

Linked Issue

Fixes #13892

Visual Proof

N/A — there is no UI change. The defect and the fix are both invisible on screen by
construction: the leaked bytes are consumed by a child process's stdin, which is exactly
why the regression test asserts on what a child process read rather than on what rendered.

Testing

Everything below is real output from this branch on macOS arm64 (darwin 25.3.0), fish 4.

  • npm_config_build_from_source=true pnpm rebuild node-pty — the patch applies and compiles:
    CXX(target) Release/obj.target/pty/src/unix/pty.o ... gyp info ok, with only node-pty's
    two pre-existing kevent -Wmissing-field-initializers warnings and none from the added
    code. The loaded binding exports [ 'fork', 'open', 'resize', 'process', 'echoState' ]
    from build/Release/.
  • npx tsc --noEmit -p config/tsconfig.node.json — clean.
  • npx tsc --noEmit -p config/tsconfig.tc.web.json — clean.
  • npx oxlint — no errors. node config/scripts/check-max-lines-ratchet.mjs — "max-lines
    ratchet OK — 347 grandfathered suppression(s), no new bypasses." No max-lines disable was
    added; pty-startup-ingress.ts was kept under its 300-line cap by collapsing a five-line
    onEmission({...}) object literal that fits on one line.
  • npx vitest run --config config/vitest.config.ts src/shared src/main/providers src/main/daemon src/relay — 698 files / 7916 tests passed. The one failure,
    src/relay/agent-exec-handler.test.ts (2 tests), reproduces identically on a clean stash
    of this branch
    : it asserts on a spawn env that this machine's ambient environment
    perturbs, and is unrelated to this change.
  • The prior decisions this touches, run specifically, all green:
    issue-12112-agent-pane-startup-color-reply-leak.repro.test.ts,
    src/shared/pty-startup-ingress.test.ts,
    src/shared/pty-startup-ingress-live-query-reply.test.ts, src/main/ipc/pty.test.ts,
    config/scripts/pr-workflow-parallelism.test.mjs — 549 tests passed. Existing node-pty
    contract suites (fish-color-scheme-child-stdin, omp-shell-wrapper, node-pty-fd-leak)
    — 20 passed. No existing test was edited to match new behavior.
  • node tests/tools/fish-query-reply-order/capture-reply-order-trace.mjs --json, 4 runs:
    {"leaked":false,"childStdin":"hello\n","inversions":0,"maxEchoSafeDeferMs":0.1-0.2}.

Tests added

  1. src/shared/pty-slave-line-discipline-echo.test.ts — the sync probe's mapping and every
    fail-open case: win32, missing method, non-function property, null/undefined pty,
    -1, undefined, and a throwing readEchoState, plus a live toggle read through the
    terminal.
  2. src/shared/pty-startup-reply-delivery.test.ts — answer() takes the fast path ONLY when
    the queue is empty AND the probe says 'quiet'; a non-empty queue still queues and the
    pair flushes in query order (the ordering property); 'echoing' / 'unknown' / no-probe
    defer exactly as before; the readline/BEL projection stays armed while the caret
    projection retires; ConPTY consults no probe; and a same-turn write reports its own
    failure instead of the deferred path's optimistic true.
  3. src/shared/fish-query-reply-child-stdin.node-pty.test.ts — real fish, real
    PtyStartupIngress / PtyStartupReplyDelivery / both probes, and
    local-pty-provider.write()'s gate verbatim; the child reads a full LINE (a leaked reply
    carries no newline, so a once('data') child would report it alone whenever it landed in
    its own read); itWithFish plus fishRequirementViolation so CI cannot go green by
    skipping. Proven to fail against pre-fix code: with the fast-path condition disabled
    it fails with expected 'CHILD-READ:"^[]11;rgb:1e1e/1e1e/1e1e^[\\hello\n"' to be 'CHILD-READ:"hello\n"' — the issue's exact payload; restored, it passes.
  4. src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts — the durable version of
    the slow-raw-querier harness, and the guard that killed drop-on-expiry: a querier that
    asks while COOKED and arms raw mode 50 ms and 250 ms later (the second outruns the 200 ms
    probe budget, so the deadline flush answers instead of the probe) must still receive its
    reply, and the sync probe must read 'echoing' at query time so the fast path is never
    eligible.

Review hardening (second commit)

A reviewer found two ways this fix could be switched off with the suite still green. Both
are now closed by tests only — no runtime behavior changed.

1. The production wiring was unguarded. Deleting the echoSyncProbe spread at every
site left 2391 files / 29962 tests passing, so the fix's only real-world delivery path could
be refactored away silently. Each of the four links now proves the BEHAVIOR the spread buys
rather than matching source text — given a pty whose readEchoState says quiet, the probe is
consulted and the reply reaches the pty inside the caller's own turn:

link guard deleting the spread
pty-subprocess.ts (builds the handle's probe) pty-subprocess.test.ts — "sync ECHO probe on the handle" expected undefined to be 'quiet'
session.ts new session-same-turn-query-reply-wiring.test.ts expected "vi.fn()" to be called at least once
local-pty-provider.ts local-pty-provider.test.ts — "same-turn query reply wiring" same
relay/pty-handler.ts pty-handler.test.ts — "same-turn query reply wiring" same

Each deletion was actually performed and the failure observed, then reverted. Each host also
keeps a negative case: an echoing verdict (and, for the daemon, no probe at all) still
defers, so the guard cannot be satisfied by writing unconditionally.

2. The vacuity guard could not detect a prebuilt binding. The JS half of the patch ships
in the pnpm patch, so createPtySlaveEchoSyncProbe returns a DEFINED probe even when the
loaded native module is the upstream prebuild — exports ['fork','open','resize','process'],
no echoState. readEchoState() then answers undefined, the probe maps it to 'unknown'
forever, the fast path never fires, and the old expect(probe).toBeDefined() saw nothing.

New src/shared/node-pty-echo-state-requirement.ts mirrors fish-binary-requirement.ts: it
inspects node-pty's native binding for a real echoState export, both node-pty suites now
require a DEFINITE 'quiet' | 'echoing' verdict off the live pty instead of a defined probe,
and an always-running requirement test fails when ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1. The
shell contracts lane sets it (along with ORCA_REQUIRE_FISH=1, whose comment already
promised a test-time re-check that was never actually wired), so CI fails loudly while a
developer with a stale node_modules gets a skip naming the remedy — and the remedy names
the flag, because plain pnpm rebuild node-pty finds the shipped darwin prebuild and
exits 0.

Verified by simulating the prebuild (stripping echoState from the loaded binding): without
the env var both suites report 3 passed | 3 skipped; with ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1
both fail with ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1 but the patched-node-pty tests would skip: the loaded node-pty native binding exports [fork, open, resize, process] and has no echoState.... Restored, both suites pass against real fish 4.7.1.

After the hardening commit, on the same machine: npx tsc --noEmit -p config/tsconfig.node.json clean; npx oxlint exit 0 with no new warnings;
node config/scripts/check-max-lines-ratchet.mjs "OK — 347 grandfathered suppression(s), no
new bypasses" (no max-lines disable added, and pty-startup-ingress.ts untouched);
npx vitest run --config config/vitest.config.ts src/shared src/main/providers src/main/daemon src/relay — 701 files / 7933 tests passed, 21 skipped, 0 failures (the
agent-exec-handler noise above is this machine's ambient GIT_CONFIG_COUNT; unsetting it
makes that file pass unchanged); config/scripts/pr-workflow-parallelism.test.mjs 12 passed.

The tests read no ambient process.env beyond PATH, which they pass explicitly into the
pty rather than mutating.

Platforms: macOS verified end to end. Linux is covered by the shell_contracts CI lane
(where both new node-pty suites are registered) and always builds node-pty from source, so
echoState is present there. Windows is unaffected by construction (win32 short-circuit,
defersWrite early return, and src/unix/pty.cc not compiled). SSH/relay, WSL and folder
workspaces are unaffected: the probe is built per-pty by whichever host owns it.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Written with Claude (Opus 5).

Review

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH,
Mobile, general backwards compatibility, performance.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)

Made with Orca 🐋

A startup/live color reply on a POSIX pty is deferred until an `stty`
subprocess proves the slave's ECHO bit is clear. Any deferral, however
short, lets a reply written later in the same turn overtake it — fish's
DA1 read sentinel is exactly that — so the held OSC 11 reply lands in the
NEXT child process's stdin (#13892).

Read the ECHO bit synchronously instead: POSIX redirects a master's mode
ioctls to the slave, so `tcgetattr` on the master fd Orca already owns
answers for the slave with no fork and no extra fd. When it says quiet and
nothing is already queued, the reply is written inside the query's turn.

Degrades to today's behavior on any host whose node-pty lacks the patch
(no method -> no probe), on Windows/ConPTY, and on `unknown`/`echoing`.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds native Unix PTY ECHO-state access through the patched node-pty binding. It introduces synchronous echo probes and passes them through daemon, local provider, relay, and startup ingress paths. Startup reply delivery can now write immediately when the PTY is synchronously quiet. New unit and integration tests cover echo states, cooked PTY replies, Fish child-stdin ordering, and reply failures. A Fish query-reply trace harness and dedicated workflow test routing were added.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR addresses POSIX reply leakage, preserves ordering and cooked-mode protections, and keeps Windows behavior unchanged [#13892].
Out of Scope Changes check ✅ Passed The native patch, wiring, tests, CI updates, and reproduction harness directly support the linked issue and stated fix.
Title check ✅ Passed The title clearly and concisely describes the primary same-turn terminal query reply fix.
Description check ✅ Passed The description covers the required sections, linked issue, rationale, testing, compatibility, visual proof, AI disclosure, and checklist.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

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: 3

Caution

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

⚠️ Outside diff range comments (2)
config/patches/[email protected] (2)

8-14: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Restore Spectre mitigation for the Windows native targets.

Lines 8-14 and Lines 54-71 remove SpectreMitigation: 'Spectre'. This weakens the security posture of the shipped PTY binaries. Keep the mitigation enabled. If the build toolchain lacks the required libraries, install the Visual Studio Spectre component in CI and release builds.

Also applies to: 54-71


40-50: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use an MSYS-safe cmd.exe invocation.

Line 41 and Line 50 invoke batch files with bare cmd /c. Git Bash can rewrite /c, which prevents these GYP commands from running. Use the MSYS-safe cmd.exe //d //c form for both commands.

As per coding guidelines: “Never launch a .cmd runner with bare cmd.exe /c from a Git Bash pane because MSYS rewrites /c.”

Source: Coding guidelines

🧹 Nitpick comments (4)
tests/tools/fish-query-reply-order/capture-reply-order-trace.mjs (3)

229-253: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Declare deferredByReply before the ingress that reads it.

The write callback at Line 232 reads deferredByReply, but the const is declared at Line 253, after the PtyStartupIngress construction. The callback works today only because PtyStartupIngress does not invoke write during its constructor. If the constructor ever flushes a pending reply, this hits the temporal dead zone and throws ReferenceError.

Move the declaration above the ingress.

♻️ Proposed change
+/** Reply text -> records awaiting the delivery flush, so the trace can pair them up. */
+const deferredByReply = new Map()
+
 // FIFO model: an immediate reply may not overtake an echo-safe reply queued ahead of it.
 const fifo = { deferred: 0, held: [] }
@@
 })
 
-/** Reply text -> records awaiting the delivery flush, so the trace can pair them up. */
-const deferredByReply = new Map()
-
 // VERBATIM from local-pty-provider.write() (src/main/providers/local-pty-provider.ts ~:1082).

94-94: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Resolve the default fish path instead of hardcoding the Homebrew location.

/opt/homebrew/bin/fish exists only on Apple Silicon with Homebrew. On Linux and on Intel macOS the harness fails until the operator passes --shell. The repository already has resolveFishBinary in src/shared/fish-binary-requirement, which the sibling test imports.

Use that resolver as the default, and keep --shell as the override.


424-425: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Return a non-zero exit code when the run does not reach its markers.

waitFor logs TIMEOUT and returns false at Line 425, but the return value is discarded. Line 511 then exits 0 unconditionally. A run in which fish never printed a prompt reports success. If anyone wires this harness into a script, the failure is silent.

Track the timeout results and exit non-zero when a required marker never appeared.

Also applies to: 511-511

src/shared/pty-startup-reply-delivery.test.ts (1)

54-60: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Close each deferred delivery at the end of the loop iteration.

answer() arms a write timer, and close() clears it.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d83d26a4-4a46-4e00-b66a-7b8577400fe6

📥 Commits

Reviewing files that changed from the base of the PR and between 36d45af and fa0be93.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (16)
  • .github/workflows/pr.yml
  • config/patches/[email protected]
  • config/scripts/pr-workflow-parallelism.test.mjs
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/session.ts
  • src/main/providers/local-pty-provider.ts
  • src/relay/pty-handler.ts
  • src/shared/fish-query-reply-child-stdin.node-pty.test.ts
  • src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts
  • src/shared/pty-slave-line-discipline-echo.test.ts
  • src/shared/pty-slave-line-discipline-echo.ts
  • src/shared/pty-startup-ingress-contract.ts
  • src/shared/pty-startup-ingress.ts
  • src/shared/pty-startup-reply-delivery.test.ts
  • src/shared/pty-startup-reply-delivery.ts
  • tests/tools/fish-query-reply-order/capture-reply-order-trace.mjs

Comment on lines +18 to +20
'src/main/pty/omp-shell-wrapper.node-pty.test.ts',
'src/shared/fish-query-reply-child-stdin.node-pty.test.ts',
'src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts'

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Show the full list and how it is asserted, then compare against the workflow job.
rg -n -B 10 -A 40 'patchedNodePtyContractFiles' config/scripts/pr-workflow-parallelism.test.mjs
rg -n 'node-pty.test.ts' .github/workflows/pr.yml

Repository: stablyai/orca

Length of output: 3786


🏁 Script executed:

#!/bin/bash
sed -n '55,95p' config/scripts/pr-workflow-parallelism.test.mjs
sed -n '220,295p' .github/workflows/pr.yml
rg -n -B 5 -A 8 'node-pty-fd-leak|fish-color-scheme-child-stdin' config/scripts .github/workflows src tests

Repository: stablyai/orca

Length of output: 11111


Add src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts to patchedNodePtyContractFiles. The file runs in shell_contracts and is excluded from the general shards, but the contract test does not assert either relationship for this file.

Source: Learnings

Comment on lines +40 to +43
{
re: /^\x1b\]1[012];\?(\x07|\x1b\\)/,
reply: (m: RegExpExecArray) => `\x1b]11;rgb:1e1e/1e1e/1e1e${m[1]}`
},

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

Reply with the OSC index that was queried.

The pattern matches OSC 10, 11, and 12, but the reply always uses index 11 and the background color value. An OSC 10 query therefore receives a background-color answer, and an OSC 12 query receives an answer for a different parameter. fish can treat that as an unmatched reply, which weakens the ordering evidence this test collects. tests/tools/fish-query-reply-order/capture-reply-order-trace.mjs keeps OSC10, OSC11, and OSC12 as separate grammars with matching indices.

Echo the captured index back.

🔧 Proposed fix
   {
-    re: /^\x1b\]1[012];\?(\x07|\x1b\\)/,
-    reply: (m: RegExpExecArray) => `\x1b]11;rgb:1e1e/1e1e/1e1e${m[1]}`
+    re: /^\x1b\](1[012]);\?(\x07|\x1b\\)/,
+    reply: (m: RegExpExecArray) =>
+      m[1] === '11' ? `\x1b]11;rgb:1e1e/1e1e/1e1e${m[2]}` : `\x1b]${m[1]};rgb:ffff/ffff/ffff${m[2]}`
   },
📝 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
{
re: /^\x1b\]1[012];\?(\x07|\x1b\\)/,
reply: (m: RegExpExecArray) => `\x1b]11;rgb:1e1e/1e1e/1e1e${m[1]}`
},
{
re: /^\x1b\](1[012]);\?(\x07|\x1b\\)/,
reply: (m: RegExpExecArray) =>
m[1] === '11' ? `\x1b]11;rgb:1e1e/1e1e/1e1e${m[2]}` : `\x1b]${m[1]};rgb:ffff/ffff/ffff${m[2]}`
},

Comment on lines +98 to +108
onEmission: (emission) => {
rendered += emission.data
if (!emission.data.includes(OSC11_QUERY)) {
return
}
verdictsAtQuery.push(echoSyncProbe?.() ?? 'unknown')
// The host gate, verbatim from local-pty-provider.write().
if (extractOnlyCookedEchoSafeQueryReplies(OSC11_REPLY)) {
ingress.answerLiveQueryReply(OSC11_REPLY)
}
},

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 | 🟡 Minor | ⚡ Quick win

Match the query against an accumulated buffer, not a single emission.

emission.data.includes(OSC11_QUERY) requires all 8 bytes of \x1b]11;?\x07 to arrive in one emission. A pty read can split that sequence across two emissions. If the split happens, the reply is never written, verdictsAtQuery stays empty, and the test fails after the 15s wait. The sibling test in src/shared/fish-query-reply-child-stdin.node-pty.test.ts carries a tail for exactly this reason.

Match against the accumulated rendered buffer and answer once.

🔧 Proposed fix
         let rendered = ''
+        let answered = false
         const verdictsAtQuery: PtySlaveLineDisciplineEcho[] = []
         const ingress = new PtyStartupIngress({
           ownerBackend: 'posix-pty',
           write: (data) => term.write(data),
           onEmission: (emission) => {
             rendered += emission.data
-            if (!emission.data.includes(OSC11_QUERY)) {
+            if (answered || !rendered.includes(OSC11_QUERY)) {
               return
             }
+            answered = true
             verdictsAtQuery.push(echoSyncProbe?.() ?? 'unknown')
📝 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
onEmission: (emission) => {
rendered += emission.data
if (!emission.data.includes(OSC11_QUERY)) {
return
}
verdictsAtQuery.push(echoSyncProbe?.() ?? 'unknown')
// The host gate, verbatim from local-pty-provider.write().
if (extractOnlyCookedEchoSafeQueryReplies(OSC11_REPLY)) {
ingress.answerLiveQueryReply(OSC11_REPLY)
}
},
let rendered = ''
let answered = false
const verdictsAtQuery: PtySlaveLineDisciplineEcho[] = []
const ingress = new PtyStartupIngress({
ownerBackend: 'posix-pty',
write: (data) => term.write(data),
onEmission: (emission) => {
rendered += emission.data
if (answered || !rendered.includes(OSC11_QUERY)) {
return
}
answered = true
verdictsAtQuery.push(echoSyncProbe?.() ?? 'unknown')
// The host gate, verbatim from local-pty-provider.write().
if (extractOnlyCookedEchoSafeQueryReplies(OSC11_REPLY)) {
ingress.answerLiveQueryReply(OSC11_REPLY)
}
},

…ding

Two ways the #13892 fix could be off with the suite still green.

The probe reaches production through four spreads — pty-subprocess's handle,
session.ts, local-pty-provider.ts and the relay's pty-handler — and deleting
any of them left 29962 tests passing. Each host now proves the behavior the
spread buys: with a pty whose readEchoState says quiet, the probe is consulted
and the reply reaches the pty inside the caller's own turn; an `echoing`
verdict, or no probe at all, still defers.

The other way is a stale node_modules: the JS half of the patch ships in the
pnpm patch, so createPtySlaveEchoSyncProbe hands back a probe even when the
loaded native binding is the upstream prebuild with no `echoState`. Every
verdict is then 'unknown', the fast path never fires, and the old
`toBeDefined()` vacuity guard saw nothing. The node-pty suites now require a
definite live verdict and, mirroring ORCA_REQUIRE_FISH, skip with the
source-build remedy locally while ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1 fails the
shell-contracts lane. That remedy names the flag, because plain
`pnpm rebuild node-pty` finds the darwin prebuild and exits 0.

Co-authored-by: Orca <[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.

🧹 Nitpick comments (1)
src/main/daemon/session-same-turn-query-reply-wiring.test.ts (1)

1-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce the module comments.

Keep one short sentence for the non-obvious invariant.

  • src/main/daemon/session-same-turn-query-reply-wiring.test.ts#L1-L13: State that the test guards #13892 ECHO-probe wiring.
  • src/shared/node-pty-echo-state-requirement.ts#L1-L12: State that native echoState exports must be verified.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9122f674-7f39-44b0-b7c9-ba716bcbb961

📥 Commits

Reviewing files that changed from the base of the PR and between fa0be93 and 17010ec.

📒 Files selected for processing (9)
  • .github/workflows/pr.yml
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/session-same-turn-query-reply-wiring.test.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/relay/pty-handler.test.ts
  • src/shared/fish-query-reply-child-stdin.node-pty.test.ts
  • src/shared/node-pty-echo-state-requirement.test.ts
  • src/shared/node-pty-echo-state-requirement.ts
  • src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/shared/fish-query-reply-child-stdin.node-pty.test.ts
  • .github/workflows/pr.yml

@brennanb2025

Copy link
Copy Markdown
Contributor

Superseded by #14609. I rebuilt this from current main, retained @nwparker’s synchronous echo-state design with attribution, and added upstream SSH/remote-runtime ordering plus real Linux fish coverage. Leaving this PR open for history.

williamfligor added a commit to williamfligor/orca that referenced this pull request Aug 15, 2026
Upstream stablyai#13904 (between fork base and PR stablyai#13998 base) introduced this
self-contained test helper; stablyai#13998's node-pty tests import it. Pull the two
files directly so the cherry-picked PR compiles without dragging in stablyai#13904.
@nwparker

Copy link
Copy Markdown
Contributor Author

Current-main audit (2026-09-19): this fix still has strong historical proof and green CI on its original base, but it is not review-ready against today’s main. A clean rebase stops on conflicts in the workflow registration, node-pty patch, daemon/session/provider/relay wiring, and shared reply-delivery contracts. I left the branch unchanged and am keeping #13892 open rather than treating stale CI as current verification. Merge risk is medium until the native patch and all four host wiring paths are rebased and the real fish/OMP ordering smoke is rerun.

@nwparker

Copy link
Copy Markdown
Contributor Author

Superseded by the merged current-main query-reply ordering fixes; the related issues #13892 and #13908 are closed with current regression proof.

@nwparker nwparker closed this Sep 19, 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.

[Bug]: OSC/DSR query replies are reordered behind CPR/DA1 by the POSIX echo-safe write path, stranding them into the next child's stdin

2 participants