Skip to content

fix(pty): answer a terminal colour query in its own turn - #15567

Closed
nwparker wants to merge 2 commits into
mainfrom
nwparker/sync-echo-state-query-order
Closed

nwparker wants to merge 2 commits into
mainfrom
nwparker/sync-echo-state-query-order

Conversation

@nwparker

@nwparker nwparker commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1407 $\color{#cf222e}{\Huge{\mathbf{−}}}$​40 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1367
Prod 25 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​706 $\color{#cf222e}{\Huge{\mathbf{−}}}$​312 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​394

Root-cause follow-up to #15559.

Supersedes #14609 (STA-3948, @brennanb2025). This is that branch rebased onto main and reconciled with #15559, which landed in the meantime, plus fixes for three defects found in review. #14609 is closed in favour of this PR; the original commit is preserved with its Co-authored-by trailer.

What this actually fixes (corrected)

#15559 is what makes reply ordering correct, not this PR. Its cross-call FIFO holds a CPR behind a still-deferred colour reply, and that holds regardless of how long the deferral lasts — verified by running the ordering scenario with the sync probe absent (an unpatched host), where OSC → CPR is still preserved.

What this PR removes is the deferral itself, and with it two things the FIFO cannot address:

  • Timeout exposure. Withholding a reply for up to 200 ms can exceed a querying program's read window. The program gives up and the reply lands late in its stdin — the same failure as the original bug, reached by timeout instead of reorder.
  • Cost. A subprocess fork per probe (2403 µs), replaced by a syscall (0.26 µs).

So: a latency and robustness fix that deletes the mechanism which produced the ordering bug, not the ordering fix itself.

Why the deferral existed

Orca answers terminal queries by writing to the PTY master, which a line discipline in ECHO copies straight back out as junk on a cooked prompt (#12112). The guard was to withhold the write until an stty subprocess proved ECHO clear — and forking is what forced the decision to be asynchronous.

That async hop is the bug. Any deferral, however short, lets a reply written later in the same turn overtake the held one. #15559 stopped a CPR jumping the queue, but left the deferral — and the latency and fork cost — in place.

The root-cause fix

Read the bit synchronously. Linux and the BSDs redirect a master's mode ioctls to the slave, so tcgetattr on the master fd node-pty already owns answers for the slave with no fork:

cost
stty subprocess (before) 2403 µs
tcgetattr on master (after) 0.26 µs

With a verdict available inline, a program that already cleared ECHO — every raw-mode prober, including the colour probe behind the gh auth login report — is answered in its own turn and can never be reordered.

The deferral stays for the genuinely cooked case, and #15559's ordering guarantee stays underneath it: hosts whose node-pty predates this patch get no sync probe and fall back to the deferred path, which mixed client/host versions make a live production path.

Fail-safe by construction

Every non-ideal outcome degrades toward the old behaviour, never toward a false "quiet":

  • tcgetattr fails → -1 → unknown → deferred path.
  • A kernel that did not redirect answers from the master's own termios, whose ECHO defaults set → echoing → deferred path.
  • Unpatched node-pty → no probe at all → deferred path.

Verification

  • Linux redirect proven, not assumed — a C program on a real pty in a container: master tracks the slave's ECHO live through raw/cooked transitions, a fresh master reports ECHO set, an invalid fd returns -1. tcgetattr needs only GLIBC_2.2.5, far below the 2.31 floor, so no new glibc surface.
  • Clean room: pnpm install --frozen-lockfile --ignore-scripts from a cold store (0 reused / 1280 downloaded) applies the patch, and a from-source rebuild exports echoState.
  • Live PTY: the binding tracks stty -echo / stty echo in real time.
  • End-to-end: a faithful reimplementation of the prober's protocol — pre-fix leaves \x1b]11;rgb:... in the next program's stdin; post-fix stdin is clean.
  • 34,125 tests pass; typecheck, oxlint, max-lines ratchet and the reliability-gate manifest are clean.

Guards against silent inertness

The JS half of the patch ships in the pnpm patch while the native half needs a source build, so readEchoState exists the moment node_modules is patched even when the loaded binding is an upstream prebuild without echoState — a test that only checked "does the probe exist" would pass with the fix switched off. ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1 makes CI fail rather than skip. A live-PTY test additionally asserts the probe really observes a quiet slave, so a kernel that does not redirect fails loudly instead of leaving the fast path inert.

Review-driven changes to the rebased branch

Adversarial review found three defects, all fixed here with regression tests that fail without their fix:

  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. A payload needing neither containment nor ordering now stays on the host's own path.
  2. Patch/lockfile integrity. A reworded comment had changed a hunk's line count without bumping its header, which pnpm rejects with ERR_PNPM_INVALID_PATCH; the lockfile hash was regenerated. The rebase had also dropped lint-staged from patchedDependencies — restored.
  3. Coverage gaps. The mid-probe re-arm guard was untested after the reconcile; a live-PTY quiet assertion was missing.

Known scope limit (unchanged)

Ordering is FIFO among recognised query replies, not over every byte. A reply coalesced with a keystroke and ordinary typed input still bypass the queue. The renderer change narrows this — query replies buffered during a viewport claim are no longer concatenated with keystrokes — but the host-side gap remains, pinned by known-limitation tests.

@coderabbitai

coderabbitai Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds synchronous PTY ECHO-state detection and uses it for immediate or deferred terminal query reply delivery. Query replies are parsed, classified, kept atomic, ordered, and bounded across local, relay, and remote-runtime paths. PTY session wiring and native node-pty support are updated. Integration tests cover cooked-mode delivery and child-stdin isolation. CI now gates expensive checks by code-path classification.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.42% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the fix and testing in detail, but it omits several required template sections and the required Fixes # issue format. Add the missing template sections, include Fixes #<issue>, provide visual proof or N/A with a reason, and complete the checklist and disclosures.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main PTY change: answering terminal colour queries in the caller's turn.
✨ 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: 8

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)

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

Use an MSYS-safe cmd.exe invocation.

Line 41 and Line 50 still use cmd /c. Git Bash can rewrite /c, so the WinPTY batch commands can fail during a Windows source build. Use the project-safe form that preserves the command switch in both locations.

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 (3)
tests/e2e/pty-input-write-queue-ssh.spec.ts (2)

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

Remove the cast so the unsupported-architecture guard stays type-safe.

Line 58 casts the uname -m output to keyof typeof FISH_ASSETS. The indexed access at line 59 is then typed as a defined release, so the guard at line 60 is dead code to the type checker while it is still required at runtime. Any future refactor can delete it without a type error.

♻️ Proposed fix
-  const arch = execDockerSshRelayTargetCommand(target, 'uname -m') as keyof typeof FISH_ASSETS
-  const release = FISH_ASSETS[arch]
+  const arch = execDockerSshRelayTargetCommand(target, 'uname -m').trim()
+  const release: (typeof FISH_ASSETS)[keyof typeof FISH_ASSETS] | undefined = Object.hasOwn(
+    FISH_ASSETS,
+    arch
+  )
+    ? FISH_ASSETS[arch as keyof typeof FISH_ASSETS]
+    : undefined
   if (!release) {
     throw new Error(`No pinned fish binary for Docker architecture ${arch}`)
   }

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

Write the screenshot into the Playwright output dir.

Lines 174-176 write into process.cwd()/validation-screenshots/sta-3948. That path pollutes the repository working tree and collides between parallel workers. testInfo.outputPath gives a per-test directory that Playwright creates and cleans.

♻️ Proposed fix
-      const screenshotDir = path.join(process.cwd(), 'validation-screenshots', 'sta-3948')
-      const screenshotPath = path.join(screenshotDir, 'linux-ssh-fish-child-stdin-pass.png')
-      mkdirSync(screenshotDir, { recursive: true })
+      const screenshotPath = testInfo.outputPath('linux-ssh-fish-child-stdin-pass.png')
       await orcaPage.screenshot({ path: screenshotPath, fullPage: true })

mkdirSync and the node:fs import can then be dropped if nothing else uses them.

src/shared/node-pty-echo-state-requirement.ts (1)

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

Reduce the new TypeScript comments.

Keep only concise, non-obvious rationale.

  • src/shared/node-pty-echo-state-requirement.ts#L1-L12: Replace the overview block with one short contract comment.
  • src/shared/node-pty-echo-state-requirement.ts#L52-L58: Reduce the CI rationale to one line.
  • src/shared/pty-slave-line-discipline-echo.ts#L94-L104: Reduce the kernel and fallback explanation to one line.
  • src/main/daemon/session-same-turn-query-reply-wiring.test.ts#L1-L13: Remove the multi-paragraph test overview.
  • src/main/daemon/session-same-turn-query-reply-wiring.test.ts#L78-L79: Keep one short assertion rationale.
  • src/main/daemon/session-same-turn-query-reply-wiring.test.ts#L123-L125: Keep one short flush-gate rationale.

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

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e9a213a6-58c2-4a76-9048-eb29b2fccd2c

📥 Commits

Reviewing files that changed from the base of the PR and between 4daace6 and ee68656.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (43)
  • .github/CONTRIBUTING.md
  • .github/workflows/adhoc-mac-build.yml
  • .github/workflows/daily-mac-build.yml
  • .github/workflows/hourly-mac-build.yml
  • .github/workflows/pr.yml
  • .github/workflows/pullfrog.yml
  • config/patches/[email protected]
  • config/patches/[email protected]
  • config/reliability-gates.jsonc
  • config/scripts/pr-workflow-parallelism.test.mjs
  • package.json
  • 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-subprocess-handle.ts
  • src/main/daemon/session.ts
  • src/main/providers/local-pty-provider-io-events.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/relay/pty-handler-same-turn-query-reply-wiring.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-input-coalescing.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/pty-startup-reply-echo-shapes.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
💤 Files with no reviewable changes (4)
  • .github/workflows/hourly-mac-build.yml
  • .github/workflows/daily-mac-build.yml
  • .github/workflows/adhoc-mac-build.yml
  • .github/CONTRIBUTING.md

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

Comment on lines +11223 to 11229
"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

Evidence command does not match its own summary.

The evidenceRun dated 2026-08-14 for pty-input-write-queue-ssh.spec.ts has this "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

Its "summary" states "Run with SKIP_BUILD=1 against the existing e2e bundle." The recorded command omits SKIP_BUILD=1. Add SKIP_BUILD=1 to the command string so the logged command reproduces what was actually run.

📝 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
"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."
}
"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 +11237 to 11238
"evidence": "Ten consecutive local unit-gate runs passed 1,380 tests in 29.57 seconds total with no fixed timing sleeps. The exact Docker SSH OSC oracle passed three consecutive runs before extraction and then passed both registered full-spec runs. The upstream-node-pty fish handoff oracle passed three local runs, including the final post-rebase run. CI and the normal soak window are not yet available."
},

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

