diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 8af803db1fd8c..aa0953142aac9 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -3,6 +3,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + DEFAULT_MAX_TERMINAL_BUFFER_BYTES, DEFAULT_TERMINAL_ID, ProjectId, ThreadId, @@ -488,6 +489,98 @@ it("restores bounded history across append compaction, clears and split Unicode" expect(persisted).toBe("z".repeat(maxBytes)); }); +it("stops holding a control sequence that outgrows its limit", () => { + const limit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; + // No final byte for a CSI and no terminator for a string. + const filler = "0123456789 123\r\n".repeat(64); + const fed = filler.repeat(Math.ceil(limit / filler.length) + 2); + // The terminal runs the line breaks inside a CSI while it waits for the final byte. + const lineBreaks = fed.replaceAll(/[^\r\n]/g, ""); + for (const { name, open, end, history } of [ + { name: "OSC, BEL", open: ["\u001b]0;"], end: ["\u0007"], history: "\u001b\\" }, + { + name: "OSC, split ST", + open: ["\u001b]0;"], + end: ["\u001b", "\\\u001b[31m"], + history: "\u001b\\\u001b[31m", + }, + // The last UTF-8 byte of U+20805 is 0x85, NEL, which ends the DCS and replays as ESC E. + { + name: "DCS, split code point", + open: ["\u001bPstuck"], + end: ["\ud842", "\udc05"], + history: "\u001b\\\u001bE", + }, + // The dropped CSI's ESC ended the title, so history ends it too. Its final byte would have + // made it a query that the replay answers. + { + name: "CSI after a title its ESC cuts short", + open: ["\u001b]0;title", "\u001b["], + end: ["\n6n"], + history: `\u001b]0;title\u001b\\${lineBreaks}\n`, + }, + { + name: "CSI, ESC", + open: ["\u001b["], + end: ["\n\u001b[31m"], + history: `\u001b\\${lineBreaks}\n\u001b[31m`, + }, + ]) { + let held = ""; + let visible = ""; + const feed = (data: string) => { + const sanitized = TerminalManager.sanitizeTerminalHistoryChunk(held, data); + held = sanitized.pendingControlSequence; + visible += sanitized.visibleText; + }; + + feed("before\n"); + for (const data of open) feed(data); + for (let offset = 0; offset < fed.length; offset += filler.length) { + feed(fed.slice(offset, offset + filler.length)); + } + expect(held.length, name).toBeLessThanOrEqual(3); + + for (const data of end) feed(data); + feed("after\n"); + expect(held, name).toBe(""); + expect(visible, name).toBe(`before\n${history}after\n`); + } + + // Held text of exactly the limit stays held, and a sequence that ends in the chunk where it + // passes the limit is kept whole. + for (const atLimit of ["\u001b]".padEnd(limit, "0"), "\u001b[".padEnd(limit, "0")]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", atLimit)).toEqual({ + visibleText: "", + pendingControlSequence: atLimit, + }); + const ended = `${atLimit}0${atLimit[1] === "]" ? "\u0007" : "m"}`; + expect(TerminalManager.sanitizeTerminalHistoryChunk("", ended)).toEqual({ + visibleText: ended, + pendingControlSequence: "", + }); + } + + // An escape sequence keeps its first four intermediates, the only ones libghostty reads. + const escape = '\u001b!"#$'; + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&")).toEqual({ + visibleText: "", + pendingControlSequence: escape, + }); + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&B")).toEqual({ + visibleText: `${escape}%&B`, + pendingControlSequence: "", + }); + + // A completed escape sequence stays when another ESC follows it at once. + for (const kept of ["OLD\u001bc\u001b[31mNEW", "abc\u001b7\u001b[2;5HB\u001b8Z"]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", kept)).toEqual({ + visibleText: kept, + pendingControlSequence: "", + }); + } +}); + it.layer( Layer.mergeAll( NodeServices.layer, @@ -1756,6 +1849,39 @@ it.layer( }), ); + it.effect("starts a snapshot inside the sequence the terminal has not finished", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const outputs = yield* Queue.unbounded(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" ? Queue.offer(outputs, undefined).pipe(Effect.asVoid) : Effect.void, + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + const historyAfter = Effect.fnUntraced(function* (data: string) { + process.emitData(data); + yield* Queue.take(outputs); + return (yield* manager.open(openInput())).history; + }); + + expect(yield* historyAfter("A\u001b]0;ti")).toBe("A\u001b]0;ti"); + // A long string would push history out of the client's budget, so its payload is left out. + expect(yield* historyAfter("x".repeat(4_096))).toBe("A\u001b]"); + // Past the limit only the introducer is left to replay. + expect(yield* historyAfter("x".repeat(DEFAULT_MAX_TERMINAL_BUFFER_BYTES))).toBe( + "A\u001b\\\u001b]", + ); + expect(yield* historyAfter("\u0007B")).toBe("A\u001b\\B"); + + // Saved history has no live output to finish the sequence. + process.emitData("\u001b]0;open"); + yield* Queue.take(outputs); + yield* manager.close({ threadId: "thread-1" }); + expect(yield* readFileString(yield* historyLogPath(logsDir))).toBe("A\u001b\\B"); + }), + ); + it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index e87ba67cf5837..92600d0a326a8 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -415,7 +415,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { worktreePath: session.worktreePath, status: session.status, pid: session.pid, - history: session.history.value(), + history: session.history.value() + unfinishedSequenceReplay(session), exitCode: session.exitCode, exitSignal: session.exitSignal, label: terminalWireLabel(session), @@ -1394,7 +1394,32 @@ function findEscapeSequenceEndIndex(input: string, start: number): number | null const HISTORY_SEQUENCE_START = /\u001b/; const NEXT_HISTORY_SEQUENCE_START = new RegExp(HISTORY_SEQUENCE_START.source, "g"); -function sanitizeTerminalHistoryChunk( +// Clients keep this much output and drop a sequence their trim cuts through, so none of them +// could replay a longer string or CSI whole. +const MAX_HELD_SEQUENCE_LENGTH = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; +// ESC and four intermediates: libghostty ignores every intermediate past the fourth. +const MAX_HELD_ESCAPE_LENGTH = 5; +// Leads the held text of a string or CSI that outgrew its limit and stays out of history. Only its +// introducer is still held, with a final ESC or high surrogate that may begin its end. Other held +// text starts with ESC. +const OVERSIZED_SEQUENCE = "\u0018"; +// Stands in for the ESC of an oversized sequence, which ended any string history left open. +const STRING_TERMINATOR = "\u001b\\"; + +// Longer held text is cut to its introducer in a snapshot, so it cannot push history out of the +// client's budget or add its size to every resync. +const MAX_SNAPSHOT_SEQUENCE_LENGTH = 4_096; + +// History leaves out the sequence the terminal is still inside. A client that starts from a +// snapshot needs it, or it prints the rest of the sequence as text. +function unfinishedSequenceReplay(session: TerminalSessionState): string { + const held = session.pendingHistoryControlSequence; + if (held.startsWith(OVERSIZED_SEQUENCE)) return held.slice(1); + if (held.length <= MAX_SNAPSHOT_SEQUENCE_LENGTH) return held; + return held.slice(0, 2) + (/[\u001b\ud800-\udbff]$/.exec(held)?.[0] ?? ""); +} + +export function sanitizeTerminalHistoryChunk( pendingControlSequence: string, data: string, ): { visibleText: string; pendingControlSequence: string } { @@ -1402,9 +1427,12 @@ function sanitizeTerminalHistoryChunk( return { visibleText: data, pendingControlSequence: "" }; } - const input = `${pendingControlSequence}${data}`; - // Only the pending prefix's final ESC can begin a terminator split across chunks. - const pendingScanStart = Math.max(0, pendingControlSequence.length - 1); + const resumesOversized = pendingControlSequence.startsWith(OVERSIZED_SEQUENCE); + const held = resumesOversized ? pendingControlSequence.slice(1) : pendingControlSequence; + const input = `${held}${data}`; + // Only the held text's final code unit, an ESC or a high surrogate, can begin an end split + // across chunks. + const pendingScanStart = Math.max(0, held.length - 1); let visibleText = ""; let index = 0; // Set when a C1 code point began the sequence at `index`: the ESC form that stands in for it. @@ -1421,6 +1449,7 @@ function sanitizeTerminalHistoryChunk( // Empty for a sequence the input introduces itself, which starts with ESC at `index`. const prefix = c1Introducer; c1Introducer = ""; + const oversized = resumesOversized && index === 0; const contentStart = prefix.length > 0 ? index : index + 2; const nextCodePoint = (prefix || input).charCodeAt(prefix.length > 0 ? 1 : index + 1); if (Number.isNaN(nextCodePoint)) { @@ -1428,19 +1457,21 @@ function sanitizeTerminalHistoryChunk( } if (nextCodePoint === 0x5b) { - let cursor = contentStart; + // A held CSI has not ended, so only its last code unit is scanned again. + let cursor = index === 0 ? Math.max(contentStart, pendingScanStart) : contentStart; // Inside a CSI Ghostty executes 0x00-0x0F and ignores DEL and 0x10-0x1F, which it would // print in ground state. None join the parameters; only executed ones survive a strip. - let body = ""; - let executedControls = ""; + const executedControls = () => + input.slice(contentStart, cursor).replace(/[^\x00-\x0f]+/g, ""); while (cursor < input.length) { const cursorCodePoint = input.charCodeAt(cursor); const cancelled = isControlSequenceCancel(cursorCodePoint); if (cancelled || isCsiFinalByte(cursorCodePoint)) { - if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) { + const body = input.slice(contentStart, cursor).replace(/[^\x20-\x7e]+/g, ""); + if (!oversized && (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? ""))) { append(prefix + input.slice(index, cursor + 1)); } else { - append(executedControls); + append(executedControls()); } index = cursor + 1; break; @@ -1452,10 +1483,10 @@ function sanitizeTerminalHistoryChunk( if (c1) { // The CSI ends here undispatched, so it is kept only when the terminal is back in // ground with nothing to answer. - if (c1.next.length === 0 && !c1.query) { + if (!oversized && c1.next.length === 0 && !c1.query) { append(prefix + input.slice(index, end)); } else { - append(executedControls + c1.safe); + append(executedControls() + c1.safe); } c1Introducer = c1.next; index = end; @@ -1466,19 +1497,24 @@ function sanitizeTerminalHistoryChunk( } // An ESC abandons the CSI and starts the next sequence, which may be stripped. if (cursorCodePoint === 0x1b) { - append(executedControls); + append(executedControls()); index = cursor; break; } - if (cursorCodePoint < 0x10) { - executedControls += input[cursor]; - } else if (cursorCodePoint >= 0x20 && cursorCodePoint !== 0x7f) { - body += input[cursor]; - } cursor += 1; } if (cursor >= input.length) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + // The terminal has run these controls already, so history takes them as they come. + append((oversized ? "" : STRING_TERMINATOR) + executedControls()); + const endStart = /[\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: `${OVERSIZED_SEQUENCE}\u001b[${endStart}`, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } continue; } @@ -1495,7 +1531,16 @@ function sanitizeTerminalHistoryChunk( nextCodePoint === 0x5d, ); if (stringEnd === null) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + append(oversized ? "" : STRING_TERMINATOR); + const endStart = /[\u001b\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: OVERSIZED_SEQUENCE + unfinished.slice(0, 2) + endStart, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } const { end, c1 } = stringEnd; const content = stripStringTerminator( @@ -1505,6 +1550,7 @@ function sanitizeTerminalHistoryChunk( // has its own terminator. Without one, the query ends at the next ESC, which history may // strip, so ST would not replay the same and the query stays. if ( + !oversized && nextCodePoint === 0x5d && isOscPaletteQuery(content) && /[\x07\x18\x1a]$|\x1b\\$/.test(input.slice(index, end)) @@ -1514,6 +1560,7 @@ function sanitizeTerminalHistoryChunk( continue; } const strip = + oversized || (nextCodePoint === 0x5d && shouldStripOscSequence(content)) || (nextCodePoint === 0x50 && shouldStripDcsSequence(content)); if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) { @@ -1532,7 +1579,10 @@ function sanitizeTerminalHistoryChunk( const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1); if (escapeSequenceEndIndex === null) { - return { visibleText, pendingControlSequence: input.slice(index) }; + return { + visibleText, + pendingControlSequence: input.slice(index, index + MAX_HELD_ESCAPE_LENGTH), + }; } // ESC Z (DECID) is the legacy primary device attributes query. if (nextCodePoint !== 0x5a) {