Skip to content

fix(terminal): preserve startup query reply order (STA-3948) - #14609

Closed
brennanb2025 wants to merge 1 commit into
mainfrom
brennan/sta-3948-terminal-query-order
Closed

brennanb2025 wants to merge 1 commit into
mainfrom
brennan/sta-3948-terminal-query-order

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

ELI5

Some shells ask the terminal questions while they start. Orca could delay an early OSC answer while keyboard echo was active, let a later DA1 answer pass it, and then deliver the delayed bytes to the next child process as if the user had typed them. This change answers immediately when the kernel proves echo is quiet and otherwise keeps every later query reply behind the earlier delayed one.

What Changed

  • Preserve query-reply order across local PTYs, daemon sessions, relay/SSH hosts, and the remote renderer transport.
  • Add a synchronous native echoState probe to node-pty so safe replies can be delivered in the same turn.
  • Send renderer and remote-runtime query replies atomically and retain ordering through debounce, async validation, and viewport-claim buffering.
  • Bound host, renderer, and remote viewport reply storage to 64 entries.
  • Add native fish, cooked-query, wiring, mixed-version, bounded-queue, and real Docker/OpenSSH regression coverage.
  • Retain @nwparker's synchronous echo-state design and authorship credit while rebuilding the fix from current main.

This focused maintainer PR supersedes #13998.

Why

The bug is ordering, not only timing: once an OSC/private DSR reply is deferred, DA1/CPR replies must not overtake it. Moving the kernel echo check into the same native call turn closes the local race, while an ordered fallback protects upstream SSH hosts that cannot expose the synchronous probe.

There is no wire-format change. Patched native hosts use the synchronous probe; older or unpatched SSH hosts preserve reply order but may retain the existing bounded 200 ms fallback. Windows ConPTY is unaffected. Modified-F3/CPR ambiguity shares the same bounded reply budget.

Linked Issue

Fixes #13892

Linear: STA-3948

Visual Proof

N/A — this changes terminal input routing and has no visible UI or layout change. Contextual Linux SSH/fish validation:

linux-ssh-fish-child-stdin-pass.png

Testing

  • I manually tested these changes locally
  • Automated tests added/updated
  • pnpm lint (LINT_OK)
  • pnpm typecheck (TYPECHECK_OK)
  • Reliability manifest: 82 gates
  • Affected Vitest suite: 729 files passed, 6 skipped; 8,483 tests passed, 24 skipped
  • Native fish/cooked-query tests: 6/6 passed with zero required skips
  • Cross-version wire compatibility: 5/5 passed
  • Electron/Playwright Docker OpenSSH: 2/2 passed in 36.9s
  • Linux ARM64 fish 4.8.1 child read exactly "hello\n"; the relay node-pty did not expose echoState
  • Performance: 100,000 synchronous tcgetattr reads measured approximately 0.25–0.324 μs/read

Review

Reviewed for native/local/daemon/SSH/remote-runtime behavior, folder workspaces, mixed-version compatibility, Windows/ConPTY degradation, bounded storage, query-reply atomicity and ordering, security, and performance. Two independent reviewers returned CLEAN on the exact final head.

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 (lint, typecheck, affected tests, and SSH E2E pass locally; CI covers the full matrix)

Author

  • X / Twitter: @BrennanKB5

Answer cooked-mode terminal queries in the originating turn when the native PTY can prove echo is quiet, and hold later query-only replies behind deferred replies on upstream SSH relays. Keep renderer replies atomic and bound both renderer and host-side queues with local, daemon, relay, native, and Docker SSH fish regression coverage.

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

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds patched node-pty ECHO-state support and shared capability checks. PTY startup reply delivery now supports immediate quiet-state writes and ordered deferred replies. Daemon, local, relay, and remote-runtime paths preserve query-reply boundaries and input ordering with bounded buffering. New tests cover native support, PTY wiring, terminal replies, fish handoffs, SSH relays, and CI reliability gates.

Merge Risk: 🟠 High · up to fc7f3

This PR changes terminal startup query-reply ordering and native PTY handling, but the current head removes Spectre mitigation from Windows native builds and leaves new same-turn tests unguarded where the synchronous probe is unavailable, creating security exposure and Windows validation risk. Merge should be blocked until the mitigation is restored and the tests are POSIX-gated.

