Skip to content

fix(terminal): serialize PTY writes and harden large terminal sends - #10504

Open
innocarpe wants to merge 4 commits into
stablyai:mainfrom
innocarpe:fix/windows-pty-input-chunk-pacing
Open

innocarpe wants to merge 4 commits into
stablyai:mainfrom
innocarpe:fix/windows-pty-input-chunk-pacing

Conversation

@innocarpe

@innocarpe innocarpe commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

A large terminal send can yield while checking its size. A shorter send arriving then could overtake it. This change reserves the terminal’s input turn first, so the larger send stays ahead and queued input stops when that terminal exits.

What Changed

  • Reserve a queue per PTY and lifecycle generation before asynchronous validation or liveness checks; share it with preview input and prompt writes. Reserve queued prompts before waiting for prior receipt observation.
  • Release the input turn once prompt submit bytes land, while the separate prompt-receipt observation continues. Protocol replies reserve a normal queue position and can enter an active prompt turn, including while a queued prompt awaits the prior receipt. Replies execute once, preserve their own order, and drain before the next input turn.
  • Keep current chunk yields and atomic prompt paste frames. Start RPC keepalive for queued terminal sends without consuming a long-poll slot.

Why

Ordering and teardown protection address independently reproducible problems. Current chunk yields already keep the event loop responsive; unproven Windows-only pacing would slow every paste.

Linked Issue

Refs #10416

Visual Proof

N/A — terminal byte ordering and RPC lifetime changes; the before/after evidence is the deterministic runtime regressions.

Testing

  • 91 focused runtime tests cover large-send ordering, preview input, rejected input, prompt receipt observation, queued prompt/raw input order, immediate replies during prior receipt observation, protocol reply order and draining, generation teardown, chunk yields, and queued-send keepalive.
  • Focused runtime tests on macOS, changed-code quality gate, Node TypeScript check, and whitespace check.
  • Manual Windows/Linux/SSH verification and full build remain for CI or maintainer testing. No ConPTY truncation or pacing claim is made.

AI Disclosure

Implementation and verification assisted by OpenAI Codex.

Review

Addressed the Greptile ordering, queued-prompt, and protocol-reply findings with regressions. Current runtime modules and existing platform/remote behavior are retained.

Agent skill upstream boundary

  • Not applicable — no agent skill source changed.

Checklist

  • Focused terminal input ordering change, with before/after and mechanism explained.
  • Self-reviewed and considered platform, remote, folder-workspace, and mobile input paths.
  • Focused tests, changed-code quality gate, and Node type check.
  • Full build and cross-platform manual validation.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

  • Last reviewed commit: 3e23a88e2769c716a21ed80d8ecef344c4122387
  • Latest commit, not reviewed: 52a7c29

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

Adds platform-aware terminal input chunk sizes and inter-chunk delays, with smaller chunks and longer gaps for Windows ConPTY. Routes regular, action, prompt, and paste writes through per-PTY queues that serialize operations, track delays, and cancel pending writes during PTY shutdown. Adds tests for pacing, ordering, cancellation, and RPC keepalive behavior. Terminal sends now start keepalive handling without consuming long-poll capacity.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.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
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 and concisely describes the main change: serialized PTY writes and more reliable large terminal sends.
Description check ✅ Passed The description covers the required sections and explains the user impact, implementation, rationale, testing, issue reference, and validation limits. The Notes section is omitted, but the relevant pl…
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6250c252-ecd5-407b-b64b-dfc2cbf49fe2

📥 Commits

Reviewing files that changed from the base of the PR and between 12fa5ff and d6d8f25.

📒 Files selected for processing (3)
  • src/main/runtime/orca-runtime.ts
  • src/shared/terminal-input.test.ts
  • src/shared/terminal-input.ts

Comment thread src/shared/terminal-input.ts Resolved
@nwparker

Copy link
Copy Markdown
Contributor

Maintainer review: I could not reproduce the premise on real Windows, and the pacing introduces a new failure mode

