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

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-07-07 16:42:43 -07:00
committed by GitHub
co-authored by Orca
parent c256a5a417
commit 79d0de9c33
24 changed files with 1412 additions and 23 deletions
@@ -0,0 +1,86 @@
import { describe, expect, it } from 'vitest'
import {
advancePartialEscapeTail,
extractPartialEscapeTail,
MAX_PARTIAL_ESCAPE_TAIL_LENGTH
} from './terminal-partial-escape-tail'
describe('extractPartialEscapeTail', () => {
it('returns empty for parser-clean streams', () => {
expect(extractPartialEscapeTail('')).toBe('')
expect(extractPartialEscapeTail('plain text no escapes')).toBe('')
expect(extractPartialEscapeTail('\x1b[38;5;196mred\x1b[0m done')).toBe('')
expect(extractPartialEscapeTail('\x1b[2J\x1b[H')).toBe('')
})
it('returns the dangling CSI when a chunk ends mid-sequence', () => {
expect(extractPartialEscapeTail('hello\x1b[3')).toBe('\x1b[3')
expect(extractPartialEscapeTail('a\x1b[38;5;')).toBe('\x1b[38;5;')
expect(extractPartialEscapeTail('\x1b')).toBe('\x1b')
expect(extractPartialEscapeTail('\x1b[')).toBe('\x1b[')
})
it('returns the dangling OSC (unterminated) sequence', () => {
// OSC 0 title with no BEL/ST terminator yet.
expect(extractPartialEscapeTail('\x1b]0;my-title')).toBe('\x1b]0;my-title')
// Terminated OSC is clean.
expect(extractPartialEscapeTail('\x1b]0;title\x07after')).toBe('')
expect(extractPartialEscapeTail('\x1b]0;title\x1b\\after')).toBe('')
})
it('treats a fresh ESC as aborting a pending CSI', () => {
// The second ESC starts a new (complete) sequence.
expect(extractPartialEscapeTail('\x1b[3\x1b[0m')).toBe('')
// ...and a new dangling one.
expect(extractPartialEscapeTail('\x1b[3\x1b[')).toBe('\x1b[')
})
it('treats CAN/SUB as aborting an in-progress escape back to ground', () => {
// CAN (0x18) / SUB (0x1a) abort the sequence in xterm's VT500 parser.
// esc state:
expect(extractPartialEscapeTail('\x1b\x18')).toBe('') // ESC CAN
expect(extractPartialEscapeTail('\x1b\x1a')).toBe('') // ESC SUB
// escIntermediate state (ESC then an intermediate byte, then CAN):
expect(extractPartialEscapeTail('\x1b \x18')).toBe('') // ESC SP CAN
expect(extractPartialEscapeTail('\x1b#\x1a')).toBe('') // ESC # SUB
// csi/osc/string already aborted — keep them green:
expect(extractPartialEscapeTail('\x1b[38;\x18')).toBe('') // CSI ... CAN
expect(extractPartialEscapeTail('\x1b]0;title\x18')).toBe('') // OSC ... CAN
// A CAN that aborts, followed by a fresh dangling sequence, tracks the new one:
expect(extractPartialEscapeTail('\x1b\x18\x1b[3')).toBe('\x1b[3')
})
it('is fold-safe across chunk boundaries', () => {
// extract(a + b) === extract(extract(a) + b) — the invariant ingest relies on.
const cases: [string, string][] = [
['first\x1b[3', '8;5;196mred'],
['\x1b', '[0m'],
['\x1b]0;ti', 'tle\x07'],
['clean', '\x1b[1'],
// Fold-safety must hold across the CAN abort too.
['\x1b', '\x18after'],
['\x1b ', '\x18after']
]
for (const [a, b] of cases) {
expect(extractPartialEscapeTail(extractPartialEscapeTail(a) + b)).toBe(
extractPartialEscapeTail(a + b)
)
}
})
})
describe('advancePartialEscapeTail', () => {
it('accumulates a split sequence across chunks', () => {
let tail = ''
tail = advancePartialEscapeTail(tail, 'ls\r\n\x1b[3')
expect(tail).toBe('\x1b[3')
tail = advancePartialEscapeTail(tail, '8;5;196m')
expect(tail).toBe('') // sequence completed
})
it('abandons tracking (returns empty) past the cap', () => {
// An unterminated OSC longer than the cap degrades to pre-fix behavior.
const huge = `\x1b]0;${'x'.repeat(MAX_PARTIAL_ESCAPE_TAIL_LENGTH + 10)}`
expect(advancePartialEscapeTail('', huge)).toBe('')
})
})
+149
View File
@@ -0,0 +1,149 @@
// Why this module exists: a PTY read can end mid-escape-sequence. The bytes
// already handed to xterm sit inside its parser state machine, not the screen
// buffer, so a serialized snapshot cannot carry them — and the next chunk's
// continuation bytes then render as literal text after a snapshot restore
// (Bug E in notes/garble-fuzz-divergences.md). Tracking the unparsed trailing
// partial sequence at the ingest boundary lets snapshot producers append it
// after the serialized screen so the continuation completes exactly as live.
// Mirrors the VT500 parser states that can span a chunk boundary. C0 controls
// (except ESC/CAN/SUB) execute mid-sequence without aborting it, matching
// xterm's state machine.
type ScanState =
| 'ground'
| 'esc'
| 'escIntermediate'
| 'csi'
| 'osc'
| 'oscEsc'
| 'string'
| 'stringEsc'
const ESC = 0x1b
const CAN = 0x18
const SUB = 0x1a
const BEL = 0x07
// Why a cap: OSC/DCS payloads are unbounded and an unterminated one would
// grow the tracked tail (and every snapshot) without limit. Real payloads
// (titles, cwd, hyperlinks) are far below this; beyond it we stop tracking
// and degrade to the pre-fix behavior for that pathological stream.
export const MAX_PARTIAL_ESCAPE_TAIL_LENGTH = 4096
/** ESC-state transition shared by the fresh-ESC and abort-reprocess paths. */
function stateAfterEscByte(code: number): ScanState {
if (code === 0x5b) {
return 'csi' // [
}
if (code === 0x5d) {
return 'osc' // ]
}
// P / X / ^ / _ open DCS / SOS / PM / APC — ST-terminated strings.
if (code === 0x50 || code === 0x58 || code === 0x5e || code === 0x5f) {
return 'string'
}
if (code >= 0x20 && code <= 0x2f) {
return 'escIntermediate'
}
if (code < 0x20 || code === 0x7f) {
return 'esc' // C0 executes / DEL is ignored mid-sequence; ESC via callers
}
return 'ground' // final byte — two-byte sequence (ESC 7, ESC 8, ESC c, …)
}
/** Returns the trailing incomplete escape sequence of `stream` ('' when the
* stream ends parser-clean). Fold-safe across chunk boundaries:
* extract(a + b) === extract(extract(a) + b), which is how ingest-time
* trackers advance without keeping the whole stream. */
export function extractPartialEscapeTail(stream: string): string {
let state: ScanState = 'ground'
let start = 0
for (let i = 0; i < stream.length; i++) {
const code = stream.charCodeAt(i)
if (state === 'ground') {
if (code === ESC) {
start = i
state = 'esc'
}
continue
}
if (
code === ESC &&
state !== 'osc' &&
state !== 'string' &&
state !== 'oscEsc' &&
state !== 'stringEsc'
) {
// ESC aborts a pending ESC/CSI sequence and starts a new one.
start = i
state = 'esc'
continue
}
// CAN/SUB abort an in-progress escape sequence back to ground in every
// non-string state (xterm's VT500 parser). The csi/osc/string cases handle
// this inline below; esc/escIntermediate must too, or `ESC CAN` and
// `ESC <intermediate> CAN` leave a bogus tail instead of dropping to ground.
if ((code === CAN || code === SUB) && (state === 'esc' || state === 'escIntermediate')) {
state = 'ground'
continue
}
switch (state) {
case 'esc':
state = stateAfterEscByte(code)
break
case 'escIntermediate':
if (code >= 0x30 && code <= 0x7e) {
state = 'ground'
}
// 0x20–0x2f stays; other C0 executes and stays (CAN/SUB handled above).
break
case 'csi':
if (code === CAN || code === SUB) {
state = 'ground'
} else if (code >= 0x40 && code <= 0x7e) {
state = 'ground' // final byte completes the CSI
}
// params/intermediates (0x20–0x3f), C0, DEL stay in-sequence.
break
case 'osc':
if (code === BEL || code === CAN || code === SUB) {
state = 'ground'
} else if (code === ESC) {
state = 'oscEsc'
}
break
case 'oscEsc':
if (code === 0x5c) {
state = 'ground' // ESC \ = ST terminates the OSC
} else {
// The ESC aborted the OSC and opened a new sequence at i-1.
start = i - 1
state = code === ESC ? 'esc' : stateAfterEscByte(code)
}
break
case 'string':
if (code === CAN || code === SUB) {
state = 'ground'
} else if (code === ESC) {
state = 'stringEsc'
}
break
case 'stringEsc':
if (code === 0x5c) {
state = 'ground'
} else {
start = i - 1
state = code === ESC ? 'esc' : stateAfterEscByte(code)
}
break
}
}
return state === 'ground' ? '' : stream.slice(start)
}
/** Ingest-time fold: advance the tracked tail with one more chunk. Returns ''
* (tracking abandoned) when the tail exceeds the cap — see the cap comment. */
export function advancePartialEscapeTail(pendingTail: string, chunk: string): string {
const tail = extractPartialEscapeTail(pendingTail + chunk)
return tail.length > MAX_PARTIAL_ESCAPE_TAIL_LENGTH ? '' : tail
}
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it } from 'vitest'
import { isTerminalQueryReply } from './terminal-query-reply'
describe('isTerminalQueryReply', () => {
it('matches synthetic query replies that must be sent immediately', () => {
// CPR cursor position report (answer to CSI 6n) — the #7329 culprit.
expect(isTerminalQueryReply('\x1b[3;1R')).toBe(true)
expect(isTerminalQueryReply('\x1b[22;1R')).toBe(true)
// DSR device status.
expect(isTerminalQueryReply('\x1b[0n')).toBe(true)
// DA1/DA2/DA3 device attributes.
expect(isTerminalQueryReply('\x1b[?1;2c')).toBe(true)
expect(isTerminalQueryReply('\x1b[?61;4c')).toBe(true)
expect(isTerminalQueryReply('\x1b[>0;276;0c')).toBe(true)
// Window/cell pixel-size reports.
expect(isTerminalQueryReply('\x1b[6;16;8t')).toBe(true)
expect(isTerminalQueryReply('\x1b[4;384;640t')).toBe(true)
// DECRPM mode report — private (with ?) and ANSI (without ?).
expect(isTerminalQueryReply('\x1b[?2026;2$y')).toBe(true)
expect(isTerminalQueryReply('\x1b[4;1$y')).toBe(true)
// OSC 10/11 color responses (the #7329 culprit) — BEL and ST terminated.
expect(isTerminalQueryReply('\x1b]11;rgb:2828/2c2c/3434\x1b\\')).toBe(true)
expect(isTerminalQueryReply('\x1b]10;rgb:c0c0/c0c0/c0c0\x07')).toBe(true)
// DECXCPR extended cursor position report (answer to CSI ? 6n).
expect(isTerminalQueryReply('\x1b[?12;5R')).toBe(true)
// Text-area size in characters (answer to CSI 18t).
expect(isTerminalQueryReply('\x1b[8;24;80t')).toBe(true)
// Kitty keyboard flags report (answer to CSI ? u) — crossterm probes this
// at startup, so a debounced reply corrupts the same way CPR did.
expect(isTerminalQueryReply('\x1b[?0u')).toBe(true)
expect(isTerminalQueryReply('\x1b[?31u')).toBe(true)
// DCS DECRQSS reports (vim queries cursor style via DCS $ q) + XTVERSION.
expect(isTerminalQueryReply('\x1bP1$r2 q\x1b\\')).toBe(true)
expect(isTerminalQueryReply('\x1bP1$r0m\x1b\\')).toBe(true)
expect(isTerminalQueryReply('\x1bP0$r\x1b\\')).toBe(true)
expect(isTerminalQueryReply('\x1bP>|xterm.js(5.6.0)\x1b\\')).toBe(true)
})
it('documents the accepted modified-F3/CPR collision', () => {
// xterm.js encodes Shift+F3 as CSI 1;2R — byte-identical to a CPR report.
// Classified as a reply on purpose: order is still preserved (the immediate
// path flushes pending input first); see the comment in terminal-query-reply.ts.
expect(isTerminalQueryReply('\x1b[1;2R')).toBe(true)
})
it('does NOT match ordinary typed input or navigation sequences', () => {
// Plain text.
expect(isTerminalQueryReply('yes')).toBe(false)
expect(isTerminalQueryReply('y')).toBe(false)
expect(isTerminalQueryReply('\r')).toBe(false)
expect(isTerminalQueryReply('\x03')).toBe(false) // Ctrl-C
// Arrow keys / navigation — must stay batched (coalesced auto-repeat).
expect(isTerminalQueryReply('\x1b[A')).toBe(false)
expect(isTerminalQueryReply('\x1b[B')).toBe(false)
expect(isTerminalQueryReply('\x1b[C')).toBe(false)
expect(isTerminalQueryReply('\x1b[D')).toBe(false)
expect(isTerminalQueryReply('\x1b[H')).toBe(false) // Home
expect(isTerminalQueryReply('\x1b[F')).toBe(false) // End
// Function keys (end in ~).
expect(isTerminalQueryReply('\x1b[15~')).toBe(false)
expect(isTerminalQueryReply('\x1b[3~')).toBe(false) // Delete
// Bare Escape key.
expect(isTerminalQueryReply('\x1b')).toBe(false)
// Alt+key (including Alt+Shift+P, whose bytes prefix the DCS grammar).
expect(isTerminalQueryReply('\x1bb')).toBe(false)
expect(isTerminalQueryReply('\x1bP')).toBe(false)
// Kitty-protocol KEYSTROKES (CSI code;mods u, no "?") must stay batched.
expect(isTerminalQueryReply('\x1b[97;5u')).toBe(false)
expect(isTerminalQueryReply('\x1b[13u')).toBe(false)
// Modified F1/F2/F4 (CSI 1;<mod> P/Q/S) are keystrokes, not replies.
expect(isTerminalQueryReply('\x1b[1;2P')).toBe(false)
expect(isTerminalQueryReply('\x1b[1;2Q')).toBe(false)
expect(isTerminalQueryReply('\x1b[1;2S')).toBe(false)
// Bracketed paste markers are input framing, not replies.
expect(isTerminalQueryReply('\x1b[200~')).toBe(false)
expect(isTerminalQueryReply('\x1b[201~')).toBe(false)
// Incomplete / non-terminated OSC and DCS must not match.
expect(isTerminalQueryReply('\x1b]11;rgb:2828/2c2c/3434')).toBe(false)
expect(isTerminalQueryReply('\x1bP1$r2 q')).toBe(false)
})
})
+69
View File
@@ -0,0 +1,69 @@
// Why this module exists: xterm's public onData stream mixes real keystrokes
// with the parser's synthetic replies to terminal queries a program embedded in
// its output (CPR/DSR cursor + device-status reports, DA device attributes,
// DECRPM mode reports, window/cell pixel-size reports, OSC 10/11 color reports,
// kitty keyboard flag reports, DCS-framed DECRQSS/XTVERSION reports).
// A querying program (e.g. starship/orb) reads these replies synchronously in
// raw mode with a short timeout, so on the remote path they must NOT sit behind
// the input debounce — a late reply lands on the shell prompt in cooked mode,
// which echoes it literally and splices it into the next typed line (#7329).
// This classifier lets the transport send replies immediately while keeping
// ordinary typed input (including bursty arrow-key auto-repeat) coalesced.
const ESC = String.fromCharCode(0x1b)
// Built via new RegExp from \u-escaped strings so no literal control
// characters appear in the source. // Final bytes of xterm's own query-reply grammars:
// R — CPR / DECXCPR cursor position report (answer to CSI 6n / CSI ? 6n)
// n — DSR device status report (answer to CSI 5n → CSI 0n)
// c — DA1/DA2/DA3 device attributes (answer to CSI c / CSI > c / CSI = c)
// t — window/cell pixel-size + text-area-size reports (CSI 14t/16t/18t)
// y — DECRPM mode report (answer to CSI ? Ps $ p), body ends "$y"
// u — kitty keyboard flags report (answer to CSI ? u), carries "?"
/* oxlint-disable no-control-regex -- grammars match terminal ESC/BEL sequences by definition */
// Known accepted collision: xterm.js encodes MODIFIED F3 (Shift/Ctrl/Alt+F3) as
// `CSI 1 ; <mod> R`, which is indistinguishable from a CPR report (a classic
// VT ambiguity). Such a keystroke is sent immediately instead of debounced —
// byte order is still preserved (the immediate path flushes pending input
// first), it just skips input-intent/activity bookkeeping. Harmless, so we
// keep the reply grammar complete rather than special-casing it.
const CPR_OR_DSR_RE = new RegExp('^\\u001b\\[\\??[0-9;]*[Rn]$')
const DEVICE_ATTRIBUTES_RE = new RegExp('^\\u001b\\[[?>=]?[0-9;]*c$')
// 4/6 = pixel-size reports, 8 = text-area size in characters (answer to CSI 18t).
const WINDOW_SIZE_REPORT_RE = new RegExp('^\\u001b\\[[468];[0-9]+;[0-9]+t$')
// `?` optional: private-mode reports carry it (DECRPM), ANSI-mode reports don't.
const DECRPM_RE = new RegExp('^\\u001b\\[\\??[0-9;]*\\$y$')
// Kitty keyboard protocol flags report: CSI ? flags u. The `?` distinguishes it
// from kitty-protocol *keystrokes* (CSI code;mods u), which must stay batched.
const KITTY_FLAGS_RE = new RegExp('^\\u001b\\[\\?[0-9]+u$')
// OSC color/title responses: ESC ] Ps ; body ST (ST = BEL or ESC backslash).
const OSC_RESPONSE_RE = new RegExp('^\\u001b\\][0-9]+;[^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\)$')
// DCS-framed reports xterm emits: DECRQSS "ESC P 1 $ r Pt ST" / "ESC P 0 $ r ST"
// (vim queries cursor style this way) and XTVERSION "ESC P > | text ST".
const DCS_RESPONSE_RE = new RegExp('^\\u001bP(?:[01]\\$r[^\\u001b]*|>\\|[^\\u001b]*)\\u001b\\\\$')
/* oxlint-enable no-control-regex */
/**
* True when `data` (from xterm.onData) is a synthetic reply the emulator
* generated in response to a query — not something the user typed. These are
* latency-critical and must bypass input coalescing on the remote transport.
*
* Conservative by design: matches only complete, well-formed reply grammars so
* ordinary keystrokes and navigation sequences (arrows CSI A/B/C/D, Home/End,
* function keys ending in ~, kitty CSI-u keystrokes) are never misclassified
* as replies — with the single documented modified-F3/CPR collision above.
*/
export function isTerminalQueryReply(data: string): boolean {
if (data.length < 3 || data[0] !== ESC) {
return false
}
return (
CPR_OR_DSR_RE.test(data) ||
DEVICE_ATTRIBUTES_RE.test(data) ||
WINDOW_SIZE_REPORT_RE.test(data) ||
DECRPM_RE.test(data) ||
KITTY_FLAGS_RE.test(data) ||
OSC_RESPONSE_RE.test(data) ||
DCS_RESPONSE_RE.test(data)
)
}