🚥 Pre-merge checks | ✅ 4 | ❌ 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%. 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 summarizes the primary change: preserving terminal startup query-reply order.
Description check ✅ Passed The description covers the required sections, explains the change and rationale, and documents testing and compatibility considerations.
Linked Issues check ✅ Passed The changes implement FIFO query-reply ordering, synchronous echo-state detection, cross-path wiring, and regression coverage required by issue #13892.
Out of Scope Changes check ✅ Passed The native, renderer, remote-runtime, reliability, and SSH test changes directly support the linked issue and stated objectives.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • 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: 5

Caution

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

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

9-11: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Retain Spectre mitigation for Windows native builds.

The patch removes SpectreMitigation: 'Spectre' from binding.gyp and both winpty targets. No /Qspectre or equivalent setting replaces it. Restore the mitigation and provision the matching Spectre-mitigated MSVC libraries in Windows build environments.

🧹 Nitpick comments (2)
src/shared/pty-startup-reply-delivery.ts (1)

4-12: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the explanatory comments.

Keep the safety invariant. Remove the detailed incident narrative and repeated mechanics. One brief rationale per path is sufficient.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Also applies to: 210-215

Source: Coding guidelines

src/shared/fish-query-reply-child-stdin.node-pty.test.ts (1)

217-245: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Wait for the OSC query instead of using a fixed handoff delay.

Replace sleep(1_500) with a bounded waitUntil(() => oscQueryCount > oscQueriesBeforeHandoff, ...). The reliability gate tracks the related SSH oracle, not this test file; its flake status remains unknown, with no CI or soak data.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 355de8ac-12a1-4554-ac9d-abc64d401b5f

📥 Commits

Reviewing files that changed from the base of the PR and between 9bb8836 and fc7f372.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (34)
  • .github/workflows/pr.yml
  • config/patches/[email protected]
  • config/reliability-gates.jsonc
  • config/scripts/pr-workflow-parallelism.test.mjs
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/session-same-turn-query-reply-wiring.test.ts
  • src/main/daemon/session.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/relay/pty-handler.test.ts
  • src/relay/pty-handler.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue.test.ts
  • src/renderer/src/components/terminal-pane/pty-input-write-queue.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-batching.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-batching.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.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
  • 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-live-query-reply.test.ts
  • src/shared/pty-startup-ingress.ts
  • src/shared/pty-startup-reply-delivery.test.ts
  • src/shared/pty-startup-reply-delivery.ts
  • src/shared/terminal-query-reply-delivery.ts
  • src/shared/terminal-query-reply.test.ts
  • src/shared/terminal-query-reply.ts
  • tests/e2e/pty-input-write-queue-ssh.spec.ts

Comment on lines 9917 to 9923
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-input-write-queue.test.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts src/shared/terminal-query-reply.test.ts src/shared/pty-startup-ingress-live-query-reply.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-batching.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts",
"pnpm exec vitest run --config config/vitest.config.ts src/shared/pty-startup-reply-delivery.test.ts",
"pnpm exec playwright test tests/e2e/terminal-osc-color-queries.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
"pnpm exec playwright test tests/e2e/terminal-typing-latency.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
"ORCA_E2E_SSH_DOCKER=1 pnpm exec playwright test tests/e2e/pty-input-write-queue-ssh.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Two new commands have no corresponding evidenceRuns entry.

The commands array adds two vitest invocations at lines 9918-9919: one covering remote-runtime-pty-batching.test.ts, remote-runtime-pty-query-reply-immediate.test.ts, and remote-runtime-pty-transport.test.ts, and one covering src/shared/pty-startup-reply-delivery.test.ts. Both commands have matching testFiles entries and assertionRefs (lines 9927-9932, 9958-9976, 9989-9994). Neither command has a matching entry in evidenceRuns (lines 10015-10061).

This file exists to record proof that each declared command actually ran and passed. Without an evidenceRuns entry, a reader cannot confirm these two commands were executed, even though the gate's flakeHistory and redGreenEvidence narratives describe broader validation.

Add an evidenceRuns entry for each of the two commands, or remove them from commands until evidence exists.

Also applies to: 9927-9932, 9958-9976, 9989-9994, 10015-10061

Comment on lines +10052 to 10060
{
"date": "2026-08-14",
"runner": "local",
"platform": "macos",
"command": "ORCA_E2E_SSH_DOCKER=1 pnpm exec playwright test tests/e2e/pty-input-write-queue-ssh.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
"result": "passed",
"durationSeconds": 36.9,
"summary": "Run with SKIP_BUILD=1 against the existing e2e bundle. Both Docker OpenSSH Electron tests passed: the live OSC query returned its RGB reply, and an upstream-node-pty Linux ARM64 relay without echoState kept OSC/DA1 bytes out of the next fish 4.8.1 child's stdin."
}

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

The recorded command does not match the summary's description of how it ran.

The command field at line 10056 is:

ORCA_E2E_SSH_DOCKER=1 pnpm exec playwright test tests/e2e/pty-input-write-queue-ssh.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1

The summary field at line 10059 states: "Run with SKIP_BUILD=1 against the existing e2e bundle." SKIP_BUILD=1 does not appear in the recorded command.

A reader who reruns the exact recorded command will perform a full build, not reuse the existing bundle as the summary claims. Add SKIP_BUILD=1 to the command string, or correct the summary to match the command that was actually recorded.

📝 Proposed fix
-          "command": "ORCA_E2E_SSH_DOCKER=1 pnpm exec playwright test tests/e2e/pty-input-write-queue-ssh.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
+          "command": "ORCA_E2E_SSH_DOCKER=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/pty-input-write-queue-ssh.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
📝 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
{
"date": "2026-08-14",
"runner": "local",
"platform": "macos",
"command": "ORCA_E2E_SSH_DOCKER=1 pnpm exec playwright test tests/e2e/pty-input-write-queue-ssh.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
"result": "passed",
"durationSeconds": 36.9,
"summary": "Run with SKIP_BUILD=1 against the existing e2e bundle. Both Docker OpenSSH Electron tests passed: the live OSC query returned its RGB reply, and an upstream-node-pty Linux ARM64 relay without echoState kept OSC/DA1 bytes out of the next fish 4.8.1 child's stdin."
}
{
"date": "2026-08-14",
"runner": "local",
"platform": "macos",
"command": "ORCA_E2E_SSH_DOCKER=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/pty-input-write-queue-ssh.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
"result": "passed",
"durationSeconds": 36.9,
"summary": "Run with SKIP_BUILD=1 against the existing e2e bundle. Both Docker OpenSSH Electron tests passed: the live OSC query returned its RGB reply, and an upstream-node-pty Linux ARM64 relay without echoState kept OSC/DA1 bytes out of the next fish 4.8.1 child's stdin."
}

Comment on lines +2294 to +2335

// Wiring guard for #13892; see session-same-turn-query-reply-wiring.test.ts for why
// this is asserted per host rather than once on PtyStartupIngress.
describe('same-turn query reply wiring', () => {
const OSC11_REPLY = '\x1b]11;rgb:1e1e/1e1e/1e1e\x07'

it('hands the pty’s sync ECHO probe to the startup ingress', async () => {
const write = vi.fn()
const readEchoState = vi.fn(() => 0)
spawnMock.mockReturnValueOnce({ ...mockProc, write, readEchoState })
const { id } = await provider.spawn({ cols: 80, rows: 24 })

provider.write(id, OSC11_REPLY)

// Both matter: the probe must be CONSULTED, and a `quiet` verdict must reach the
// pty in this turn rather than behind the deferral timer.
expect(readEchoState).toHaveBeenCalled()
expect(write).toHaveBeenCalledWith(OSC11_REPLY)
})

it('still defers the reply when the pty reports the slave would echo', async () => {
const write = vi.fn()
spawnMock.mockReturnValueOnce({ ...mockProc, write, readEchoState: () => 1 })
const { id } = await provider.spawn({ cols: 80, rows: 24 })

provider.write(id, OSC11_REPLY)

expect(write).not.toHaveBeenCalled()
})

it('does not let DA1 overtake a held OSC reply', async () => {
const da1 = '\x1b[?1;2c'
const write = vi.fn()
spawnMock.mockReturnValueOnce({ ...mockProc, write, readEchoState: () => 1 })
const { id } = await provider.spawn({ cols: 80, rows: 24 })

provider.write(id, OSC11_REPLY)
provider.write(id, da1)

expect(write).not.toHaveBeenCalled()
})
})

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 | 🟠 Major | ⚡ Quick win