I picked this up to land it and ran the change against a real Windows 11 box (win32 x64, Node v24.18.0, ConPTY via the repo's own node-pty). The measurements do not support the stated mechanism, and they surface a regression that I think blocks the current approach. Details below so the work isn't lost.

1. 16 KiB + setTimeout(0) did not truncate on real ConPTY

Self-contained node-pty probe: spawns a raw-stdin reader under ConPTY (useConpty: true), writes a payload under three pacing regimes, and reports bytes actually received by the child.

Regime A — reader busy-blocks its main thread 40 ms every 3 reads (the "TUI stalls on render" theory from #10416):

platform=win32 node=v24.18.0 payload=65536B stallMs=40 stallEvery=3 bootMs=0
single write             writes=    1 sent=65536 got=65536 lost=0 OK writeWall=1ms
main 16KiB/0ms           writes=    4 sent=65536 got=65536 lost=0 OK writeWall=1ms
PR 1KiB/16ms             writes=   64 sent=65536 got=65536 lost=0 OK writeWall=1829ms

Regime B — child stays in cooked mode and does not read for 6 s (the "freshly launched agent" regime), 256 KiB:

platform=win32 node=v24.18.0 payload=262144B stallMs=0 bootMs=6000
single write             writes=    1 sent=262144 got=262144 lost=0 OK writeWall=2ms
main 16KiB/0ms           writes=   16 sent=262144 got=262144 lost=0 OK writeWall=1ms
PR 1KiB/16ms             writes=  256 sent=262144 got=262144 lost=0 OK writeWall=7330ms

Current main delivered 100% of bytes in every case. Even a single unchunked 256 KiB write delivered intact. I could not produce the reported tail-fragment truncation at the ConPTY layer at all.

At 2 MiB with a 60 ms/2-read stall, all three regimes failed identically (including this PR's) — that is the reader timing out, not a pacing effect. Pacing does not fix it either.

2. The reporter was on daemon-hosted panes, which do not touch ConPTY on this path

#10416 says "daemon-hosted panes". On that path ptyController.write → DaemonPtyAdapter.write → this.client.notify('write', …) (src/main/daemon/daemon-pty-adapter.ts:599), i.e. one NDJSON socket frame per chunk, applied daemon-side at daemon-server.ts:811. So on the reporter's actual setup, 1 KiB chunking multiplies socket frames 16x rather than pacing a console host. Whatever drops the input there, it is not ConPTY back-pressure — so this fix likely does not address the reported bug.

3. Blocking regression: paced sends over ~1.83 MiB exceed the 30 s RPC socket idle timeout on Windows

orca terminal send is served by UnixSocketTransport, which destroys any socket idle for RUNTIME_RPC_SOCKET_IDLE_TIMEOUT_MS = 30_000 (src/main/runtime/rpc/unix-socket-transport.ts:12,119). Keepalive is opt-in for long-polls only, and terminal.send is not one — isLongPollRequest covers only terminal.wait, orchestration.ask, and orchestration.check --wait (runtime-rpc.ts:398). The comment there states the consequence outright: without keepalive "the 30 s socket idle timer tears it down."

With 1 KiB / 16 ms, wall time crosses 30 s at ceil(b/1024) > 1876 → ~1.83 MiB. TERMINAL_INPUT_MAX_BYTES is 16 MiB, so every Windows payload between ~1.83 MiB and the 16 MiB cap is accepted by validation and then has its socket destroyed mid-write. Measured on the Windows box: 2 MiB paced took 57 785 ms. That converts a truncation bug into a hard teardown on the exact path the PR targets.

Latency cost, chunks x gap (measured wall time in brackets):

Payload main this PR
4 KiB 1 write, 0 ms 4 writes, 48 ms
64 KiB 4 writes, 0 ms 64 writes, 1.0 s [1829 ms]
256 KiB 16 writes, 0 ms 256 writes, 4.1 s [7330 ms]
100 KB 7 writes, 0 ms 98 writes, 1.6 s
2 MiB 128 writes, 0 ms 2048 writes, 32.7 s [57 785 ms] — past the 30 s wall
16 MiB (cap) 1024 writes, 0 ms 16 384 writes, 262 s

4. Concurrent sends to one PTY interleave — pre-existing, but this widens the window 16x

There is no per-PTY write queue on the runtime path (the renderer has one in pty-input-write-queue.ts; the runtime/RPC path does not). Two overlapping sendTerminal calls to one PTY interleave chunk-by-chunk — I confirmed with a temporary test that logged write order ababab. This is pre-existing on main (which also awaits setTimeout(0) between chunks and therefore also yields), so the PR does not introduce it. But it stretches the interleavable window on Windows from ~0 ms to ~1 s per 64 KiB, making a latent race materially more likely to bite.

What is good here

  • Pacing is correctly scoped to win32; getTerminalInputChunkGapMs() returns 0 elsewhere.
  • Commit 9f090cb (skip the timer when gap is 0) is a genuine improvement over main for macOS/Linux — main awaits setTimeout(0) between chunks unconditionally; this skips it. That part is worth keeping regardless of what happens to the rest.
  • No per-keystroke impact. Interactive typing goes through pty:write IPC → writePtyProviderInput (src/main/ipc/pty.ts:4812), which never calls the runtime helper and keeps the 16 KiB default. And any payload under one chunk emits a single chunk, so the gap loop never runs.

Suggested path

  1. Reproduce Long PTY injections into TUI agent panes are silently truncated; dispatch reports 'dispatched' anyway #10416 against the daemon write path (NDJSON frame handling), not ConPTY — that is where the reporter's bytes actually flow.
  2. If pacing is still wanted, bound total paced duration or make terminal.send a keepalive/long-poll request first, otherwise the 30 s wall turns into a new bug.
  3. Consider the issue's own asks 2 and 3 (file-based delivery, delivery ack before marking dispatched) — an ack would have surfaced this class of failure instead of silently reporting success.

Verification run: src/shared/terminal-input.test.ts 14 passed; orca-runtime.test.ts -t chunk 24 passed; tsc --noEmit -p config/tsconfig.node.json exit 0; oxlint on all three changed files clean. Windows probes executed on real hardware as shown. Not pushing changes — the diff is unchanged from the author's.

Original patch by @innocarpe — the win32 scoping and the zero-gap fast path are sound; it is the underlying premise I could not confirm.

@nwparker

Copy link
Copy Markdown
Contributor

Could not reproduce the truncation this paces around — recommend holding

I ran a self-contained node-pty probe on a real Windows host (win32, Node v24.18.0, useConpty: true): spawn a raw-stdin reader child, write a payload under three pacing strategies, count bytes actually delivered. Zero truncation in every configuration, including a single unchunked 1 MiB write into a reader that busy-blocks its main thread:

1MB payload, reader stalling 80ms every 4 reads:
single write     writes=   1  sent=1048576  got=1048576  lost=0  OK  writeWall=4ms
main 16KiB/0ms   writes=  64  sent=1048576  got=1048576  lost=0  OK  writeWall=2ms
PR 1KiB/16ms     writes=1024  sent=1048576  got=1048576  lost=0  OK  writeWall=28864ms

Also tested an idle reader at 64 KB, a stalled reader at 256 KB, and a child still in cooked mode with raw mode not yet armed (the freshly-launched-agent regime). All three strategies delivered 100% in all of them. I could not get ConPTY to drop bytes at all.

The cost is severe and measured. The gap is per-chunk, so wall-clock ≈ bytes/1024 × 16 ms: 64 KB → ~1.7 s, 100 KB → ~1.6 s, 1 MiB → 28.9 s. That's a large regression on paste to fix a truncation I can't demonstrate, and 1 KiB/16 ms don't correspond to any ConPTY buffer behavior I could measure — they read as tuned constants.

What the PR gets right: it's correctly Windows-gated (non-win32 returns gap 0 and the chunkGapMs > 0 guard skips the timer entirely, so no macOS/Linux regression), and single keystrokes are unaffected since iterateTerminalInputChunks yields the whole string when under the max.

Two real defects if pacing is kept:

  • Remote host is mis-detected. Both call sites use bare getTerminalInputChunkMaxBytes()/getTerminalInputChunkGapMs(), which key off the local process.platform. A macOS client driving a Windows SSH host gets no pacing at all; a Windows client driving a Linux host pays 16 ms/chunk over the relay for nothing. orca-runtime.ts:8334 already resolves win32-ness per-PTY via pathFlavorForPty(pty) including connectionId — that's the correct input.
  • No per-PTY write serialization, so two concurrent sendTerminal calls to one PTY interleave chunk-wise. Pre-existing on main, but this widens the window from ~0 ms to 16 ms × chunks, making it far likelier to bite.

I've left Closes #10416 changed to Refs so an unresolved issue isn't auto-closed. My suggestion is to hold this pending a reproducible repro — the reporter's own file-based delivery idea (ask #2 in #10416) and delivery verification (ask #3, where dispatch reports success despite failed delivery) look like the higher-value directions. Happy to be shown a repro that contradicts my probe; the scripts are self-contained and I can share them.

@nwparker

Copy link
Copy Markdown
Contributor

Re-reviewed after the rewrite — three of my findings are fixed; the linkage regressed

I verified the new revision (fc7d60681c) rather than taking the summary at face value.

Fixed, and I confirmed each:

  • Interleaving. The per-PTY write queue is real and the test is a genuine detector, not a tautology. Against the merge-base runtime it fails with an actual byte-order assertion (expected 'aaaa…' to be 'aaaa…'); at head it passes. That defect was real and is now closed.
  • Wrong host for pacing — my main concern. orca-runtime.ts:14210,14246 now reads getPtyExecutionHostMetadata(ptyId).hostPlatform ?? process.platform, so a macOS client driving a Windows SSH host paces correctly and a Windows client driving Linux doesn't pay 16 ms/chunk for nothing. WSL maps to linux, which is right.
  • Teardown now cancels pending chunks and clears timers, and stale-incarnation exits don't cancel a replacement PTY.

The RPC keepalive addition is a good catch too — it addresses the 30-second socket idle timeout I measured earlier, which would otherwise have killed large paced sends outright.

One thing to put back: this revision restored Closes #10416. I've changed it to Refs #10416 again.

That isn't bookkeeping pedantry. The PR's own body states the Windows probe did not reproduce the truncation — my independent probe didn't either (zero loss at 1 MiB unchunked into a stalled reader). Merging with Closes would auto-close a bug report whose defect has never been demonstrated to be fixed, and whose reporter would then have to reopen it. Refs links the work without making that claim.

Where that leaves it. The concurrency, lifetime, remote-host, and timeout fixes are solid, well-tested work that stands on its own merits. The pacing remains unjustified by any reproduction — two independent probes on real Windows/ConPTY failed to lose a byte, and 1 KiB/16 ms still costs ~1.55 s per 100 KB and ~262 s at 16 MiB. Reasonable people could ship this as defensive hardening; I'd rather see the pacing gated or dropped until someone reproduces #10416, with the queue/lifetime/keepalive fixes landing regardless. That call is the maintainers', and the body is now honest about the evidence either way.

@innocarpe

Copy link
Copy Markdown
Contributor Author

@nwparker Thanks for the thorough real-Windows probes and for re-checking the rewrite — the measurements and the split between “justified infrastructure” vs “unjustified pacing” are very clear.

I agree: we still don’t have a reproduction of the silent truncation this PR originally targeted, so I don’t want to ship 1 KiB / 16 ms pacing as a fix for #10416. The per-PTY write queue, host-platform-aware chunking inputs, teardown cancellation, and RPC keepalive are the parts that stand on their own (and the queue regression is real).

Plan from here: drop (or fully disable by default) the Windows inter-chunk gap / small-chunk pacing, keep the serialization + lifetime + keepalive work, and leave the issue as Refs #10416 until someone can reproduce the original drop. Happy to adjust if you’d rather gate pacing behind an env flag instead of removing it outright.

@innocarpe innocarpe changed the title fix(terminal): pace Windows PTY input chunks to stop silent truncation fix(terminal): serialize PTY writes and harden large terminal sends Jul 27, 2026
@innocarpe

Copy link
Copy Markdown
Contributor Author

@nwparker Follow-up on the plan above — pushed to this branch:

  • Dropped the Windows 1 KiB / 16 ms pacing (chunk budget is the same on all platforms now; gap stays 0)
  • Left the pieces that stood up under review: per-PTY write serialization, host-aware helpers, teardown cancel, RPC keepalive
  • Updated tests for the no-pacing behavior
  • PR title/body now describe that scope; still Refs #10416 rather than claiming the truncation is fixed

Happy to tweak further if you'd rather have pacing behind an env flag instead of removing it outright.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (2)
src/main/runtime/runtime-rpc.test.ts (1)

4441-4443: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Synchronize on overflow responses instead of a fixed sleep.

activeLongPolls >= 2 only proves that two asks were admitted; the other two requests may not yet have reached admission when the later shed assertion runs. Wait until two ask sessions contain terminal responses with runtime_busy rather than relying on sleep(100).

src/main/runtime/runtime-rpc.ts (1)

501-502: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve reserved headroom when longPollCap is 1.

With longPollCap: 1, this computes askLongPollCap as 1, allowing an orchestration.ask to consume the only slot and starve terminal.wait/check --wait. Clamp the ask cap to at most longPollCap - 1 (or reject configurations below two slots); the existing tests already use longPollCap: 1.

Suggested boundary fix
-    this.askLongPollCap = Math.max(1, Math.floor(longPollCap * ASK_LONG_POLL_SHARE))
+    this.askLongPollCap = Math.max(
+      0,
+      Math.min(longPollCap - 1, Math.floor(longPollCap * ASK_LONG_POLL_SHARE))
+    )
🧹 Nitpick comments (2)
src/main/runtime/runtime-rpc.ts (1)

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

Correct the admission-fence comment.

Short RPCs bypass admitLongPoll(), so the total cap bounds concurrent long-polls; it does not protect short RPCs.

src/main/runtime/orca-runtime.ts (1)

14200-14232: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Reintroduce a periodic macrotask yield for multi-chunk terminal sends.

TERMINAL_INPUT_CHUNK_GAP_MS is now 0 for all platforms, so large texts are chunked into up to 64 chunks per MiB with no unconditional setTimeout/delay between chunks. Add a lightweight macrotask yield periodically in writeTerminalInputChunks when the remaining payload can exceed one chunk, instead of avoiding yielding every chunk.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a83cb870-5a29-4a2a-9207-e241ba002b4c

📥 Commits

Reviewing files that changed from the base of the PR and between 9f090cb and 5c84225919fd951729eb8106e36cfb518ee9f56b.

📒 Files selected for processing (4)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/runtime-rpc.test.ts
  • src/main/runtime/runtime-rpc.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3559d326-efe9-492c-a8cc-0d9f84ef3026

📥 Commits

Reviewing files that changed from the base of the PR and between 5c84225919fd951729eb8106e36cfb518ee9f56b and 3e23a88e2769c716a21ed80d8ecef344c4122387.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/orca-runtime.ts

Comment thread src/main/runtime/orca-runtime.test.ts Resolved
@innocarpe

Copy link
Copy Markdown
Contributor Author

@coderabbitai Tightened the large-chunk test so it only flushes microtasks (no timer advance) before asserting both 16 KiB writes — reintroducing an inter-chunk gap should fail that assertion now.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline src/main/runtime/orca-runtime.test.ts --items all --type function --match 'sendTerminal|chunk|terminal' || true
rg -n -i -C 8 '16\s*\*\s*1024|16384|microtask|advanceTimers|sendTerminal|chunk' src/main/runtime/orca-runtime.test.ts
rg -n -C 6 'writeTerminalInputChunks|waitForTerminalInputGap|getTerminalInputChunkGapMs|iterateTerminalInputChunks' src/main/runtime/orca-runtime.ts src/shared/terminal-input.ts

Length of output: 83391


@innocarpe Confirmed. The updated test at src/main/runtime/orca-runtime.test.ts Lines 13486–13518 is an effective regression guard:

  • It flushes microtasks only, then requires both 16 KiB writes to have occurred.
  • It also asserts that no timers were scheduled.
  • Restoring a timer-based inter-chunk gap would leave the second write pending and/or make vi.getTimerCount() non-zero, so the test would fail without accidentally advancing through the delay.

If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@innocarpe
innocarpe force-pushed the fix/windows-pty-input-chunk-pacing branch from 8d78eea to f7fcdf8 Compare August 6, 2026 03:42
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (f7fcdf8dad)

Rebase onto latest upstream/main: serialize paced PTY input writes with absence gate preserved.

@AmethystLiang
AmethystLiang requested a review from OrcaWin August 7, 2026 16:49
@nwparker nwparker removed the P1 label Aug 19, 2026
@innocarpe
innocarpe force-pushed the fix/windows-pty-input-chunk-pacing branch from f7fcdf8 to 7632f29 Compare September 28, 2026 22:58
@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[High impact] Adds serialization and keepalive logic to terminal input handling.

The PR is not yet safe to merge because opted-in agent prompts can still be overtaken by later terminal input.

Findings

  1. P1 Opted-in prompts bypass input queue ▶

Summary

The PR adds per-PTY-generation input serialization, lifecycle checks, prompt reply windows, and RPC keepalives for queued terminal sends. The default prompt, raw-send, preview, and protocol-reply paths are coordinated, but opted-in prompt submissions still bypass the shared queue.

  • Serializes ordinary and preview terminal input before asynchronous validation and liveness checks.
  • Separates prompt receipt observation from ownership of the terminal input turn.
  • Admits and drains protocol replies during active prompt turns.
  • Keeps queued terminal-send RPC connections alive without consuming long-poll admission capacity.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[sendTerminalAgentPrompt] --> B{onPermission wait or expectedBinding?}
  B -- No --> C[serializeTerminalInput]
  C --> D[serializeAgentPromptSubmission]
  B -- Yes --> E[submitTerminalAgentPrompt]
  E --> F[serializeAgentPromptSubmission only]
  G[Raw and preview input] --> H[serializeTerminalInput]
  F -. independent queues permit overtaking .- H
Loading

Reviews (5) · Last reviewed commit: "fix(runtime): keep protocol replies flow..." · Reviewed by Greptile

Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/main/runtime/orca-runtime.ts Resolved
@innocarpe
innocarpe force-pushed the fix/windows-pty-input-chunk-pacing branch from 7632f29 to 6612d06 Compare September 29, 2026 07:33
@innocarpe
innocarpe force-pushed the fix/windows-pty-input-chunk-pacing branch from 6612d06 to e5a2775 Compare September 29, 2026 07:53
@innocarpe

Copy link
Copy Markdown
Contributor Author

Updated this follow-up at f9f1b46ecb: known review findings are addressed, with 91 focused runtime tests, the Node TypeScript check, and changed-code quality checks passing. Queued prompts preserve input order while protocol replies can reach an earlier prompt still awaiting receipt observation.

Greptile has completed successfully. PR Checks, Mobile Checks, PR test LoC, and Bun profile persistence currently require maintainer approval; please approve those workflow runs when reviewing this update.

@innocarpe
innocarpe force-pushed the fix/windows-pty-input-chunk-pacing branch from f9f1b46 to b3fbc81 Compare October 29, 2026 02:44
Comment on lines 28 to +29
const delivery = await this.serializeAgentPromptSubmission(ptyId, generation, async () => {
await assertTerminalInputWithinLimitWithYield(payload)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Opted-in prompts bypass input queue

When an agent prompt uses onPermission: 'wait' or expectedBinding, this path serializes it only through serializeAgentPromptSubmission instead of the shared per-PTY input queue. If later raw or preview input arrives while the prompt is waiting for permission or yielding during validation, that later input writes first, reversing the invocation order.

@innocarpe
innocarpe force-pushed the fix/windows-pty-input-chunk-pacing branch from b3fbc81 to 52a7c29 Compare November 2, 2026 11:19

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants