Skip to content

fix(terminal): remote query-reply corruption (#7329) + snapshot grid-width repaint (#7279) - #7736

Merged
Jinwoo-H merged 6 commits into
mainfrom
Jinwoo-H/bug-7329-remote-term-corruption
Jul 7, 2026
Merged

Jinwoo-H merged 6 commits into
mainfrom
Jinwoo-H/bug-7329-remote-term-corruption

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7329.

Symptom

On the remote-server (remote-runtime) path, typing gets escape sequences injected around it and follow-up commands are corrupted. From the reporter's screenshot (running orb reset, whose starship prompt queries the terminal), complete query replies appear as literal text and splice into typed input:

Type "yes" to continue: ^[]11;rgb:2828/2c2c/3434^[\^[[3;1Ryes

^[]11;rgb:...^[\ is a complete OSC 11 background-color reply and ^[[3;1R is a complete CPR cursor-position reply — both are xterm's answers to the prompt's queries, and both are echoed literally and mixed into the yes the user typed.

Root cause

The remote transport routes all sendInput — including terminal query replies (OSC 10/11, CPR/DSR, DA, pixel-size, mode 2031) — through an 8ms input debounce (REMOTE_TERMINAL_INPUT_FLUSH_MS). A querying program reads these replies synchronously in raw mode with a short timeout, so the debounced reply misses that window and lands on the shell prompt in cooked mode, which echoes it literally and buffers it into the next input line. The local transport drains promptly (no wall-clock timer), which is why local terminals don't corrupt.

Fix

  • Add isTerminalQueryReply() — a conservative classifier for xterm's synthetic query-reply grammars (CPR/DSR, DA, pixel-size, DECRPM, OSC color/title). It deliberately does not match arrows, Home/End, function keys, or bracketed-paste markers, so ordinary typed input stays coalesced.
  • Add transport.sendInputImmediate(data):
    • Remote: flush pending batched input first (preserving byte order), then send the reply immediately without arming the debounce.
    • Local: same as sendInput (already prompt).
  • Route the reply call-sites through it: OSC 10/11 + DA1 (installTerminalCapabilityReplyHandlers), pixel-size, mode 2031, hidden/foreground OSC color, and the native CPR/DSR/DA replies that arrive mixed with keystrokes via xterm's onData.

Typed input — including bursty arrow-key auto-repeat — keeps the debounce coalescing.

Also fixed (same corruption family)

A separate mid-escape snapshot bug: a PTY read ending mid-escape leaves bytes in the emulator's parser, so SerializeAddon drops them and the next live chunk's continuation renders literally after a snapshot restore. The headless emulator now tracks the trailing partial (terminal-partial-escape-tail.ts, VT500 state machine, fold-safe, capped) and ships it as TerminalSnapshot.pendingEscapeTailAnsi; the restorer writes it last (after the post-replay reset, whose ESC would otherwise abort it) so the live continuation completes it. Threaded through both the remote terminal.multiplex snapshot path and the local hidden-reveal (getMainBufferSnapshot) path.

Not ported: the DECSC saved-cursor (Bug D) fix — it depends on an unmerged serializeWithAbsoluteCursor serialization subsystem that has diverged significantly from main; porting it is disproportionate risk and it is not implicated by this report.

Regression notes

  • sendInputImmediate is additive; typed-input coalescing is unchanged (proven by test: typed input stays debounced, a reply is sent immediately with pending input flushed ahead of it in-order).
  • pendingEscapeTailAnsi is an optional, backward-compatible wire field (old daemon omits it, old renderer ignores it — no PROTOCOL_VERSION bump).
  • Known, documented mid-escape trade-off: if a process dies/idles exactly mid-escape and never sends the continuation, the re-armed tail eats the next unrelated output byte. This is strictly narrower than the bug it fixes (pre-fix such a stream just dropped the partial); the snapshot-seq accounting guarantees the normal live case completes with no eaten byte. Both cases are pinned by tests.

Tests

  • terminal-query-reply.test.ts — classifier grammar (matches all reply types; rejects arrows/function-keys/paste/typed text).
  • remote-runtime-pty-query-reply-immediate.test.ts — reply sent immediately vs typed input debounced by 8ms.
  • repro-7329-remote-snapshot-corruption.test.ts — mid-escape repro against the real daemon serializer + real xterm; plus the contiguous-continuation safety proof and the documented idle-death edge.
  • terminal-partial-escape-tail.test.ts — module (fold-safe invariant + cap).
  • terminal-multiplex-escape-tail.test.ts — pendingEscapeTailAnsi rides the real terminal.multiplex wire.

tsc clean, oxlint clean, max-lines ratchet OK. Targeted (512) + daemon (661) + ipc (1432) suites green.

Verification gap

Verified against the real daemon serializer, real xterm, and the real terminal.multiplex RPC wire, but not driven end-to-end through a live Electron + remote-runtime session. Would appreciate the reporter confirming on a build with this change.

Made with Orca 🐋


Folded in: #7279 — repaint remote snapshot at its serialized grid width

A separate, adjacent bug (same subsystem, two overlapping files) was folded into this PR to ship once and avoid a later conflict — a layout/grid-width bug, distinct from the #7329 query-reply/mid-escape byte-timing fixes above.

Bug: on remote snapshot reattach, the renderer wrote the daemon's serialized soft-wrapped ANSI at the pane's current cols, ignoring connectResult.snapshotCols/snapshotRows. When the local pane grid drifted from the daemon grid (SSH reconnect, resize between disconnect and reattach), soft-wrapped lines rewrap one cell early/late and wide emoji wrap a column off.

Fix: resize the pane to snapshotCols/snapshotRows before replaying, guarded by suppressSnapshotReplayPtyResize so the layout-only resize does not SIGWINCH the live remote TUI; the existing safeFit then fits the pane back and resizes the remote PTY. Mirrors applyMainBufferSnapshot (which already did this for the hidden-output-restore path). snapshotCols/snapshotRows were already plumbed end-to-end; this path just wasn't consuming them.

Also fixes a latent typecheck-only gap in the #7329 code: applyMainBufferSnapshot's inline snapshot param type was missing pendingEscapeTailAnsi?: string that the mid-escape restore referenced (typecheck:web — a stricter tsgo config than plain tsc -p tsconfig.json — caught it).

Verification: regression test resizes the pane to the snapshot grid before replaying daemon snapshot bytes (bug #7279) asserts resize(snapshotCols, snapshotRows) fires before the snapshot write, and fails without the resize (independently confirmed). Full pty-connection.test.ts 332/332 green; pnpm typecheck (node + cli + web) green; #7329 suites still green.

Fixes #7279.

Jinwoo-H added 2 commits July 7, 2026 15:19
…rrupt input (#7329)

On the remote-server (remote-runtime) path, terminal query replies — OSC 10/11
color, CPR/DSR cursor reports, DA device attributes, pixel-size, mode 2031 —
were routed through the 8ms input debounce (REMOTE_TERMINAL_INPUT_FLUSH_MS).
A querying program (e.g. starship/orb) reads these replies synchronously in
raw mode with a short timeout, so the debounced reply missed that window and
landed on the shell prompt in cooked mode: the shell echoed it literally
(`^[]11;rgb:...^[\`, `^[[3;1R`) and spliced it into the next typed line
(`...Ryes`). The local path drains promptly and never corrupts.

Fix: classify synthetic query replies (isTerminalQueryReply) and add
transport.sendInputImmediate — on the remote transport it flushes pending
batched input (preserving byte order) then sends the reply without arming the
debounce timer; on the local transport it is sendInput (already prompt).
Routed the capability/OSC/pixel/mode2031 reply call-sites plus native
CPR/DSR/DA replies (which arrive via xterm's onData) through it. Ordinary
typed input — including bursty arrow-key auto-repeat — stays coalesced.

Also fixes a separate mid-escape snapshot bug in the same family: a PTY read
ending mid-escape leaves bytes in the emulator's parser, so SerializeAddon
drops them and the next live chunk's continuation renders literally after a
snapshot restore. The headless emulator now tracks the trailing partial
(terminal-partial-escape-tail.ts) and ships it as
TerminalSnapshot.pendingEscapeTailAnsi; the restorer writes it LAST (after the
post-replay reset) so the live continuation completes it. Threaded through both
the remote terminal.multiplex snapshot path and the local hidden-reveal
(getMainBufferSnapshot) path.

Tests: query-reply classifier grammar; immediate-vs-debounced remote send;
mid-escape repro against the real daemon serializer + real xterm; the
pending-escape-tail module (fold-safe + cap); transport wire threading.
…7279)

Folds the #7279 fix into this PR (was a separate branch). Distinct bug from
the #7329 query-reply/mid-escape corruption already here, same subsystem.

Root cause: the renderer snapshot-reattach path wrote the daemon's serialized
soft-wrapped ANSI at the pane's CURRENT cols, ignoring connectResult
.snapshotCols/snapshotRows. When the remote daemon grid differs from the local
pane (SSH reconnect, window resize between disconnect and reattach), lines
rewrap one cell early/late and wide emoji wrap a column off.

Fix: resize the pane to snapshotCols/snapshotRows before replaying the snapshot,
guarded by suppressSnapshotReplayPtyResize so the layout-only resize does not
SIGWINCH the live remote TUI. The existing safeFit fits the pane back and
resizes the remote PTY afterward. Mirrors applyMainBufferSnapshot, which
already did this for the hidden-output-restore path.

Also: add pendingEscapeTailAnsi to applyMainBufferSnapshot's local param type
(this PR referenced snapshot.pendingEscapeTailAnsi but the inline type omitted
it, so typecheck:web was red before this commit).

Validated e2e over a real SSH Docker target: real remote PTY -> daemon headless
serialize (source=headless, cols=80) -> replay at drifted 79 cols tears, replay
at snapshotCols=80 restores identity. Regression test added (fails without the
resize). Full pty-connection suite 332/332 green; typecheck:web green.
@Jinwoo-H

Jinwoo-H commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

🤝 Folded in the #7279 fix (commit b4a71e6)

Heads up — I merged a separate but adjacent bug fix into this branch so we ship one PR instead of two. It's a distinct bug from the #7329 query-reply/mid-escape corruption this PR already fixes, but same subsystem (remote terminal repaint) and it touched two of the same files, so a single PR avoids a later conflict.

What #7279 is: remote snapshot reattach repaints soft-wrapped lines / wide emoji one cell off — a layout (grid-width) bug, not a byte-timing bug.

What I changed:

  1. pty-connection.ts — the connectResult?.snapshot reattach branch (~line 5400). Before replaying the daemon snapshot, resize the pane to connectResult.snapshotCols/snapshotRows, guarded by suppressSnapshotReplayPtyResize (so the layout-only resize doesn't SIGWINCH the live remote TUI). The daemon serializes soft-wrapped lines as continuous text; replaying at the pane's current cols rewraps them. This mirrors what applyMainBufferSnapshot already did for the hidden-output-restore path. snapshotCols/snapshotRows were already plumbed end-to-end (daemon-pty-adapter.ts → transport → PtyConnectResult); this path just wasn't consuming them.

  2. pty-connection.ts — one-line type fix in applyMainBufferSnapshot (your code, not mine): added pendingEscapeTailAnsi?: string to its inline snapshot param type. typecheck:web was already red on this branch before my change — snapshot.pendingEscapeTailAnsi (lines ~5024/5029, your mid-escape fix) referenced a field the local param type omitted. It's declared on the wire (daemon/types.ts), preload, and pty-transport-types.ts, just not on that inline literal. Flagging since I edited your code — please sanity-check it's the field you intended.

  3. pty-connection.test.ts — regression test resizes the pane to the snapshot grid before replaying daemon snapshot bytes (bug #7279). Asserts resize(snapshotCols, snapshotRows) fires before the snapshot write. Verified it fails without the resize.

No overlap with your logic: my change is at the snapshot-reattach block; yours is at the query-reply routing (sendInputImmediate, ≤ line 5282) and the pendingEscapeTailAnsi restore. They coexist cleanly.

Verification:

PR body: you'll want to update the title/description to cover both #7329 and #7279 (currently it only mentions #7329). Pre-commit hooks (oxlint/oxfmt) passed. Didn't touch anything else on your branch.

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

This PR adds partial ANSI escape-tail tracking across PTY writes and snapshot restore paths, and threads pendingEscapeTailAnsi through daemon snapshots, runtime serialization, IPC/preload payloads, and renderer replay handling. It also adds sendInputImmediate for terminal query replies and routes several query-reply paths through that immediate send path. Regression tests cover escape-tail parsing, snapshot threading, replay restoration, resize ordering, and immediate reply behavior.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed Clear, specific, and aligned with the main changes: remote query-reply corruption plus snapshot repaint fix.
Description check ✅ Passed Mostly complete and highly detailed, though it omits the Screenshots, AI Review Report, and Security Audit sections from the template.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 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: 1

Caution

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

⚠️ Outside diff range comments (2)
src/renderer/src/components/terminal-pane/pty-connection.ts (1)

4978-5030: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Compile break: applyMainBufferSnapshot param type is missing pendingEscapeTailAnsi.

Line 5024 reads snapshot.pendingEscapeTailAnsi, but the parameter type declared at Lines 4978-4984 does not include that property, so this fails type-checking (confirmed by the verify check failing at 5025/5030). Beyond the compile error, the field must be typed here for the tail to actually reach the replay write — serializeHiddenOutputSnapshot returns a PtyBufferSnapshot that now carries it.

Proposed fix
     function applyMainBufferSnapshot(snapshot: {
       data: string
       cols: number
       rows: number
       seq?: number
       alternateScreen?: boolean
+      pendingEscapeTailAnsi?: string
     }): void {

Source: Linters/SAST tools

src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts (1)

421-430: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Add pendingEscapeTailAnsi to requestSnapshot. The request-based snapshot path already resolves that field, but this return type drops it from the snapshot shape.

🧹 Nitpick comments (1)
src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts (1)

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

Solid regression test; consider also covering the explicit SnapshotRequest path.

This nicely pins the subscribe-time SnapshotStart threading behavior for #7329. The other call site that also injects pendingEscapeTailAnsi — sendRequestedSnapshot in terminal.ts (triggered by the SnapshotRequest opcode, used for renderer-initiated re-snapshot/resize scenarios) — isn't exercised by any test in this diff. Given this bug's history (silently regressing terminal rendering), extending coverage to that second call site would close the remaining gap identified in the sibling terminal.ts review comment.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7c119fa7-acf0-40b2-969a-26f3bc0c828f

📥 Commits

Reviewing files that changed from the base of the PR and between 0f7658d and cb34dcb.

📒 Files selected for processing (20)
  • src/main/daemon/headless-emulator.ts
  • src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts
  • src/main/daemon/types.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-multiplex-escape-tail.test.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.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.ts
  • src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts
  • src/shared/terminal-partial-escape-tail.test.ts
  • src/shared/terminal-partial-escape-tail.ts
  • src/shared/terminal-query-reply.test.ts
  • src/shared/terminal-query-reply.ts

@Jinwoo-H Jinwoo-H changed the title fix(terminal): send remote query replies immediately so they don't corrupt input (#7329) fix(terminal): remote query-reply corruption (#7329) + snapshot grid-width repaint (#7279) Jul 7, 2026
@Jinwoo-H

Jinwoo-H commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

✅ Reviewed and validated the #7279 fold-in — it's correct and I confirmed all three claims independently:

  1. The typecheck fix was real and necessary. I checked out my pre-fold-in commit (cb34dcb2e) and ran pnpm typecheck:web against it — it was genuinely red with two TS2339 errors at pty-connection.ts:5024/5029 (Property 'pendingEscapeTailAnsi' does not exist on ...). My own verification missed this because I was running tsc -p tsconfig.json (a project-references solution config that doesn't deep-check the renderer sources) instead of the real gate pnpm typecheck / typecheck:web (tsgo -p config/tsconfig.tc.web.json, which includes src/renderer/src/**/*). The added pendingEscapeTailAnsi?: string on applyMainBufferSnapshot's inline type is exactly the field I intended. Thanks for catching it.

  2. The [Bug] Remote sessions repaint terminal output with different cell layout #7279 resize logic is sound. Verified the suppressSnapshotReplayPtyResize guard actually short-circuits forwardPtyResize in the onResize handler (so the layout-only resize doesn't SIGWINCH the remote TUI), and that safeFit(pane) + transport.resize(...) afterward restore the pane to real dims and forward them to the remote PTY. It correctly mirrors applyMainBufferSnapshot.

  3. The regression test is meaningful. Reverted only the [Bug] Remote sessions repaint terminal output with different cell layout #7279 resize hunk and confirmed resizes the pane to the snapshot grid before replaying daemon snapshot bytes (bug #7279) fails without it, then restored.

Full state on current HEAD (b4a71e67f): pnpm typecheck (node + cli + web) green, oxlint clean, pty-connection.test.ts 332/332, all #7329 suites green. Working tree matches HEAD.

Updated the PR title + description to cover both #7279 and #7329. No changes needed to your fold-in.

Jinwoo-H and others added 2 commits July 7, 2026 17:12
…e states

CodeRabbit review: CAN (0x18) and SUB (0x1a) abort an in-progress escape
sequence back to ground in xterm's VT500 parser. extractPartialEscapeTail
handled this for the csi/osc/string states but not esc/escIntermediate, so
`ESC CAN` and `ESC <intermediate> CAN` left a bogus tail that would re-arm on
restore and eat the next output byte. Handle CAN/SUB before the generic C0
branch in both states. Adds tests incl. fold-safety across the CAN abort.

Co-authored-by: Orca <[email protected]>
…ixes

- sendInputImmediate: when a large paste is still in the batcher's async
  byte-length validation (validationTail), its bytes are not yet in `pending`
  and takePending() cannot see them. Bypassing the queue then would send a
  query reply ahead of the paste and reorder bytes on the wire. Detect pending
  validation (new inputBatcher.hasPendingValidation()) and route the reply
  through the ordered queue in that rare window instead. Regression test added
  (fails without the guard).

- Local daemon reattach dropped snapshot.pendingEscapeTailAnsi: the mid-escape
  tail fix covered the remote-multiplex and hidden-reveal paths but not the
  local daemon reattach path (daemon-pty-adapter built PtyConnectResult without
  the field). Thread it through PtyConnectResult -> adapter -> connect() ->
  the connectResult.snapshot replay, writing it LAST after the reset. Test added.

- onData query-reply branch: drop the redundant `!pendingTerminalInputIntent`
  guard. The only intents are plain-escape (\x1b) and ctrl-c (\x03); neither can
  satisfy isTerminalQueryReply (needs length >= 3 + a full reply grammar), so a
  real keystroke never reaches the branch. The guard only created a latency gap
  where a reply overlapping a keydown fell back onto the debounced path.

- isTerminalQueryReply: DECRPM_RE now also matches ANSI (non-private) mode
  reports `CSI Ps;Pm $ y` (no leading `?`), not just private DECRPM.

Also (prior commit) CAN/SUB abort in esc/escIntermediate states, per CodeRabbit.
@Jinwoo-H

Jinwoo-H commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

🔍 Code-review pass (self + CodeRabbit) — findings addressed

Ran a high-recall multi-angle review over the diff. Findings and resolutions:

Fixed (correctness):

  1. sendInputImmediate byte-ordering vs in-flight paste — a paste over the async byte-length-measurement threshold sits in the batcher's validationTail, invisible to takePending(). Bypassing the queue could send a query reply ahead of the paste and reorder bytes. Now detects pending validation (inputBatcher.hasPendingValidation()) and routes the reply through the ordered queue in that rare window. Regression test fails without the guard.
  2. Local daemon reattach dropped pendingEscapeTailAnsi — the mid-escape tail fix covered the remote-multiplex and hidden-reveal paths but not the local daemon reattach path (daemon-pty-adapter built PtyConnectResult without the field). Threaded it end-to-end and write it after the reset on the connectResult.snapshot replay. Regression test added (fails without it).
  3. CAN/SUB abort (CodeRabbit) — extractPartialEscapeTail treated CAN (0x18)/SUB (0x1a) as still-pending in the esc/escIntermediate states, leaving a bogus tail. Now aborts to ground like xterm's VT500 parser, in all states. Tests added incl. fold-safety across the abort.

Fixed (robustness):
4. onData query-reply routing — dropped a redundant !pendingTerminalInputIntent guard that created a latency gap when a reply overlapped a keydown (a real keystroke can never match isTerminalQueryReply, so the guard was unnecessary).
5. DECRPM grammar — isTerminalQueryReply now also matches ANSI (non-private) mode reports CSI Ps;Pm $ y, not just private CSI ? … $ y.

Reviewed & rejected (not bugs):

  • Coalesced multi-replies in one onData — xterm fires onData once per reply as it parses, so the anchored single-reply grammars are correct.
  • Altitude (6 call-sites + onData branch vs one transport choke-point) — a choke-point would run the classifier on all typed input; the current caller-expresses-intent design is the cleaner altitude.
  • Reuse — isTerminalQueryReply classifies replies (renderer→PTY); the existing is*RendererReplyCsiQuery classify queries (PTY→renderer). Different direction/grammar; no genuine duplication.

Noted, not changed (low-value cleanup): sendInputImmediate and the #7279 resize each share a few lines with a sibling (sendInputAccepted flush / applyMainBufferSnapshot); extracting a helper is optional and I kept the explicit forms for clarity.

Commits: fd2a10e2e (CAN/SUB), eb38d5f68 (review fixes). pnpm typecheck (node+cli+web) green, oxlint clean, affected suites + full daemon suite green.

@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/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts (1)

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

Fixed real-timer wait may be flaky under CI load.

await new Promise((resolve) => setTimeout(resolve, 20)) assumes the async byte-length measurement (and subsequent flush chain) always settles within 20ms of real time. Under slower/loaded CI runners this margin could be too tight, causing an intermittent false failure. Since Vitest 4 supports vi.waitFor, prefer polling for the expected condition instead of a fixed delay.

♻️ Suggested refactor using vi.waitFor
-    // Let validation + flush settle.
-    await new Promise((resolve) => setTimeout(resolve, 20))
-
-    const sends = terminalSendCalls() as { params: { text: string } }[]
-    const combined = sends.map((s) => s.params.text).join('')
-    // The paste bytes must come before the reply — no reordering.
-    expect(combined.indexOf('p')).toBeLessThan(combined.indexOf('\x1b[3;1R'))
-    expect(combined).toContain(`${paste}\x1b[3;1R`)
+    // Let validation + flush settle.
+    await vi.waitFor(() => {
+      const sends = terminalSendCalls() as { params: { text: string } }[]
+      const combined = sends.map((s) => s.params.text).join('')
+      expect(combined).toContain(`${paste}\x1b[3;1R`)
+    })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a54091a9-841c-491b-92ac-ec3b40018150

📥 Commits

Reviewing files that changed from the base of the PR and between b4a71e6 and eb38d5f.

📒 Files selected for processing (12)
  • src/main/daemon/daemon-pty-adapter.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-transport.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.ts
  • src/shared/terminal-partial-escape-tail.test.ts
  • src/shared/terminal-partial-escape-tail.ts
  • src/shared/terminal-query-reply.test.ts
  • src/shared/terminal-query-reply.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • src/shared/terminal-query-reply.ts
  • src/shared/terminal-query-reply.test.ts
  • src/shared/terminal-partial-escape-tail.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts
  • src/shared/terminal-partial-escape-tail.ts
  • src/renderer/src/components/terminal-pane/pty-transport-types.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts

Jinwoo-H and others added 2 commits July 7, 2026 19:28
…ery replies (#7329)

xterm.js also emits DECXCPR (CSI ? y;x R), text-area size reports (CSI 8;h;w t,
answer to CSI 18t), kitty keyboard flag reports (CSI ? flags u — crossterm
probes this at startup), and DCS-framed DECRQSS/XTVERSION reports through the
same onData stream. Those replies still sat behind the remote input debounce
and corrupted the same way CPR did. Extends the reply grammars, documents the
accepted modified-F3/CPR collision, and pins kitty CSI-u keystrokes and
modified F1/F2/F4 as non-replies.

Co-authored-by: Orca <[email protected]>
…g + tail plumbing

Review follow-ups on #7736, each verified to fail with its fix hunk reverted:

- Replace the paste-reorder test's fixed 20ms sleep with expect.poll — the
  reply legitimately trails async paste validation plus one debounce tick, and
  the sleep raced that chain under CI load (~50% failure in parallel runs).
- Pin the onData routing decision itself: a native CPR reply must reach
  transport.sendInputImmediate while typed input and arrow keys stay on the
  debounced sendInput path. The mock's sendInputImmediate delegates to the
  sendInput spy, so no existing test could tell the two apart — reverting the
  whole renderer half of #7329 previously kept the suite green.
- Pin the client-side pendingEscapeTailAnsi chain end to end: real SnapshotStart
  /Chunk/End frames through the real multiplexer into the real transport must
  surface the tail in onReplayData meta (kills the decodeSnapshotInfo,
  onSnapshot-meta, and processData-meta links), the drainReplayDataQueue
  consumer must write the tail after the replayed bytes, and the local IPC
  connect result must thread the field from the spawn result.

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

Jinwoo-H commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Independent verification (skeptical re-review from scratch)

Verdict: land. Diagnosis confirmed, every fix hunk mutation-tested, and the reporter's exact corruption reproduced live pre-fix / clean post-fix. Two review findings were fixed in the follow-up commits on this branch.

Diagnosis — confirmed live

Stood up a real headless orca serve + paired dev client (Playwright over CDP typing into the real renderer → terminal.multiplex → daemon → PTY):

  • Query-reply latency with fix: 7.0–9.4ms; with sendInputImmediate reverted to the batcher: 15.6–18.8ms — exactly the REMOTE_TERMINAL_INPUT_FLUSH_MS debounce delta, on both OSC 11 and CPR.
  • A raw-mode program querying OSC 11 + CSI 6n with a 12ms read window: pre-fix got 0 reply bytes and the late reply echoed onto the cooked-mode prompt, splicing with typed input as $ 11;rgb:ffff/ffff/ffff;1Ryes (the issue screenshot's ^[[3;1Ryes), then executed as garbage commands. Post-fix: 31 reply bytes inside the window, clean prompt.
  • Local path verified debounce-free by code reading (pty-input-write-queue drains a lone item in the same task).

Mutation testing — each hunk reverted alone, its test fails, restored

immediate-vs-debounced send · hasPendingValidation ordering guard · local-reattach pendingEscapeTailAnsi write-after-reset · #7279 resize-before-replay · CAN/SUB abort in esc/escIntermediate · emulator snapshot tail field · SnapshotStart wire threading.

Follow-up commits pushed to this branch

  • 3f9d73790 — classifier also matches DECXCPR, CSI 18t reply, kitty flags report (CSI ? Ps u, crossterm probes at startup), and DCS DECRQSS/XTVERSION — all emitted by xterm.js through the same onData stream and previously still debounced. Documents the accepted modified-F3/CPR collision and pins kitty CSI-u keystrokes as non-replies.
  • 6cb388239 — test hardening: de-flaked the paste-reorder test (fixed 20ms sleep raced async validation + debounce, ~50% failure under parallel load); pinned the onData routing decision (previously reverting the entire renderer half of [Bug] Remote server + terminal work #7329 kept all 333 pty-connection tests green — the mock delegated sendInputImmediate to the sendInput spy); pinned the client-side tail chain end-to-end (real binary frames → multiplexer decode → transport → onReplayData meta → drain-writes-tail-last → local IPC connect-result threading). All new tests verified to fail with their fix hunks reverted.

Checks on this branch

pnpm typecheck (node+cli+web) green · oxlint green · max-lines ratchet green · 1611 affected terminal/daemon/rpc/shared tests green, previously-flaky combo green 3×3 consecutive runs. The earlier verify CI failure was an apt-mirror infra flake, unrelated to the code.

@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 (2)
src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts (1)

29-47: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider restoring globals after the test.

vi.stubGlobal('window', ...) is set in beforeEach but there's no corresponding vi.unstubAllGlobals()/afterEach in this file. Low risk today since the describe block has a single test, but worth adding for robustness if more tests are appended later.

src/renderer/src/components/terminal-pane/pty-connection.test.ts (1)

5243-5272: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Routing test relies on a self-acknowledged mock limitation.

Since sendInputImmediate delegates to the sendInput spy, calling the immediate path also records a call on sendInput. The assertions here still pass because toHaveBeenCalledWith doesn't assert exclusivity, and the test comment already flags this limitation. No action needed given the explicit documentation, but worth keeping in mind if this test is later refactored to assert sendInput was not called with the reply bytes.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 05cb2fae-dc5e-460a-9750-fda010da207e

📥 Commits

Reviewing files that changed from the base of the PR and between eb38d5f and 6cb3882.

📒 Files selected for processing (6)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-transport.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-snapshot-escape-tail.test.ts
  • src/shared/terminal-query-reply.test.ts
  • src/shared/terminal-query-reply.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts
  • src/shared/terminal-query-reply.ts

@Jinwoo-H
Jinwoo-H merged commit 79d0de9 into main Jul 7, 2026
2 checks passed
@Jinwoo-H
Jinwoo-H deleted the Jinwoo-H/bug-7329-remote-term-corruption branch July 7, 2026 23:42
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 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] Remote server + terminal work [Bug] Remote sessions repaint terminal output with different cell layout

1 participant