The new same-turn query reply wiring suites run unguarded on Windows. createPtySlaveEchoSyncProbe returns undefined when platform === 'win32', so neither host installs an echoSyncProbe on a Windows runner. In both suites the first test fails, because readEchoState is never called and the reply is deferred. The remaining tests pass vacuously and stop guarding the deferral behavior. The sibling suites already gate this: src/main/daemon/pty-subprocess.test.ts uses itOnPosixHost, and src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts uses itOnPosix.

  • src/main/providers/local-pty-provider.test.ts#L2294-L2335: declare a POSIX gate in the same-turn query reply wiring block and apply it to all three it( calls, unless the suite already pins process.platform to a POSIX value.
  • src/relay/pty-handler.test.ts#L3930-L3971: apply the identical POSIX gate to all three it( calls in the matching block.

As per coding guidelines, "commands and scripts must work on macOS, Linux, and Windows".

📍 Affects 2 files
  • src/main/providers/local-pty-provider.test.ts#L2294-L2335 (this comment)
  • src/relay/pty-handler.test.ts#L3930-L3971

Source: Coding guidelines

Comment on lines +146 to +157
})

const echoProbe = createPtySlaveEchoProbe(readPtySlavePath(term))
const echoSyncProbe = createPtySlaveEchoSyncProbe(term)
// Vacuity guard: a DEFINED probe proves nothing — the JS patch alone yields one that
// answers 'unknown' forever. Only a definite verdict off this live pty proves the
// native echoState is really being read, and so that there is a fast path to regress.
expect(
echoSyncProbe?.(),
`the sync probe gave no definite verdict, so #13892's same-turn reply is off. ${NODE_PTY_SOURCE_BUILD_HINT}`
).toMatch(/^(quiet|echoing)$/)

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

🧩 Analysis chain

🌐 Web query:

Vitest onTestFinished hook availability and version

💡 Result:

The onTestFinished hook is an available and officially supported feature in Vitest for cleaning up state after a test has finished running [1][2]. It is called after afterEach hooks and is not affected by the sequence.hooks configuration option [1][2]. You can use onTestFinished in two primary ways: 1. As a global import from vitest: import { onTestFinished, test } from 'vitest'; test('example', => { onTestFinished( => { /* cleanup logic / }); }); 2. From the test context (recommended for concurrent tests): When running tests concurrently, it is best practice to use the hook provided by the test context because Vitest does not track concurrent tests in global hooks [1][2]. import { test } from 'vitest'; test.concurrent('concurrent example', ({ onTestFinished }) => { onTestFinished( => { / cleanup logic */ }); }); The hook is available in current versions of Vitest, including v4.x [2][3][4]. It is designed to ensure cleanup code runs even if a test assertion fails, making it a reliable way to manage resources like database connections or mock restorations [1][2].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- candidate files ---'
git ls-files | rg '(^|/)(package\.json|pnpm-lock\.yaml|yarn\.lock|package-lock\.json|src/shared/fish-query-reply-child-stdin\.node-pty\.test\.ts)$'
printf '%s\n' '--- Vitest declarations and versions ---'
rg -n '"vitest"|vitest@|onTestFinished' package.json package-lock.json pnpm-lock.yaml yarn.lock 2>/dev/null || true
printf '%s\n' '--- test imports and cleanup context ---'
sed -n '1,280p' src/shared/fish-query-reply-child-stdin.node-pty.test.ts

Repository: stablyai/orca

Length of output: 10643


🌐 Web query:

Vitest v4.1.5 onTestFinished API hooks

💡 Result:

In Vitest v4.1.5, the onTestFinished API hook is a powerful tool designed to perform cleanup tasks after a test has completed, regardless of whether it passed or failed [1][2]. Key details for using onTestFinished: Usage: It is called during test execution to register a cleanup function [1][3]. This is particularly useful for managing resources—such as closing database connections or cleaning up temporary files—where you want the cleanup logic to remain close to the resource's initialization [1][3]. Concurrent Tests: When running tests concurrently, you must use the version of onTestFinished provided via the test context to ensure it correctly associates the cleanup logic with the specific test being executed [1][4][5]. Example: test.concurrent('performs a task', ({ onTestFinished }) => { const resource = setupResource; onTestFinished( => resource.cleanup); //... test code }); Behavior: 1. Execution Order: This hook runs after all afterEach hooks [1][4]. 2. LIFO Order: Multiple onTestFinished hooks are executed in reverse order of their registration (Last-In, First-Out) [1][2]. 3. Independence: Its execution is not affected by the sequence.hooks configuration option [1][4]. 4. Limitations: The hook is not called if a test is skipped using a dynamic ctx.skip call [2]. Comparison to Spies: It is considered best practice to use onTestFinished for cleaning up spies (e.g., spy.mockClear) rather than relying on standard afterEach blocks, as onTestFinished is guaranteed to run even if an assertion within the test fails [1][4].