flakeHistory claims are not backed by any logged evidenceRun.

flakeHistory.evidence states: "Ten consecutive local unit-gate runs passed 1,380 tests in 29.57 seconds total with no fixed timing sleeps." The evidenceRuns array for this gate logs only a single unit-gate run (2026-08-09, 138 tests, 2.35s) plus three Electron/Docker runs. No entry shows 10 runs or 1,380 total tests. Since this manifest exists specifically to provide an auditable evidence trail for reliability claims, add the missing evidenceRuns entries (or entries summarizing the 10-run soak) that back this claim, or correct the flakeHistory text to match what is actually logged.

Comment on lines +355 to +393
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 | 🟡 Minor | ⚡ Quick win

Sync ECHO probe wiring tests depend on a POSIX platform. createPtySlaveEchoSyncProbe returns undefined when process.platform === 'win32', so readEchoState is never consulted and no same-turn write happens on Windows. Both new wiring suites assert the opposite.

  • src/main/providers/local-pty-provider-io-events.test.ts#L355-L393: add a POSIX gate such as itOnPosixHost, matching pty-subprocess.test.ts.
  • src/relay/pty-handler-same-turn-query-reply-wiring.test.ts#L69-L102: confirm beginPtyHandlerTest forces a POSIX process.platform; if it does not, add the same gate.
