Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 154 additions & 4 deletions apps/server/src/terminal/Manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -488,6 +489,155 @@ 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 digits = "0123456789 123\r\n".repeat(64);
// 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.
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, filler = digits, end, history } of [
{
name: "DCS, split code point",
open: `${leftOpen}\u001bPstuck`,
end: splitCodePoint,
history: () => "\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[",
filler: `\u0090${"y".repeat(limit)}`,
end: ["\u001b", "\\"],
history: () => "",
},
{ name: "OSC, BEL", open: "\u001b]0;", end: ["\u0007"], history: () => "" },
{
name: "OSC, ESC",
open: "\u001b]0;",
end: ["\u001b[31m"],
history: () => "\u001b[31m",
},
{
name: "CSI, final byte",
open: `${leftOpen}\u001b[`,
end: ["\n6n"],
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",
open: "\u001b[",
end: ["\u0018"],
history: (fed: string) => `${lineBreaks(fed)}`,
},
{
name: "CSI, U+0090",
open: "\u001b[",
end: ["\n\u0090kept\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[",
end: ["\n\u001b[31m"],
history: (fed: string) => `${lineBreaks(fed)}\n\u001b[31m`,
},
{
name: "CSI, split code point",
open: "\u001b[",
end: ["\n", ...splitCodePoint],
history: (fed: string) => `${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");
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));
}
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(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",
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",
pendingControlSequence: "\u0018\u001b]\u001b",
});
expect(afterOutput(`\u001b[\u009b${csi.slice(2)}\ud842`), "CSI past the limit").toEqual({
visibleText: "before\n",
pendingControlSequence: "\u0018\u001b[\ud842",
});
expect(afterOutput(`${string}\ud842`), "string past the limit, high surrogate").toEqual({
visibleText: "before\n",
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,
Expand Down Expand Up @@ -1628,8 +1778,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");

Expand All @@ -1639,8 +1789,8 @@ 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[${"0".repeat(5000)}31mXdone\n`,
"\u001b]4;1;red;2;?\u0007\u001b]0;t\u001b\\\u001b]0;x\u001b\\" +
`\u001b[${"0".repeat(70_000)}31mXdone\n`,
),
).toBe(true);
}),
Expand Down
105 changes: 67 additions & 38 deletions apps/server/src/terminal/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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;
Expand Down Expand Up @@ -1394,17 +1394,31 @@ 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 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. Nothing stands in for
// the dropped ESC: closing what history left open could dispatch a query on replay.
const DROPPED_SEQUENCE = "\u0018";

export function sanitizeTerminalHistoryChunk(
pendingControlSequence: string,
data: string,
): { visibleText: string; pendingControlSequence: string } {
if (pendingControlSequence.length === 0 && !HISTORY_SEQUENCE_START.test(data)) {
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.
Expand All @@ -1421,26 +1435,29 @@ 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)) {
return { visibleText, pendingControlSequence: input.slice(index) };
}

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)) {
if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) {
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;
Expand All @@ -1452,10 +1469,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 (!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;
Expand All @@ -1466,19 +1483,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 held = prefix + input.slice(index);
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 + executedControls(),
pendingControlSequence: `${DROPPED_SEQUENCE}\u001b[${surrogate}`,
};
}
return { visibleText, pendingControlSequence: held };
}
continue;
}
Expand All @@ -1495,30 +1517,32 @@ 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_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,
pendingControlSequence: DROPPED_SEQUENCE + held.slice(0, 2) + terminatorStart,
};
}
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.
Expand All @@ -1532,10 +1556,15 @@ 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) {
// 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;
Expand Down
Loading