Citations:


Register PTY cleanup before the vacuity assertion. Import onTestFinished from vitest and register term.kill() immediately after nodePty.spawn; otherwise an assertion failure before try leaves fish running.

Comment on lines +125 to +129
// 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.

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Verify the host write gate shape and remaining users of the echo-safe extractor.
set -euo pipefail

echo '== current host write gates =='
ast-grep run --pattern 'answerLiveQueryReply($$$)' --lang typescript src

echo '== remaining references to the extractor =='
rg -n -C 3 'extractOnlyCookedEchoSafeQueryReplies' src

Repository: stablyai/orca

Length of output: 182


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== target test imports and query-reply section =='
sed -n '1,45p;105,140p' src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts

echo '== provider write implementation =='
rg -n -C 12 'answerLiveQueryReply|extractOnlyCookedEchoSafeQueryReplies' src/main/providers/local-pty-provider.ts

echo '== all extractor references =='
rg -n -C 3 'extractOnlyCookedEchoSafeQueryReplies' src || true

echo '== all answerLiveQueryReply references =='
rg -n -C 5 'answerLiveQueryReply' src || true

Repository: stablyai/orca

Length of output: 31892


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== ingress delivery semantics =='
sed -n '1,190p' src/shared/pty-startup-ingress.ts
rg -n -C 12 'function deliverTerminalQueryReplyPayload|const deliverTerminalQueryReplyPayload|deliverTerminalQueryReplyPayload' src/shared

echo '== relevant test assertions and cleanup =='
sed -n '140,240p' src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts

echo '== structural comparison of production and test host-write shapes =='
python3 - <<'PY'
from pathlib import Path
provider = Path('src/main/providers/local-pty-provider.ts').read_text()
test = Path('src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts').read_text()
for name, text, needles in [
    ('provider', provider, ['answerLiveQueryReply(data)', 'ptyProcesses.get(id)?.write(data)']),
    ('test', test, ['extractOnlyCookedEchoSafeQueryReplies(OSC11_REPLY)', 'answerLiveQueryReply(OSC11_REPLY)']),
]:
    print(name)
    for needle in needles:
        print(f'  {needle!r}: {text.count(needle)}')
PY

Repository: stablyai/orca

Length of output: 12523


Align the test with the production reply path

Call ingress.answerLiveQueryReply(OSC11_REPLY) directly, remove the stale “verbatim” comment, and delete the unused extractOnlyCookedEchoSafeQueryReplies import. PtyStartupIngress now performs the reply classification.

@nwparker

Copy link
Copy Markdown
Contributor

Closing in favour of #15567, which carries this work forward.

That PR is this branch rebased onto main and reconciled with #15559 (a narrower ordering fix that landed in the meantime), with three defects fixed and regression tests added for each:

  1. Reply routing is now all-or-nothing. answerInOrder took ownership even with nothing to order behind, so Session.write returned before reaching the post-ready flush gate. A CPR answered during shell startup landed ahead of the buffered startup command and the shell ran the spliced remainder — 4;1Recho ... — so the agent never launched.
  2. Patch/lockfile integrity, plus a restored lint-staged entry that the rebase had dropped.
  3. Coverage gaps — the mid-probe re-arm guard, and a live-PTY assertion that the native probe really observes a quiet slave, so a kernel that does not redirect master mode ioctls fails loudly instead of leaving the fast path inert.

The approach here was the right one and is unchanged: the stty fork is what made the write async, and async is what reorders replies. Two things this branch asserted are now proven rather than assumed — the Linux master→slave termios redirect (verified on a real pty in a container), and the glibc floor (tcgetattr needs only GLIBC_2.2.5). The shell contracts lane passes with ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1.

Your commit is preserved with its Co-authored-by trailer.

@nwparker nwparker closed this Aug 20, 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