Repository navigation
fix(terminal): remote query-reply corruption (#7329) + snapshot grid-width repaint (#7279) - #7736
Conversation
…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.
🤝 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:
No overlap with your logic: my change is at the snapshot-reattach block; yours is at the query-reply routing ( 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. |
📝 WalkthroughWalkthroughChangesThis PR adds partial ANSI escape-tail tracking across PTY writes and snapshot restore paths, and threads 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
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 winCompile break:
applyMainBufferSnapshotparam type is missingpendingEscapeTailAnsi.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 theverifycheck failing at 5025/5030). Beyond the compile error, the field must be typed here for the tail to actually reach the replay write —serializeHiddenOutputSnapshotreturns aPtyBufferSnapshotthat 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 winAdd
pendingEscapeTailAnsitorequestSnapshot. 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 winSolid regression test; consider also covering the explicit
SnapshotRequestpath.This nicely pins the subscribe-time
SnapshotStartthreading behavior for#7329. The other call site that also injectspendingEscapeTailAnsi—sendRequestedSnapshotinterminal.ts(triggered by theSnapshotRequestopcode, 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 siblingterminal.tsreview comment.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 7c119fa7-acf0-40b2-969a-26f3bc0c828f
📒 Files selected for processing (20)
src/main/daemon/headless-emulator.tssrc/main/daemon/repro-7329-remote-snapshot-corruption.test.tssrc/main/daemon/types.tssrc/main/ipc/pty.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/terminal.tssrc/main/runtime/rpc/terminal-multiplex-escape-tail.test.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/renderer/src/runtime/remote-runtime-terminal-multiplexer.tssrc/shared/terminal-partial-escape-tail.test.tssrc/shared/terminal-partial-escape-tail.tssrc/shared/terminal-query-reply.test.tssrc/shared/terminal-query-reply.ts
|
✅ Reviewed and validated the #7279 fold-in — it's correct and I confirmed all three claims independently:
Full state on current HEAD ( Updated the PR title + description to cover both #7279 and #7329. No changes needed to your fold-in. |
…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.
🔍 Code-review pass (self + CodeRabbit) — findings addressedRan a high-recall multi-angle review over the diff. Findings and resolutions: Fixed (correctness):
Fixed (robustness): Reviewed & rejected (not bugs):
Noted, not changed (low-value cleanup): Commits: |
There was a problem hiding this comment.
🧹 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 winFixed 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 supportsvi.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
📒 Files selected for processing (12)
src/main/daemon/daemon-pty-adapter.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-batching.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/shared/terminal-partial-escape-tail.test.tssrc/shared/terminal-partial-escape-tail.tssrc/shared/terminal-query-reply.test.tssrc/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
…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]>
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 liveStood up a real headless
Mutation testing — each hunk reverted alone, its test fails, restoredimmediate-vs-debounced send · Follow-up commits pushed to this branch
Checks on this branch
|
There was a problem hiding this comment.
🧹 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 valueConsider restoring globals after the test.
vi.stubGlobal('window', ...)is set inbeforeEachbut there's no correspondingvi.unstubAllGlobals()/afterEachin 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 valueRouting test relies on a self-acknowledged mock limitation.
Since
sendInputImmediatedelegates to thesendInputspy, calling the immediate path also records a call onsendInput. The assertions here still pass becausetoHaveBeenCalledWithdoesn'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 assertsendInputwas 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
📒 Files selected for processing (6)
src/renderer/src/components/terminal-pane/pty-connection.test.tssrc/renderer/src/components/terminal-pane/pty-transport.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.tssrc/shared/terminal-query-reply.test.tssrc/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
…ot grid-width repaint (stablyai#7279) (stablyai#7736) Co-authored-by: Orca <[email protected]>
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:^[]11;rgb:...^[\is a complete OSC 11 background-color reply and^[[3;1Ris a complete CPR cursor-position reply — both are xterm's answers to the prompt's queries, and both are echoed literally and mixed into theyesthe 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
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.transport.sendInputImmediate(data):sendInput(already prompt).installTerminalCapabilityReplyHandlers), pixel-size, mode 2031, hidden/foreground OSC color, and the native CPR/DSR/DA replies that arrive mixed with keystrokes via xterm'sonData.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
SerializeAddondrops 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 asTerminalSnapshot.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 remoteterminal.multiplexsnapshot path and the local hidden-reveal (getMainBufferSnapshot) path.Not ported: the DECSC saved-cursor (Bug D) fix — it depends on an unmerged
serializeWithAbsoluteCursorserialization subsystem that has diverged significantly frommain; porting it is disproportionate risk and it is not implicated by this report.Regression notes
sendInputImmediateis 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).pendingEscapeTailAnsiis an optional, backward-compatible wire field (old daemon omits it, old renderer ignores it — noPROTOCOL_VERSIONbump).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—pendingEscapeTailAnsirides the realterminal.multiplexwire.tscclean,oxlintclean, 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.multiplexRPC 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/snapshotRowsbefore replaying, guarded bysuppressSnapshotReplayPtyResizeso the layout-only resize does not SIGWINCH the live remote TUI; the existingsafeFitthen fits the pane back and resizes the remote PTY. MirrorsapplyMainBufferSnapshot(which already did this for the hidden-output-restore path).snapshotCols/snapshotRowswere 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 inlinesnapshotparam type was missingpendingEscapeTailAnsi?: stringthat the mid-escape restore referenced (typecheck:web— a strictertsgoconfig than plaintsc -p tsconfig.json— caught it).Verification: regression test
resizes the pane to the snapshot grid before replaying daemon snapshot bytes (bug #7279)assertsresize(snapshotCols, snapshotRows)fires before the snapshot write, and fails without the resize (independently confirmed). Fullpty-connection.test.ts332/332 green;pnpm typecheck(node + cli + web) green; #7329 suites still green.Fixes #7279.