From 1662c3c7d63205a2492157ebe99cc93444016ad3 Mon Sep 17 00:00:00 2001 From: viktorce Date: Thu, 19 Nov 2026 23:10:18 +0000 Subject: [PATCH 1/5] fix(server): terminal output after an unfinished control sequence no longer slows the server The history sanitizer held everything that arrived while a control sequence was open, with no limit, and worked through the held text again on every chunk. A sequence that never ended made the cost grow with the square of the output. The held text now has a limit in UTF-16 code units: 524,288 for an OSC, DCS, PM or APC string, the byte size of what a client retains, and 4,096 for a CSI. Past the limit a string or CSI keeps only its introducer, and the rest of the sequence stays out of history. libghostty does the same with an oversized string: it drops the payload and stays in the string until the terminator. When a string or CSI is first dropped, history gets one ST. The dropped sequence's own ESC ended whatever history left open before it, and the ST does the same on replay. A held escape sequence keeps its ESC and four intermediates. libghostty ignores intermediates past the fourth, so the cut changes nothing on replay. --- apps/server/src/terminal/Manager.test.ts | 148 +++++++++++++++++++++++ apps/server/src/terminal/Manager.ts | 64 ++++++++-- docs/internals/terminal-runtime.md | 9 ++ 3 files changed, 212 insertions(+), 9 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 154dd4a445d34..ec90c64f37e4f 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, @@ -487,6 +488,153 @@ 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 stringLimit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; + const csiLimit = 4_096; + // No final byte for a CSI and no terminator for a string. + const digits = "0123456789 123\r\n".repeat(64); + // History gets one ST where a sequence is dropped. + const st = "\u001b\\"; + // The next ESC cuts this title short, so it goes to history with no terminator. + const leftOpen = "\u001b]0;one"; + // The terminal runs the carriage returns and line feeds inside a CSI while it waits for the + // final byte. + const lineBreaks = (fed: string) => fed.replaceAll(/[^\r\n]/g, ""); + // The last UTF-8 byte of U+20805 is 0x85, NEL, which ends a CSI or a string other than OSC. + // History replays it as ESC E. + const splitCodePoint = ["\ud842", "\udc05"]; + for (const { name, open, limit, filler = digits, end, history } of [ + { + name: "DCS, split code point", + open: `${leftOpen}\u001bPstuck`, + limit: stringLimit, + end: splitCodePoint, + history: () => `${leftOpen}${st}\u001bE`, + }, + // Each piece's U+0090 ends the sequence before it and opens a DCS that the piece drops. + { + name: "DCS opened by U+0090", + open: "\u001b[", + limit: stringLimit, + filler: `\u0090${"y".repeat(stringLimit)}`, + end: ["\u001b", "\\"], + history: () => st.repeat(3), + }, + { name: "OSC, BEL", open: "\u001b]0;", limit: stringLimit, end: ["\u0007"], history: () => st }, + { + name: "OSC, ESC", + open: "\u001b]0;", + limit: stringLimit, + end: ["\u001b[31m"], + history: () => `${st}\u001b[31m`, + }, + { + name: "CSI, final byte", + open: `${leftOpen}\u001b[`, + limit: csiLimit, + end: ["\nm"], + history: (fed: string) => `${leftOpen}${st}${lineBreaks(fed)}\n`, + }, + { + name: "CSI, CAN", + open: "\u001b[", + limit: csiLimit, + end: ["\u0018"], + history: (fed: string) => `${st}${lineBreaks(fed)}`, + }, + { + name: "CSI, U+0090", + open: "\u001b[", + limit: csiLimit, + end: ["\n\u0090kept\u001b\\"], + history: (fed: string) => `${st}${lineBreaks(fed)}\n\u001bPkept\u001b\\`, + }, + // An ESC abandons the CSI and starts a sequence that is kept. + { + name: "CSI, ESC", + open: "\u001b[", + limit: csiLimit, + end: ["\n\u001b[31m"], + history: (fed: string) => `${st}${lineBreaks(fed)}\n\u001b[31m`, + }, + { + name: "CSI, split code point", + open: "\u001b[", + limit: csiLimit, + end: ["\n", ...splitCodePoint], + history: (fed: string) => `${st}${lineBreaks(fed)}\n\u001bE`, + }, + ]) { + let held = ""; + let visible = ""; + const feed = (data: string) => { + const sanitized = TerminalManager.sanitizeTerminalHistoryChunk(held, data); + held = sanitized.pendingControlSequence; + visible += sanitized.visibleText; + }; + const fed = filler.repeat(Math.ceil(limit / filler.length) + 2); + + feed("before\n"); + feed(open); + for (let offset = 0; offset < fed.length; offset += filler.length) { + feed(fed.slice(offset, offset + filler.length)); + } + expect(held.length, name).toBeLessThanOrEqual(4); + + for (const data of end) feed(data); + feed("after\n"); + expect(held, name).toBe(""); + expect(visible, name).toBe(`before\n${history(fed)}after\n`); + } + + // Held text of exactly the limit stays held, and one more code unit passes the limit. Output + // before it in the same chunk is kept, and so is a last code unit that may begin the end. A C1 + // introducer counts as its ESC form. + const afterOutput = (data: string) => + TerminalManager.sanitizeTerminalHistoryChunk("", `before\n${data}`); + const string = "\u001b]".padEnd(stringLimit, "0"); + const csi = "\u001b[".padEnd(csiLimit, "0"); + for (const atLimit of [string, csi]) { + expect(afterOutput(atLimit), atLimit.slice(0, 2)).toEqual({ + visibleText: "before\n", + pendingControlSequence: atLimit, + }); + } + // A sequence that ends in the chunk where it passes the limit is kept whole. + for (const ended of [`${string}0\u0007`, `${csi}0m`]) { + expect(afterOutput(ended), `${ended.slice(0, 2)} ends`).toEqual({ + visibleText: `before\n${ended}`, + pendingControlSequence: "", + }); + } + expect(afterOutput(`${string}\u001b`), "string past the limit").toEqual({ + visibleText: `before\n${st}`, + pendingControlSequence: "\u0018\u001b]\u001b", + }); + expect(afterOutput(`\u001b[\u009b${csi.slice(2)}\ud842`), "CSI past the limit").toEqual({ + visibleText: `before\n${st}`, + pendingControlSequence: "\u0018\u001b[\ud842", + }); + expect(afterOutput(`${string}\ud842`), "string past the limit, high surrogate").toEqual({ + visibleText: `before\n${st}`, + pendingControlSequence: "\u0018\u001b]\ud842", + }); + // libghostty ignores intermediates past the fourth, so an escape sequence keeps the first four. + const escape = '\u001b!"#$'; + expect(afterOutput(`${escape}%`), "escape sequence past the limit").toEqual({ + visibleText: "before\n", + pendingControlSequence: escape, + }); + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "&'"), "escape stays cut").toEqual({ + visibleText: "", + pendingControlSequence: escape, + }); + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "&'B"), "escape ends").toEqual({ + visibleText: `${escape}&'B`, + pendingControlSequence: "", + }); +}); + it.layer( Layer.mergeAll( NodeServices.layer, diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index a294ba7f1afe2..44c3c68cc8a40 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1379,7 +1379,25 @@ 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 cut goes through, so none of them +// could replay a longer string whole. +const MAX_HELD_STRING_LENGTH = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; +// A real CSI is short, because it carries no payload and libghostty runs one only when it has +// at most 24 parameters. Each chunk rescans the held text, so this also bounds that work. +const MAX_HELD_CSI_LENGTH = 4_096; +// The ESC and four intermediates. libghostty ignores every intermediate past the fourth, so a +// held escape sequence cut to this replays the same. +const MAX_HELD_ESCAPE_LENGTH = 5; +// Leads the held text of a string or CSI that outgrew its limit, whose rest 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. Strip it before sending held text to a client, because a CAN +// cancels the open sequence there. +const DROPPED_SEQUENCE = "\u0018"; +// The first drop writes ST to history. The dropped sequence's own ESC ended whatever history left +// open before it, and ST does the same on replay. In ground state ST does nothing. +const DROPPED_SEQUENCE_ST = "\u001b\\"; + +export function sanitizeTerminalHistoryChunk( pendingControlSequence: string, data: string, ): { visibleText: string; pendingControlSequence: string } { @@ -1387,9 +1405,11 @@ 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 resumesDropped = pendingControlSequence.startsWith(DROPPED_SEQUENCE); + const input = `${pendingControlSequence.slice(resumesDropped ? 1 : 0)}${data}`; + // Only the pending prefix's final code unit, an ESC or a high surrogate, can begin an end split + // across chunks. + const pendingScanStart = Math.max(0, input.length - data.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. @@ -1406,6 +1426,7 @@ function sanitizeTerminalHistoryChunk( // Empty for a sequence the input introduces itself, which starts with ESC at `index`. const prefix = c1Introducer; c1Introducer = ""; + const dropped = resumesDropped && 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)) { @@ -1422,7 +1443,7 @@ function sanitizeTerminalHistoryChunk( const cursorCodePoint = input.charCodeAt(cursor); const cancelled = isControlSequenceCancel(cursorCodePoint); if (cancelled || isCsiFinalByte(cursorCodePoint)) { - if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) { + if (!dropped && (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? ""))) { append(prefix + input.slice(index, cursor + 1)); } else { append(executedControls); @@ -1437,7 +1458,7 @@ 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 (!dropped && c1.next.length === 0 && !c1.query) { append(prefix + input.slice(index, end)); } else { append(executedControls + c1.safe); @@ -1463,7 +1484,17 @@ function sanitizeTerminalHistoryChunk( cursor += 1; } if (cursor >= input.length) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const held = prefix + input.slice(index); + if (dropped || held.length > MAX_HELD_CSI_LENGTH) { + // The terminal has run these already, so history takes them as they come. A final + // high surrogate may begin a code point whose bytes end the CSI. + const surrogate = /[\ud800-\udbff]$/.exec(held)?.[0] ?? ""; + return { + visibleText: visibleText + (dropped ? "" : DROPPED_SEQUENCE_ST) + executedControls, + pendingControlSequence: `${DROPPED_SEQUENCE}\u001b[${surrogate}`, + }; + } + return { visibleText, pendingControlSequence: held }; } continue; } @@ -1480,13 +1511,24 @@ function sanitizeTerminalHistoryChunk( nextCodePoint === 0x5d, ); if (stringEnd === null) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const held = prefix + input.slice(index); + if (dropped || held.length > MAX_HELD_STRING_LENGTH) { + // A final ESC may begin the terminator, and a final high surrogate a code point + // whose bytes end the string. + const terminatorStart = /[\u001b\ud800-\udbff]$/.exec(held)?.[0] ?? ""; + return { + visibleText: visibleText + (dropped ? "" : DROPPED_SEQUENCE_ST), + pendingControlSequence: DROPPED_SEQUENCE + held.slice(0, 2) + terminatorStart, + }; + } + return { visibleText, pendingControlSequence: held }; } const { end, c1 } = stringEnd; const content = stripStringTerminator( prefix.slice(2) + input.slice(contentStart, c1?.index ?? end), ); const strip = + dropped || (nextCodePoint === 0x5d && shouldStripOscSequence(content)) || (nextCodePoint === 0x50 && shouldStripDcsSequence(content)); if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) { @@ -1505,7 +1547,11 @@ function sanitizeTerminalHistoryChunk( const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1); if (escapeSequenceEndIndex === null) { - return { visibleText, pendingControlSequence: input.slice(index) }; + // Only intermediates follow this ESC. + return { + visibleText, + pendingControlSequence: input.slice(index, index + MAX_HELD_ESCAPE_LENGTH), + }; } // ESC Z (DECID) is the legacy primary device attributes query. if (nextCodePoint !== 0x5a) { diff --git a/docs/internals/terminal-runtime.md b/docs/internals/terminal-runtime.md index ca5f0d46ead6e..9cc79d5ff7d8e 100644 --- a/docs/internals/terminal-runtime.md +++ b/docs/internals/terminal-runtime.md @@ -22,6 +22,15 @@ discarded chunk references immediately, even if array compaction happens later. Client buffers have a separate 512 KiB cap. Measure throughput with full scrollback when changing this path. +The server holds the text of an unfinished control sequence until it ends, and limits +how much it holds. The limit must not end a string. libghostty stays in an oversized +string until its terminator and prints none of it as text, so history that resumed +early would replay output the live screen never showed. A CSI longer than the limit can +still run in libghostty at its final byte. History leaves it out, because it may be a +query. Below the limit each chunk copies the held string. The string limit in code +units is the client buffer's limit in bytes, so raising that buffer raises the cost +with its square. + Restoration must read only the bounded tail of current or legacy history files, skip any incomplete UTF-8 prefix, and apply the line limit. Close the read handle before rewriting the capped file. Reading whole old logs would defeat the memory From 6d435a7f3188be7563ed6b88617c028844223e16 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 20:00:05 +0000 Subject: [PATCH 2/5] chore(server): drop a stale note about held control sequences reaching clients Co-Authored-By: Claude Opus 5.5 --- apps/server/src/terminal/Manager.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 863d6038a0df7..73a61498a9aca 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1392,8 +1392,7 @@ const MAX_HELD_CSI_LENGTH = 4_096; const MAX_HELD_ESCAPE_LENGTH = 5; // Leads the held text of a string or CSI that outgrew its limit, whose rest 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. Strip it before sending held text to a client, because a CAN -// cancels the open sequence there. +// Other held text starts with ESC, so this marker never collides with it. const DROPPED_SEQUENCE = "\u0018"; // The first drop writes ST to history. The dropped sequence's own ESC ended whatever history left // open before it, and ST does the same on replay. In ground state ST does nothing. From eb1c2b6b3c19f4ebecb2c33885e682f92cceb93c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 10:19:38 +0000 Subject: [PATCH 3/5] fix(server): keep zero-padded CSI setters under the held-sequence limit Main now asserts that a 5,000-character SGR split across chunks replays whole. The 4,096 CSI cap dropped it. Raise the cap to 65,536, which still bounds the per-chunk rescan of a held CSI. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/terminal/Manager.test.ts | 2 +- apps/server/src/terminal/Manager.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index cd1a59e4c9ade..6dc9662dc1814 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -491,7 +491,7 @@ it("restores bounded history across append compaction, clears and split Unicode" it("stops holding a control sequence that outgrows its limit", () => { const stringLimit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; - const csiLimit = 4_096; + const csiLimit = 65_536; // No final byte for a CSI and no terminator for a string. const digits = "0123456789 123\r\n".repeat(64); // History gets one ST where a sequence is dropped. diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index cc16f58ecc690..8168043921923 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1397,9 +1397,9 @@ const NEXT_HISTORY_SEQUENCE_START = new RegExp(HISTORY_SEQUENCE_START.source, "g // Clients keep this much output and drop a sequence their cut goes through, so none of them // could replay a longer string whole. const MAX_HELD_STRING_LENGTH = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; -// A real CSI is short, because it carries no payload and libghostty runs one only when it has -// at most 24 parameters. Each chunk rescans the held text, so this also bounds that work. -const MAX_HELD_CSI_LENGTH = 4_096; +// A CSI carries no payload, but zero-padded parameters still make a setter long. Each chunk +// rescans the held CSI, so this bounds that work. +const MAX_HELD_CSI_LENGTH = 65_536; // The ESC and four intermediates. libghostty ignores every intermediate past the fourth, so a // held escape sequence cut to this replays the same. const MAX_HELD_ESCAPE_LENGTH = 5; From eb555c6d8ce11e8d1c65d0e47d000e4af76831ed Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 10:36:08 +0000 Subject: [PATCH 4/5] fix(server): keep held CSIs to the replay budget and stop closing left-open queries A held CSI now shares the strings' limit, the clients' replay budget, so valid zero-padded setters such as a long bracketed-paste mode survive. The CSI scan resumes at the held text's last code unit and derives its body only when it ends, so holding one costs no more than holding a string. A drop no longer writes ST to history. That ST could end a query history had left open, such as an OSC 4 palette query cut short by the dropped sequence's ESC, and the replay would answer it. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/terminal/Manager.test.ts | 58 ++++++++++-------------- apps/server/src/terminal/Manager.ts | 40 +++++++--------- 2 files changed, 40 insertions(+), 58 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 6dc9662dc1814..21b8eb5cba050 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -490,80 +490,70 @@ it("restores bounded history across append compaction, clears and split Unicode" }); it("stops holding a control sequence that outgrows its limit", () => { - const stringLimit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; - const csiLimit = 65_536; + const limit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; // No final byte for a CSI and no terminator for a string. const digits = "0123456789 123\r\n".repeat(64); - // History gets one ST where a sequence is dropped. - const st = "\u001b\\"; - // The next ESC cuts this title short, so it goes to history with no terminator. - const leftOpen = "\u001b]0;one"; + // The next ESC cuts this query short, so it goes to history with no terminator. Nothing the + // drop writes may end it, or the replay would answer it. + const leftOpen = "\u001b]4;1;?"; // The terminal runs the carriage returns and line feeds inside a CSI while it waits for the // final byte. const lineBreaks = (fed: string) => fed.replaceAll(/[^\r\n]/g, ""); // The last UTF-8 byte of U+20805 is 0x85, NEL, which ends a CSI or a string other than OSC. // History replays it as ESC E. const splitCodePoint = ["\ud842", "\udc05"]; - for (const { name, open, limit, filler = digits, end, history } of [ + for (const { name, open, filler = digits, end, history } of [ { name: "DCS, split code point", open: `${leftOpen}\u001bPstuck`, - limit: stringLimit, end: splitCodePoint, - history: () => `${leftOpen}${st}\u001bE`, + history: () => `${leftOpen}\u001bE`, }, // Each piece's U+0090 ends the sequence before it and opens a DCS that the piece drops. { name: "DCS opened by U+0090", open: "\u001b[", - limit: stringLimit, - filler: `\u0090${"y".repeat(stringLimit)}`, + filler: `\u0090${"y".repeat(limit)}`, end: ["\u001b", "\\"], - history: () => st.repeat(3), + history: () => "", }, - { name: "OSC, BEL", open: "\u001b]0;", limit: stringLimit, end: ["\u0007"], history: () => st }, + { name: "OSC, BEL", open: "\u001b]0;", end: ["\u0007"], history: () => "" }, { name: "OSC, ESC", open: "\u001b]0;", - limit: stringLimit, end: ["\u001b[31m"], - history: () => `${st}\u001b[31m`, + history: () => "\u001b[31m", }, { name: "CSI, final byte", open: `${leftOpen}\u001b[`, - limit: csiLimit, - end: ["\nm"], - history: (fed: string) => `${leftOpen}${st}${lineBreaks(fed)}\n`, + end: ["\n6n"], + history: (fed: string) => `${leftOpen}${lineBreaks(fed)}\n`, }, { name: "CSI, CAN", open: "\u001b[", - limit: csiLimit, end: ["\u0018"], - history: (fed: string) => `${st}${lineBreaks(fed)}`, + history: (fed: string) => `${lineBreaks(fed)}`, }, { name: "CSI, U+0090", open: "\u001b[", - limit: csiLimit, end: ["\n\u0090kept\u001b\\"], - history: (fed: string) => `${st}${lineBreaks(fed)}\n\u001bPkept\u001b\\`, + history: (fed: string) => `${lineBreaks(fed)}\n\u001bPkept\u001b\\`, }, // An ESC abandons the CSI and starts a sequence that is kept. { name: "CSI, ESC", open: "\u001b[", - limit: csiLimit, end: ["\n\u001b[31m"], - history: (fed: string) => `${st}${lineBreaks(fed)}\n\u001b[31m`, + history: (fed: string) => `${lineBreaks(fed)}\n\u001b[31m`, }, { name: "CSI, split code point", open: "\u001b[", - limit: csiLimit, end: ["\n", ...splitCodePoint], - history: (fed: string) => `${st}${lineBreaks(fed)}\n\u001bE`, + history: (fed: string) => `${lineBreaks(fed)}\n\u001bE`, }, ]) { let held = ""; @@ -593,8 +583,8 @@ it("stops holding a control sequence that outgrows its limit", () => { // introducer counts as its ESC form. const afterOutput = (data: string) => TerminalManager.sanitizeTerminalHistoryChunk("", `before\n${data}`); - const string = "\u001b]".padEnd(stringLimit, "0"); - const csi = "\u001b[".padEnd(csiLimit, "0"); + const string = "\u001b]".padEnd(limit, "0"); + const csi = "\u001b[".padEnd(limit, "0"); for (const atLimit of [string, csi]) { expect(afterOutput(atLimit), atLimit.slice(0, 2)).toEqual({ visibleText: "before\n", @@ -609,15 +599,15 @@ it("stops holding a control sequence that outgrows its limit", () => { }); } expect(afterOutput(`${string}\u001b`), "string past the limit").toEqual({ - visibleText: `before\n${st}`, + visibleText: "before\n", pendingControlSequence: "\u0018\u001b]\u001b", }); expect(afterOutput(`\u001b[\u009b${csi.slice(2)}\ud842`), "CSI past the limit").toEqual({ - visibleText: `before\n${st}`, + visibleText: "before\n", pendingControlSequence: "\u0018\u001b[\ud842", }); expect(afterOutput(`${string}\ud842`), "string past the limit, high surrogate").toEqual({ - visibleText: `before\n${st}`, + visibleText: "before\n", pendingControlSequence: "\u0018\u001b]\ud842", }); // libghostty ignores intermediates past the fourth, so an escape sequence keeps the first four. @@ -1776,8 +1766,8 @@ it.layer( // colour in an OSC, and runs an OSC that CAN ends or that the next ESC cuts short. process.emitData("\u001b]4;1;red;2;?\u0007\u001b]0;t\u001b]\n4;1;?;;2;?;3\u0018\u001b]4;3;?"); process.emitData("\u001b]0;x\u001b\u001b[?2026$p"); - // A long setter split across chunks is kept whole. - process.emitData(`\u001b[${"0".repeat(5000)}`); + // A long setter split across chunks is kept whole, up to the clients' replay budget. + process.emitData(`\u001b[${"0".repeat(70_000)}`); process.emitData("31mX"); process.emitData("done\n"); @@ -1788,7 +1778,7 @@ it.layer( reopened.history.startsWith( 'prompt \u001b[!p\u001b["p\u001b[4 q\u001b[u' + "\u001b]4;1;red;2;?\u0007\u001b]0;t\u001b\\\u001b]4;3;?\u001b]0;x\u001b" + - `\u001b[${"0".repeat(5000)}31mXdone\n`, + `\u001b[${"0".repeat(70_000)}31mXdone\n`, ), ).toBe(true); }), diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 8168043921923..55fdd03966ca5 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1395,21 +1395,16 @@ const HISTORY_SEQUENCE_START = /\u001b/; const NEXT_HISTORY_SEQUENCE_START = new RegExp(HISTORY_SEQUENCE_START.source, "g"); // Clients keep this much output and drop a sequence their cut goes through, so none of them -// could replay a longer string whole. -const MAX_HELD_STRING_LENGTH = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; -// A CSI carries no payload, but zero-padded parameters still make a setter long. Each chunk -// rescans the held CSI, so this bounds that work. -const MAX_HELD_CSI_LENGTH = 65_536; +// could replay a longer string or CSI whole. +const MAX_HELD_SEQUENCE_LENGTH = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; // The ESC and four intermediates. libghostty ignores every intermediate past the fourth, so a // held escape sequence cut to this replays the same. const MAX_HELD_ESCAPE_LENGTH = 5; // Leads the held text of a string or CSI that outgrew its limit, whose rest 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, so this marker never collides with it. +// Other held text starts with ESC, so this marker never collides with it. Nothing stands in for +// the dropped ESC: closing what history left open could dispatch a query on replay. const DROPPED_SEQUENCE = "\u0018"; -// The first drop writes ST to history. The dropped sequence's own ESC ended whatever history left -// open before it, and ST does the same on replay. In ground state ST does nothing. -const DROPPED_SEQUENCE_ST = "\u001b\\"; export function sanitizeTerminalHistoryChunk( pendingControlSequence: string, @@ -1448,19 +1443,21 @@ export function sanitizeTerminalHistoryChunk( } if (nextCodePoint === 0x5b) { - let cursor = contentStart; + // A held CSI has no final byte, ESC or C1 control, so only its last code unit is rescanned. + 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)) { + const body = input.slice(contentStart, cursor).replace(/[^\x20-\x7e]+/g, ""); if (!dropped && (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? ""))) { append(prefix + input.slice(index, cursor + 1)); } else { - append(executedControls); + append(executedControls()); } index = cursor + 1; break; @@ -1475,7 +1472,7 @@ export function sanitizeTerminalHistoryChunk( if (!dropped && 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; @@ -1486,25 +1483,20 @@ export 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) { const held = prefix + input.slice(index); - if (dropped || held.length > MAX_HELD_CSI_LENGTH) { + if (dropped || held.length > MAX_HELD_SEQUENCE_LENGTH) { // The terminal has run these already, so history takes them as they come. A final // high surrogate may begin a code point whose bytes end the CSI. const surrogate = /[\ud800-\udbff]$/.exec(held)?.[0] ?? ""; return { - visibleText: visibleText + (dropped ? "" : DROPPED_SEQUENCE_ST) + executedControls, + visibleText: visibleText + executedControls(), pendingControlSequence: `${DROPPED_SEQUENCE}\u001b[${surrogate}`, }; } @@ -1526,12 +1518,12 @@ export function sanitizeTerminalHistoryChunk( ); if (stringEnd === null) { const held = prefix + input.slice(index); - if (dropped || held.length > MAX_HELD_STRING_LENGTH) { + if (dropped || held.length > MAX_HELD_SEQUENCE_LENGTH) { // A final ESC may begin the terminator, and a final high surrogate a code point // whose bytes end the string. const terminatorStart = /[\u001b\ud800-\udbff]$/.exec(held)?.[0] ?? ""; return { - visibleText: visibleText + (dropped ? "" : DROPPED_SEQUENCE_ST), + visibleText, pendingControlSequence: DROPPED_SEQUENCE + held.slice(0, 2) + terminatorStart, }; } From 911c4362e51fd6010dea47baf4b538ebba0e1ba9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 10:57:02 +0000 Subject: [PATCH 5/5] fix(server): terminal history is back in ground before any sequence it drops A dropped sequence writes nothing to history, so history must not leave anything open before it that the dropped ESC would have ended. A lone ESC that the next ESC restarts did nothing, so history leaves it out. A string the next ESC cuts short now gets its own ST, as that ESC ended it live, and an OSC 4 palette query is stripped whether or not it has a terminator, so the replay never answers it. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/terminal/Manager.test.ts | 24 +++++++++++++++----- apps/server/src/terminal/Manager.ts | 28 +++++++++--------------- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 21b8eb5cba050..ed74fa74590d6 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -493,8 +493,7 @@ 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 digits = "0123456789 123\r\n".repeat(64); - // The next ESC cuts this query short, so it goes to history with no terminator. Nothing the - // drop writes may end it, or the replay would answer it. + // The next ESC cuts this query short. History leaves it out, so the replay cannot answer it. const leftOpen = "\u001b]4;1;?"; // The terminal runs the carriage returns and line feeds inside a CSI while it waits for the // final byte. @@ -507,7 +506,7 @@ it("stops holding a control sequence that outgrows its limit", () => { name: "DCS, split code point", open: `${leftOpen}\u001bPstuck`, end: splitCodePoint, - history: () => `${leftOpen}\u001bE`, + history: () => "\u001bE", }, // Each piece's U+0090 ends the sequence before it and opens a DCS that the piece drops. { @@ -528,7 +527,20 @@ it("stops holding a control sequence that outgrows its limit", () => { name: "CSI, final byte", open: `${leftOpen}\u001b[`, end: ["\n6n"], - history: (fed: string) => `${leftOpen}${lineBreaks(fed)}\n`, + history: (fed: string) => `${lineBreaks(fed)}\n`, + }, + // History must be back in ground after a drop, as the live terminal is. + { + name: "CSI after a title the next ESC cuts short", + open: ["\u001b]0;title", "\u001b["], + end: ["31m"], + history: (fed: string) => `\u001b]0;title\u001b\\${lineBreaks(fed)}`, + }, + { + name: "OSC after a lone ESC", + open: ["\u001b", "\u001b]0;"], + end: ["\u0007\u009a"], + history: () => "\u009a", }, { name: "CSI, CAN", @@ -566,7 +578,7 @@ it("stops holding a control sequence that outgrows its limit", () => { const fed = filler.repeat(Math.ceil(limit / filler.length) + 2); feed("before\n"); - feed(open); + for (const data of [open].flat()) feed(data); for (let offset = 0; offset < fed.length; offset += filler.length) { feed(fed.slice(offset, offset + filler.length)); } @@ -1777,7 +1789,7 @@ it.layer( expect( reopened.history.startsWith( 'prompt \u001b[!p\u001b["p\u001b[4 q\u001b[u' + - "\u001b]4;1;red;2;?\u0007\u001b]0;t\u001b\\\u001b]4;3;?\u001b]0;x\u001b" + + "\u001b]4;1;red;2;?\u0007\u001b]0;t\u001b\\\u001b]0;x\u001b\\" + `\u001b[${"0".repeat(70_000)}31mXdone\n`, ), ).toBe(true); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 55fdd03966ca5..ebe82ad979738 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1345,7 +1345,7 @@ function findStringEnd( input: string, start: number, isOsc: boolean, -): { end: number; c1?: { effect: C1Effect; index: number } } | null { +): { end: number; cut?: true; c1?: { effect: C1Effect; index: number } } | null { for (let index = start; index < input.length; index += 1) { const codePoint = input.charCodeAt(index); if ((isOsc && codePoint === 0x07) || isControlSequenceCancel(codePoint)) { @@ -1354,7 +1354,7 @@ function findStringEnd( // Like xterm.js, an ESC that does not start ST ends the string and begins the next sequence. if (codePoint === 0x1b) { if (index + 1 >= input.length) return null; - return { end: input.charCodeAt(index + 1) === 0x5c ? index + 2 : index }; + return input.charCodeAt(index + 1) === 0x5c ? { end: index + 2 } : { end: index, cut: true }; } if (codePoint >= 0x80 && !isOsc) { const fullCodePoint = input.codePointAt(index) ?? codePoint; @@ -1529,29 +1529,20 @@ export function sanitizeTerminalHistoryChunk( } return { visibleText, pendingControlSequence: held }; } - const { end, c1 } = stringEnd; + const { end, cut, c1 } = stringEnd; const content = stripStringTerminator( prefix.slice(2) + input.slice(contentStart, c1?.index ?? end), ); - // ST ends what the query's ESC cut short and leaves ground state, as the query does when it - // 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 ( - nextCodePoint === 0x5d && - isOscPaletteQuery(content) && - /[\x07\x18\x1a]$|\x1b\\$/.test(input.slice(index, end)) - ) { - append("\u001b\\"); - index = end; - continue; - } const strip = dropped || (nextCodePoint === 0x5d && shouldStripOscSequence(content)) || + (nextCodePoint === 0x5d && isOscPaletteQuery(content)) || (nextCodePoint === 0x50 && shouldStripDcsSequence(content)); if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) { + // ST ends a string the next ESC cut short, as that ESC did, so history is in ground + // whatever becomes of the next sequence. if (!strip) { - append(prefix + input.slice(index, end)); + append(prefix + input.slice(index, end) + (cut ? "\u001b\\" : "")); } } else { // ST stands in for a code point that cannot be replayed as it came. @@ -1571,8 +1562,9 @@ export function sanitizeTerminalHistoryChunk( pendingControlSequence: input.slice(index, index + MAX_HELD_ESCAPE_LENGTH), }; } - // ESC Z (DECID) is the legacy primary device attributes query. - if (nextCodePoint !== 0x5a) { + // ESC Z (DECID) is the legacy primary device attributes query. A second ESC restarts the + // sequence, so the first does nothing. + if (nextCodePoint !== 0x5a && input.charCodeAt(escapeSequenceEndIndex) !== 0x1b) { append(input.slice(index, escapeSequenceEndIndex)); } index = escapeSequenceEndIndex;