📍 Affects 2 files
  • src/main/providers/local-pty-provider-io-events.test.ts#L355-L393 (this comment)
  • src/relay/pty-handler-same-turn-query-reply-wiring.test.ts#L69-L102

Source: Coding guidelines

Comment on lines +251 to +271
it('applies the same bound to DA1 replies kept atomic for ordering', async () => {
const { writes, pendingYields, queue } = createParkedQueue()
const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};2c`)

for (const reply of replies) {
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
}
expect(queue.enqueue('pty-1', 'k')).toBe(true)

await Promise.resolve()
for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) {
await releaseNextWrite(writes, pendingYields)
}
await queue.waitForDrain()

expect(writes.map((write) => write.data)).toEqual([
replies[0],
...replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES),
'k'
])
})

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

Release the final parked write before waiting for drain.

Line 264 waits while drain() is parked after it writes the 64th retained reply. The queued k write still needs one release. The test will time out.

Proposed fix
     for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) {
       await releaseNextWrite(writes, pendingYields)
     }
+    await releaseNextWrite(writes, pendingYields)
     await queue.waitForDrain()
📝 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
it('applies the same bound to DA1 replies kept atomic for ordering', async () => {
const { writes, pendingYields, queue } = createParkedQueue()
const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};2c`)
for (const reply of replies) {
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
}
expect(queue.enqueue('pty-1', 'k')).toBe(true)
await Promise.resolve()
for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) {
await releaseNextWrite(writes, pendingYields)
}
await queue.waitForDrain()
expect(writes.map((write) => write.data)).toEqual([
replies[0],
...replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES),
'k'
])
})
it('applies the same bound to DA1 replies kept atomic for ordering', async () => {
const { writes, pendingYields, queue } = createParkedQueue()
const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};2c`)
for (const reply of replies) {
expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true)
}
expect(queue.enqueue('pty-1', 'k')).toBe(true)
await Promise.resolve()
for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) {
await releaseNextWrite(writes, pendingYields)
}
await releaseNextWrite(writes, pendingYields)
await queue.waitForDrain()
expect(writes.map((write) => write.data)).toEqual([
replies[0],
...replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES),
'k'
])
})

Comment on lines +96 to +112
const term = nodePty.spawn(process.execPath, [querierScript, String(rawDelayMs)], {
name: 'xterm-256color',
cols: 120,
rows: 30,
cwd: workDir,
env: { PATH: process.env.PATH ?? '/usr/bin:/bin', TERM: 'xterm-256color' }
})

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. The `verdictsAtQuery` assertion below is the
// real check; this one names the cause when the native binding is a prebuild.
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

The probe vacuity assertion runs outside the try/finally that kills the pty. Both suites spawn a live pty, then assert the sync probe returned a definite verdict before entering the block that owns term.kill(). On a prebuilt node-pty the probe answers unknown, the assertion throws, and the spawned process and pty fd stay open for the Vitest worker.

  • src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts#L96-L112: move the echoSyncProbe?.() assertion into the try block that starts at line 140.
  • src/shared/fish-query-reply-child-stdin.node-pty.test.ts#L130-L156: move the echoSyncProbe?.() assertion into the try block that starts at line 217.
📍 Affects 2 files
  • src/shared/pty-cooked-querier-reply-delivery.node-pty.test.ts#L96-L112 (this comment)
  • src/shared/fish-query-reply-child-stdin.node-pty.test.ts#L130-L156

Comment on lines +29 to +36
let accepted = false
for (const reply of replies) {
const handled = needsCookedEchoSafeQueryReply(reply)
? delivery.answer(reply)
: delivery.answerInOrder(reply)
accepted = handled || accepted
}
return accepted

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

Return value can report full ownership after partial delivery.

The doc comment states the return value is true only when delivery owns the WHOLE payload. The loop uses handled || accepted, so one accepted reply makes the result true even when a later reply is rejected. The caller then drops the rejected bytes instead of writing them on its own path. answer and answerInOrder both return false when the delivery is closed or an immediate write throws, so a mixed payload can lose its tail.

Track every reply instead, and let the caller keep the payload when any reply is rejected.

♻️ Proposed change to keep the contract all-or-nothing
-  let accepted = false
-  for (const reply of replies) {
-    const handled = needsCookedEchoSafeQueryReply(reply)
-      ? delivery.answer(reply)
-      : delivery.answerInOrder(reply)
-    accepted = handled || accepted
-  }
-  return accepted
+  let allAccepted = true
+  for (const reply of replies) {
+    const handled = needsCookedEchoSafeQueryReply(reply)
+      ? delivery.answer(reply)
+      : delivery.answerInOrder(reply)
+    allAccepted = handled && allAccepted
+  }
+  return allAccepted

Note that a mixed result still leaves the accepted replies queued, so the caller must not re-send them. If that is intended, then document the OR semantics instead.

Comment on lines +150 to +155
const relayExports = execDockerSshRelayTargetCommand(
target,
'module=$(find /root/.orca-remote -type d -path \'*/node_modules/node-pty\' | head -n 1); node -e "const p=require(process.argv[1]); console.log(Object.keys(p.native || {}).join(\',\'))" "$module"'
)
testInfo.annotations.push({ type: 'relay-node-pty-exports', description: relayExports })
expect(relayExports).not.toContain('echoState')

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check how the relay bundles node-pty and whether the patch reaches it.
set -euo pipefail

fd -H -t f 'package.json' -d 3 --exec sh -c 'grep -l "node-pty" "$1" || true' _ {} \;
rg -n --glob '!**/node_modules/**' 'orca-remote|relay.*node-pty|node-pty.*relay' -C3 config src | head -80
rg -n 'echoState' --glob '!**/node_modules/**' -C2 | head -60

Repository: stablyai/orca

Length of output: 9573


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- test context ---'
sed -n '110,175p' tests/e2e/pty-input-write-queue-ssh.spec.ts

printf '%s\n' '--- helper definition and call sites ---'
rg -n -C8 'function execDockerSshRelayTargetCommand|const execDockerSshRelayTargetCommand|execDockerSshRelayTargetCommand' tests config src

printf '%s\n' '--- relay package and patch wiring ---'
rg -n -C5 'node-pty|echoState|node_modules/node-pty|relay-assets' package.json pnpm-lock.yaml config tests src --glob '!**/node_modules/**' | head -240

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- command execution behavior ---'
sed -n '1,55p' tests/e2e/helpers/docker-ssh-relay-target.ts
rg -n -C4 'node-pty|echoState|upstream-node-pty|relay-node-pty-exports' \
  tests/e2e/pty-input-write-queue-ssh.spec.ts \
  config/reliability-gates.jsonc \
  config/relay-assets \
  package.json

printf '%s\n' '--- empty module behavior ---'
node - <<'JS'
const { spawnSync } = require('node:child_process')
const result = spawnSync(process.execPath, [
  '-e',
  'require(process.argv[1])',
  ''
], { encoding: 'utf8' })
console.log(JSON.stringify({
  status: result.status,
  stdout: result.stdout,
  stderr: result.stderr.split('\n').slice(0, 2).join('\n')
}, null, 2))
JS

Repository: stablyai/orca

Length of output: 27517


Add an explicit empty-module failure.

If find returns no path, fail with a named error before require; otherwise the helper reports only a raw docker exec failure. Keep the echoState assertion because the relay intentionally uses upstream node-pty, while the later child-stdin assertion covers fallback behavior.

Root-cause follow-up to #15559, which stopped a CPR overtaking a deferred
colour reply but left the deferral itself in place.

Orca answers terminal queries by writing to the PTY master, which a line
discipline in ECHO copies straight back out as junk on a cooked prompt
(#12112). The guard was to withhold the write until an `stty` subprocess
proved ECHO clear — and forking is what forced the decision to be async.
Any deferral, however short, lets a reply written later in the same turn
overtake this one, so the async probe was the bug's root cause.

Read the bit synchronously instead. Linux and the BSDs redirect a
master's mode ioctls to the slave, so a `tcgetattr` on the master fd
node-pty already owns answers for the slave with no fork: measured 0.26us
against 2403us for the subprocess. With a verdict available inline, a
querying program that already cleared ECHO — every raw-mode prober,
including the colour probe behind the `gh auth login` report — is
answered in its own turn and can never be reordered.

The deferral stays for the genuinely cooked case, and the ordering
guarantee stays underneath it: hosts whose node-pty predates this patch
get no sync probe and fall back to the deferred path, which mixed
client/host versions make a live production path.

Reply routing is all-or-nothing: a payload needing neither containment
nor ordering stays on the host's own path, so a CPR answered during shell
startup cannot pass the daemon's post-ready flush gate and splice into
the buffered startup command.

Native side is fail-safe: a kernel that did not redirect would answer
from the master's own termios, whose ECHO defaults set, so the degraded
verdict is "echoing" — never a false "quiet". The JS half ships in the
pnpm patch while the binding needs a source build, so
ORCA_REQUIRE_NODE_PTY_ECHO_STATE=1 makes CI fail rather than silently
skip when it is handed an upstream prebuild.

Co-authored-by: Brennan <[email protected]>
@nwparker
nwparker force-pushed the nwparker/sync-echo-state-query-order branch from ee68656 to bc319ab Compare August 20, 2026 06:35
Three defects found in external review of the reply-ordering work.

node-pty delivers onData inside the master write, so a query can be
answered while the queue is mid-flush. `flushPendingWrites` spliced the
array off before writing, so that reply saw an empty queue, took the
same-turn path, and landed ahead of entries the loop had not written yet
— reproduced as 01, 99, 02, 03. It now shifts one entry at a time so a
re-entrant reply queues behind the rest, bounded by the length at entry
so a re-entrant push cannot spin the loop.

An overflow flush can re-enter as far as teardown. `answer` did not
re-check `closed` afterwards, so it queued behind a closed delivery,
returned true, and the reply was never written and never reported.

The payload router's ownership comment overstated its guarantee. The
`any` semantics are deliberate — returning false after a constituent was
already written would have the caller re-write the whole payload and
duplicate it into the child's stdin — so the residual mixed-failure drop
is now documented rather than implied away.

@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/shared/pty-startup-reply-delivery.ts (1)

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

Shorten the added comments.

Keep only the non-obvious invariant in each comment.

  • src/shared/pty-startup-reply-delivery.ts#L327-L333: State that bounded shifting preserves FIFO order during synchronous reentry.
  • src/shared/pty-startup-reply-delivery.ts#L149-L151: State that flushing can synchronously close delivery and requires a closed-state check.
  • src/shared/pty-startup-ingress-live-query-reply.test.ts#L469-L471: State that the test protects FIFO order during flush reentry.

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

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5cfc7923-0901-4b82-af67-a8da3a832805

📥 Commits

Reviewing files that changed from the base of the PR and between bc319ab and 066510b.

📒 Files selected for processing (3)
  • src/shared/pty-startup-ingress-live-query-reply.test.ts
  • src/shared/pty-startup-reply-delivery.ts
  • src/shared/terminal-query-reply-delivery.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/shared/terminal-query-reply-delivery.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@nwparker

Copy link
Copy Markdown
Contributor Author

Closing in favour of #15578, which takes the opposite approach and lands instead.

This PR made the ECHO probe fast (native tcgetattr via a node-pty patch, 2403µs → 0.26µs) so that withholding a reply stayed cheap. Two independent frontier-model reviews and the archaeology on #12202 converged on the better answer: the probe was never the bug, deferral was. Making the wrong mechanism fast is not the fix.

#15578 deletes the withholding scheduler outright — pending-write queue, async probe, poll budget, rate limit, deadline flush, and the answer/answerInOrder split — for a net −583 lines, and drops the node-pty fork this PR would have added permanently.

The one thing withholding covered, the verbatim echo of a stty -echoctl tty, is closed rather than accepted: that shape is now projected directly, matched only when complete and never held as a partial, so it cannot take a bare trailing ESC from the query parser.

Everything of value here survives in #15578 — the all-or-nothing reply routing that keeps a CPR behind the daemon's post-ready flush gate, the renderer change that stops query replies being concatenated with keystrokes during a viewport claim, and the real-PTY fish test. The Co-authored-by trailer is preserved there too.

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

1 participant