Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2
3import {
4 appendTerminalOutput,
5 EMPTY_TERMINAL_OUTPUT,
6 normalizeTerminalOutput,
7 TERMINAL_PALETTES,
8 terminalOutputPlainText,
9 terminalOutputResumeText,
10 terminalOutputSpans,
11 terminalOutputTail,
12 type TerminalOutputState,
13} from "./terminalOutput.ts";
14
15function feed(chunks: ReadonlyArray<string>, maxChars?: number): TerminalOutputState {
16 return chunks.reduce(
17 (state, chunk) => appendTerminalOutput(state, chunk, maxChars),
18 EMPTY_TERMINAL_OUTPUT,
19 );
20}
21
22const plain = (input: string) => terminalOutputPlainText(normalizeTerminalOutput(input).text);
23
24describe("appendTerminalOutput", () => {
25 it("keeps colours as canonical codes that reset at each line end", () => {
26 expect(normalizeTerminalOutput("\u001b[1;32mPASS\u001b[0m ok\u001b]0;title\u0007\n").text).toBe(
27 "\u001b[0;1;32mPASS\u001b[0m ok\n",
28 );
29 // A colour left on across a newline is restated on the next line.
30 expect(normalizeTerminalOutput("\u001b[31mone\ntwo").text).toBe(
31 "\u001b[0;31mone\u001b[0m\n\u001b[0;31mtwo\u001b[0m",
32 );
33 });
34
35 it("keeps only the latest frame of a carriage-return progress bar", () => {
36 expect(feed(["[1/3]", "\r[2/3]", "\r[3/3] done\nnext"]).text).toBe("[3/3] done\nnext");
37 });
38
39 it("redraws several lines in place when the cursor moves up", () => {
40 // docker pull / pnpm style: print two bars, move up two lines, redraw both.
41 const frames = [
42 "layer a: 10%\nlayer b: 10%\n",
43 "\u001b[2A\u001b[2Klayer a: 60%\n\u001b[2Klayer b: 40%\n",
44 "\u001b[2A\u001b[2Klayer a: done\n\u001b[2Klayer b: done\n",
45 ];
46 expect(feed(frames).text).toBe("layer a: done\nlayer b: done\n");
47 });
48
49 it("erases from the cursor to the end of the screen", () => {
50 // log-update style: move up, clear everything below, print the new frame.
51 expect(plain("status 1\ndetail 1\n\u001b[2A\u001b[Jstatus 2\n")).toBe("status 2\n");
52 });
53
54 it("overwrites in place like a terminal: carriage return, backspace, columns", () => {
55 expect(plain("progress 100%\rdone\u001b[K")).toBe("done");
56 expect(plain("abc\b\bX")).toBe("aXc");
57 expect(plain("12345\u001b[3GX")).toBe("12X45");
58 });
59
60 it("treats CRLF as one newline even when the pair is split across chunks", () => {
61 const state = feed(["one\r", "\ntwo\r\n"]);
62 expect(state.text).toBe("one\ntwo\n");
63 expect(state.pending).toBe("");
64 });
65
66 it("holds an escape sequence split across chunks until it finishes", () => {
67 const first = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, "red: \u001b[3");
68 expect(first.text).toBe("red: ");
69 expect(feed(["red: \u001b[3", "1mR\u001b[0m"]).text).toBe("red: \u001b[0;31mR\u001b[0m");
70 });
71
72 it("drops binary control bytes but keeps tabs and replacement characters", () => {
73 expect(normalizeTerminalOutput("a\u0000b\u0007\tc�\u0090d").text).toBe("ab\tc�d");
74 });
75
76 it("keeps a bounded tail that starts on a fresh line", () => {
77 const lines = Array.from({ length: 2_000 }, (_, index) => `line ${index}`).join("\n");
78 const state = feed([lines], 1_000);
79 expect(state.truncated).toBe(true);
80 expect(state.text.length).toBeLessThanOrEqual(1_000);
81 expect(state.text.startsWith("line ")).toBe(true);
82 expect(state.text.endsWith("line 1999")).toBe(true);
83 });
84
85 it("stays bounded across many appends of huge output, including one endless line", () => {
86 let state = EMPTY_TERMINAL_OUTPUT;
87 for (let index = 0; index < 5_000; index += 1) {
88 state = appendTerminalOutput(state, "y\n".repeat(200), 4_096);
89 }
90 expect(state.text.length).toBeLessThanOrEqual(4_096);
91 expect(state.truncated).toBe(true);
92 for (let index = 0; index < 1_000; index += 1) {
93 state = appendTerminalOutput(state, ".".repeat(100), 4_096);
94 }
95 expect(state.text.length).toBeLessThanOrEqual(4_096);
96 expect(state.text.endsWith(".")).toBe(true);
97 });
98
99 it("hides a long string sequence's payload however it is split into chunks", () => {
100 const input = `a\u001b]0;${"t".repeat(100)}\u0007b`;
101 expect(feed([input]).text).toBe("ab");
102 expect(feed(["a\u001b]0;", "t".repeat(100), "\u0007b"]).text).toBe("ab");
103 expect(feed([`a\u001b]0;${"t".repeat(80)}`, "\u001b", "\\b"]).text).toBe("ab");
104 });
105
106 it("hides an SOS string sequence and its payload", () => {
107 expect(normalizeTerminalOutput("a\u001bXhidden \u001b\\b").text).toBe("ab");
108 });
109
110 it("drops an escape sequence that never terminates and resumes after it", () => {
111 expect(feed(["ok\u001b]", "x".repeat(200), "\nafter"]).text).toBe("ok\nafter");
112 });
113});
114
115describe("appendTerminalOutput edge cases from review", () => {
116 it("reads colon-form true colour with or without a colour-space id", () => {
117 const red = normalizeTerminalOutput("\u001b[38:2::255:0:0mR").text;
118 expect(red).toBe("\u001b[0;38;2;255;0;0mR\u001b[0m");
119 expect(normalizeTerminalOutput("\u001b[38:2:0:255:0:0mR").text).toBe(red);
120 });
121
122 it("clears only scrollback on ESC[3J", () => {
123 const lines = Array.from({ length: 70 }, (_, index) => `line ${index}`).join("\n");
124 const state = feed([lines, "\u001b[3J"]);
125 expect(state.text.startsWith("line 6\n")).toBe(true);
126 expect(state.text.endsWith("line 69")).toBe(true);
127 expect(state.truncated).toBe(true);
128 });
129
130 it("keeps the whole window within the tail when every line is long", () => {
131 const long = `${"x".repeat(900)}\n`;
132 const state = feed([long.repeat(64)], 4_096);
133 const windowChars = state.screen.lines.reduce(
134 (total, line) => total + line.reduce((sum, run) => sum + run.text.length, 0),
135 0,
136 );
137 expect(windowChars).toBeLessThanOrEqual(4_096);
138 expect(state.text.length).toBeLessThanOrEqual(4_096);
139 });
140
141 it("bounds long lines below a cursor that moved up", () => {
142 const long = `${"x".repeat(900)}\n`;
143 const state = feed([long.repeat(63), "\u001b[63A"], 4_096);
144 const windowChars = state.screen.lines.reduce(
145 (total, line) => total + line.reduce((sum, run) => sum + run.text.length, 0),
146 0,
147 );
148 expect(windowChars).toBeLessThanOrEqual(2 * 4_096);
149 });
150});
151
152describe("appendTerminalOutput under adversarial output", () => {
153 it("gives the same result however the output is split into chunks", () => {
154 const input = "abcdef\rX\u001b[31mred\u001b[0m\nnext line\r\u001b[2Kdone\n";
155 const whole = feed([input], 3).text;
156 for (let cut = 1; cut < input.length; cut += 1) {
157 expect(feed([input.slice(0, cut), input.slice(cut)], 3).text).toBe(whole);
158 }
159 expect(feed(["abcdef", "\rX"], 3).text).toBe(feed(["abcdef\rX"], 3).text);
160 });
161
162 it("handles a colour change on every character in linear time", () => {
163 const chunk = Array.from({ length: 200_000 }, (_, index) =>
164 index % 2 === 0 ? "\u001b[31mx" : "\u001b[32my",
165 ).join("");
166 const started = performance.now();
167 const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, chunk);
168 expect(performance.now() - started).toBeLessThan(2_000);
169 expect(terminalOutputPlainText(state.text).length).toBeLessThanOrEqual(64 * 1024);
170 });
171
172 it("keeps scrollback bounded while a single huge chunk scrolls", () => {
173 const state = appendTerminalOutput(
174 EMPTY_TERMINAL_OUTPUT,
175 "line of log output\n".repeat(200_000),
176 4_096,
177 );
178 expect(state.screen.settled.length).toBeLessThanOrEqual(2 * 4_096);
179 expect(state.truncated).toBe(true);
180 });
181});
182
183describe("terminalOutputResumeText", () => {
184 it("lets a viewer that starts from it apply later chunks exactly as the source does", () => {
185 // Mid-redraw: cursor two lines up, a colour on, and half an escape pending.
186 const chunks = [
187 "a: 1%\nb: 1%\n",
188 "\u001b[2A\u001b[2K\u001b[33ma: 5",
189 "0%\u001b[0",
190 "m\n\u001b[2Kb: 50%\n",
191 ];
192 const source = feed(chunks.slice(0, 3));
193 const viewer = appendTerminalOutput(
194 appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source)),
195 chunks[3]!,
196 );
197 expect(viewer.text).toBe(feed(chunks).text);
198 expect(terminalOutputPlainText(viewer.text)).toBe("a: 50%\nb: 50%\n");
199 });
200});
201
202describe("terminalOutputResumeText with a saved cursor or trimmed output", () => {
203 it("restores a cursor saved before the resync", () => {
204 const source = feed(["abc\u001b7def"]);
205 const viewer = appendTerminalOutput(
206 appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source)),
207 "\u001b8X",
208 );
209 expect(viewer.text).toBe("abcXef");
210 });
211
212 it("stays on the right line when early output was trimmed away", () => {
213 const lines = Array.from({ length: 40 }, (_, index) => `line ${index}`).join("\n");
214 const source = feed([lines, "\u001b[1A\rLINE"], 120);
215 const viewer = appendTerminalOutput(
216 appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source), 120),
217 " edited",
218 120,
219 );
220 expect(viewer.text).toBe(appendTerminalOutput(source, " edited", 120).text);
221 });
222
223 it("survives a huge cursor move without throwing", () => {
224 expect(() => normalizeTerminalOutput("a\u001b[999999999999Cb")).not.toThrow();
225 });
226});
227
228describe("terminalOutputTail", () => {
229 it("never begins on a lone low surrogate", () => {
230 const text = `${"a".repeat(10)}😀${"b".repeat(4)}`;
231 const tail = terminalOutputTail(text, 5);
232 expect(tail.text).toBe("bbbb");
233 });
234
235 it("never splits a colour code and keeps the colour in force when cutting a line", () => {
236 const text = `\u001b[0;32m${"g".repeat(100)}\u001b[0m`;
237 const cut = terminalOutputTail(text, 10).text;
238 expect(cut.startsWith("\u001b[0;32m")).toBe(true);
239 expect(terminalOutputPlainText(cut)).toMatch(/^g+$/u);
240 });
241});
242
243describe("terminalOutputSpans", () => {
244 it("resolves standard, 256-colour and true-colour codes against the palette", () => {
245 const text = normalizeTerminalOutput(
246 "\u001b[31mred\u001b[0m \u001b[1;38;5;196mhot\u001b[0m \u001b[38;2;1;2;3mrgb\u001b[0m",
247 ).text;
248 expect(terminalOutputSpans(text, TERMINAL_PALETTES.dark)).toEqual([
249 { text: "red", style: { color: TERMINAL_PALETTES.dark[1] } },
250 { text: " ", style: null },
251 { text: "hot", style: { color: "rgb(255,0,0)", fontWeight: "600" } },
252 { text: " ", style: null },
253 { text: "rgb", style: { color: "rgb(1,2,3)" } },
254 ]);
255 });
256
257 it("keeps text on a coloured background readable on either palette", () => {
258 // "PASS" badge: black on green; "FAIL" badge: grey-white on red.
259 const text = normalizeTerminalOutput(
260 "\u001b[30;42m PASS \u001b[0m\u001b[1;37;41m FAIL \u001b[0m",
261 ).text;
262 for (const palette of [TERMINAL_PALETTES.light, TERMINAL_PALETTES.dark]) {
263 for (const span of terminalOutputSpans(text, palette)) {
264 expect(span.style?.color === undefined).toBe(false);
265 }
266 }
267 const [pass, fail] = terminalOutputSpans(text, TERMINAL_PALETTES.light);
268 expect(pass?.style?.color).toBe("#ffffff");
269 expect(fail?.style?.color).toBe("#ffffff");
270 });
271
272 it("collapses the rest into plain text past the span limit", () => {
273 const text = normalizeTerminalOutput("\u001b[31mx\u001b[32my".repeat(50)).text;
274 const spans = terminalOutputSpans(text, TERMINAL_PALETTES.light, 10);
275 expect(spans.length).toBe(11);
276 expect(spans.at(-1)?.style).toBeNull();
277 expect(spans.map((span) => span.text).join("")).toBe("xy".repeat(50));
278 });
279});