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_OUTPUT_TAIL_CHARS,
8 TERMINAL_PALETTES,
9 terminalOutputPlainText,
10 terminalOutputResumeText,
11 terminalOutputSpans,
12 terminalOutputTail,
13 type TerminalOutputState,
14} from "./terminalOutput.ts";
15
16function feed(chunks: ReadonlyArray<string>, maxChars?: number): TerminalOutputState {
17 return chunks.reduce(
18 (state, chunk) => appendTerminalOutput(state, chunk, maxChars),
19 EMPTY_TERMINAL_OUTPUT,
20 );
21}
22
23describe("appendTerminalOutput", () => {
24 it("keeps only the latest frame of a carriage-return progress bar", () => {
25 expect(feed(["[1/3]", "\r[2/3]", "\r[3/3] done\nnext"]).text).toBe("[3/3] done\nnext");
26 });
27
28 it.each([
29 ["😀\u001b[1Gx", "x "],
30 ["界a\u001b[3GZ", "界Z"],
31 ["e\u0301a\u001b[2GZ", "e\u0301Z"],
32 ["𐐀a\u001b[2GZ", "𐐀Z"],
33 ["界a\bZ", "界Z"],
34 ["界a\u001b[2GZ", " Za"],
35 ["a界b\rXY", "XY b"],
36 ["e\u0301a\rZ", "Za"],
37 ["界a\u001b[2G\u001b[K", " "],
38 ["界a\u001b[1G\u001b[1K", " a"],
39 ["\u001b[31m界\u001b[32ma\u001b[3GZ", "界Z"],
40 ["e\u001b[31m\u0301a\u001b[1GZ", "Za"],
41 ])("overwrites Unicode at terminal columns: %j", (input, expected) => {
42 expect(terminalOutputPlainText(feed([input]).text)).toBe(expected);
43 for (let cut = 1; cut < input.length; cut += 1) {
44 const source = feed([input.slice(0, cut)]);
45 const chunk = input.slice(cut);
46 expect(terminalOutputPlainText(appendTerminalOutput(source, chunk).text)).toBe(expected);
47 expect(terminalOutputPlainText(feed([terminalOutputResumeText(source), chunk]).text)).toBe(
48 expected,
49 );
50 }
51 });
52
53 it("redraws several lines in place when the cursor moves up", () => {
54 const frames = [
55 "layer a: 10%\nlayer b: 10%\n",
56 "\u001b[2A\u001b[2Klayer a: 60%\n\u001b[2Klayer b: 40%\n",
57 "\u001b[2A\u001b[2Klayer a: done\n\u001b[2Klayer b: done\n",
58 ];
59 expect(feed(frames).text).toBe("layer a: done\nlayer b: done\n");
60 });
61
62 it("treats CRLF as one newline even when the pair is split across chunks", () => {
63 const state = feed(["one\r", "\ntwo\r\n"]);
64 expect(state.text).toBe("one\ntwo\n");
65 expect(state.pending).toBe("");
66 });
67
68 it("holds an escape sequence split across chunks until it finishes", () => {
69 const first = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, "red: \u001b[3");
70 expect(first.text).toBe("red: ");
71 expect(feed(["red: \u001b[3", "1mR\u001b[0m"]).text).toBe("red: \u001b[0;31mR\u001b[0m");
72 expect(
73 terminalOutputSpans(feed(["\u001b[38:2::12:", "34:56mR"]).text, TERMINAL_PALETTES.dark),
74 ).toEqual([{ text: "R", style: { color: "rgb(12,34,56)" } }]);
75 });
76
77 it.each(["\u001b[3", "\u001b]0;title"])(
78 "keeps output after CAN or SUB cancels %j, wherever the chunk splits",
79 (sequence) => {
80 for (const cancel of ["\u0018", "\u001a"]) {
81 const input = `before${sequence}${cancel}Ready`;
82 for (let cut = 0; cut <= input.length; cut += 1) {
83 expect(feed([input.slice(0, cut), input.slice(cut)]).text).toBe("beforeReady");
84 }
85 }
86 },
87 );
88
89 it("keeps a bounded tail that starts on a fresh line", () => {
90 const lines = Array.from({ length: 2_000 }, (_, index) => `line ${index}`).join("\n");
91 const state = feed([lines], 1_000);
92 expect(state.truncated).toBe(true);
93 expect(state.text.length).toBeLessThanOrEqual(1_000);
94 expect(state.text.startsWith("line ")).toBe(true);
95 expect(state.text.endsWith("line 1999")).toBe(true);
96 // A newline a quarter of the budget past the cut is too far to start on.
97 expect(feed(["abcdefgh\nij\nklmnop"], 8).text).toBe("klmnop");
98 expect(feed(["abcdefgh\nijk\nlmnop"], 8).text).toBe("jk\nlmnop");
99 });
100
101 it("keeps Unicode tails bounded without shifting saved cursor columns", () => {
102 const source = feed(["界界e\u0301\u001b7ab"], 4);
103 expect(source.text).toBe("e\u0301ab");
104 expect(source.screen.col).toBe(3);
105 expect(source.screen.saved?.col).toBe(1);
106 expect(appendTerminalOutput(source, "\u001b8Z", 4).text).toBe("e\u0301Zb");
107 expect(feed([terminalOutputResumeText(source), "\u001b8Z"], 4).text).toBe("e\u0301Zb");
108 expect(feed(["𐐀a"], 2).text).toBe("a");
109 expect(feed(["e\u0301ab"], 3).text).toBe("ab");
110 const wide = feed(["界".repeat(40_000), "\u001b7"]);
111 expect(feed([terminalOutputResumeText(wide)]).screen.col).toBe(wide.screen.col);
112 });
113
114 it.each([".", "界", "😀", "\u001b[31m界\u001b[0m"])(
115 "stays bounded across many appends of huge output, including one endless line of %s",
116 (character) => {
117 let state = EMPTY_TERMINAL_OUTPUT;
118 for (let index = 0; index < 5_000; index += 1) {
119 state = appendTerminalOutput(state, "y\n".repeat(200), 4_096);
120 }
121 expect(state.text.length).toBeLessThanOrEqual(4_096);
122 expect(state.truncated).toBe(true);
123 for (let index = 0; index < 1_000; index += 1) {
124 state = appendTerminalOutput(state, character.repeat(100), 4_096);
125 }
126 expect(terminalOutputPlainText(state.text).length).toBeLessThanOrEqual(4_096);
127 expect(terminalOutputPlainText(state.text).endsWith(terminalOutputPlainText(character))).toBe(
128 true,
129 );
130 },
131 );
132
133 it("hides a long string sequence's payload however it is split into chunks", () => {
134 const input = `a\u001b]0;${"t".repeat(100)}\u0007b`;
135 expect(feed([input]).text).toBe("ab");
136 expect(feed(["a\u001b]0;", "t".repeat(100), "\u0007b"]).text).toBe("ab");
137 expect(feed([`a\u001b]0;${"t".repeat(80)}`, "\u001b", "\\b"]).text).toBe("ab");
138 });
139
140 it("drops an escape sequence that never terminates and resumes after it", () => {
141 expect(feed(["ok\u001b]", "x".repeat(200), "\nafter"]).text).toBe("ok\nafter");
142 expect(feed(["ok\u001b]0;title\u001b", "\u001b[31mred"]).text).toBe(
143 "ok\u001b[0;31mred\u001b[0m",
144 );
145 for (const input of ["a\u001b[1;\u001b[32mb\u001b[0m", "a\u001b[\u001b[32mb"]) {
146 expect(normalizeTerminalOutput(input).text).toBe("a\u001b[0;32mb\u001b[0m");
147 for (let cut = 1; cut < input.length; cut += 1) {
148 expect(feed([input.slice(0, cut), input.slice(cut)]).text).toBe("a\u001b[0;32mb\u001b[0m");
149 }
150 }
151 });
152});
153
154describe("appendTerminalOutput edge cases from review", () => {
155 const boldRed = { color: TERMINAL_PALETTES.dark[1], fontWeight: "600" } as const;
156 it.each([
157 [
158 "a curly underline",
159 "\u001b[1;31m\u001b[4:3mX",
160 { ...boldRed, textDecorationLine: "underline" },
161 ],
162 ["underline off in colon form", "\u001b[1;31m\u001b[4:0mX", boldRed],
163 ["a true-colour underline colour", "\u001b[1;31m\u001b[58;2;255;0;0mX", boldRed],
164 ["a 256-colour underline colour", "\u001b[58;5;31mX", null],
165 [
166 "a colon-form underline colour",
167 "\u001b[4m\u001b[58:2::255:0:0mX",
168 { textDecorationLine: "underline" },
169 ],
170 ["extra fields in a colon-form indexed underline colour", "\u001b[58:5:0:32mX", null],
171 [
172 "extra fields in a colon-form indexed colour",
173 "\u001b[38:5:1:4mX",
174 { color: TERMINAL_PALETTES.dark[1] },
175 ],
176 [
177 "a true colour with its fields after colons",
178 "\u001b[38;2:255:0:0;1mX",
179 { color: "rgb(255,0,0)", fontWeight: "600" },
180 ],
181 [
182 "an indexed colour with its index after a colon",
183 "\u001b[38;5:1;4mX",
184 { color: TERMINAL_PALETTES.dark[1], textDecorationLine: "underline" },
185 ],
186 [
187 "a semicolon-form colour value that looks like a colour code",
188 "\u001b[38;5;38;2:1:2:3mX",
189 { color: "rgb(0,175,215)", opacity: 0.65 },
190 ],
191 ])("reads %s without disturbing the other attributes", (_, input, style) => {
192 const text = normalizeTerminalOutput(input).text;
193 expect(terminalOutputSpans(text, TERMINAL_PALETTES.dark)).toEqual([{ text: "X", style }]);
194 for (let cut = 1; cut < input.length; cut += 1) {
195 expect(feed([input.slice(0, cut), input.slice(cut)]).text).toBe(text);
196 }
197 });
198
199 it("leaves the screen and cursor alone for unsupported erase modes", () => {
200 for (const sequence of ["3K", "4J", "99K", "99J"]) {
201 const input = `a\nb\nc\u001b[${sequence}X`;
202 expect(feed([input]).text).toBe("a\nb\ncX");
203 for (let cut = 1; cut < input.length; cut += 1) {
204 expect(feed([input.slice(0, cut), input.slice(cut)]).text).toBe("a\nb\ncX");
205 }
206 }
207 });
208
209 it("clears only scrollback on ESC[3J", () => {
210 const lines = Array.from({ length: 70 }, (_, index) => `line ${index}`).join("\n");
211 const state = feed([lines, "\u001b[3J"]);
212 expect(state.text.startsWith("line 6\n")).toBe(true);
213 expect(state.text.endsWith("line 69")).toBe(true);
214 expect(state.truncated).toBe(true);
215 });
216
217 it("keeps the whole window within the tail when every line is long", () => {
218 const long = `${"x".repeat(900)}\n`;
219 const state = feed([long.repeat(64)], 4_096);
220 const windowChars = state.screen.lines.reduce(
221 (total, line) => total + line.reduce((sum, run) => sum + run.text.length, 0),
222 0,
223 );
224 expect(windowChars).toBeLessThanOrEqual(4_096);
225 expect(state.text.length).toBeLessThanOrEqual(4_096);
226 for (const prefix of ["😀", "e\u0301"]) {
227 expect(feed([`a\n${prefix}bx\nZ\u001b[2A`], 4).text).toBe("bx\nZ");
228 }
229 });
230});
231
232describe("appendTerminalOutput under adversarial output", () => {
233 it("ignores unsupported cursor-control parameters without corrupting the screen", () => {
234 for (const sequence of ["1.5A", "1.5G", "1$K", "1$J", ">1A", "?25l", "1:2A", "1:2K", "1:2J"]) {
235 const input = `a\nb\nc\u001b[${sequence}X`;
236 expect(feed([input]).text).toBe("a\nb\ncX");
237 for (let cut = 1; cut < input.length; cut += 1) {
238 expect(feed([input.slice(0, cut), input.slice(cut)]).text).toBe("a\nb\ncX");
239 }
240 }
241 });
242
243 it("drops escape sequences with intermediate bytes without printing their final byte", () => {
244 for (const sequence of ["#8", "#6", "%G", " F", "-A", ".A", "(%5", "(B"]) {
245 const input = `a\u001b${sequence}b`;
246 expect(feed([input]).text).toBe("ab");
247 for (let cut = 1; cut < input.length; cut += 1) {
248 expect(feed([input.slice(0, cut), input.slice(cut)]).text).toBe("ab");
249 }
250 }
251 for (const [interrupted, expected] of [
252 ["a\u001b#\u001b[31mb", feed(["a\u001b[31mb"]).text],
253 ["a\u001b#\n8b", "a\n8b"],
254 ] as const) {
255 for (let cut = 0; cut < interrupted.length; cut += 1) {
256 expect(feed([interrupted.slice(0, cut), interrupted.slice(cut)]).text).toBe(expected);
257 }
258 }
259 });
260
261 it("consumes an escape followed by an emoji whole, however it is split", () => {
262 for (const [input, expected] of [
263 ["a\u001b😀b", "ab"],
264 ["a\u001b\ud83dX", "aX"],
265 ] as const) {
266 expect(normalizeTerminalOutput(input).text).toBe(expected);
267 for (let cut = 1; cut < input.length; cut += 1) {
268 expect(feed([input.slice(0, cut), input.slice(cut)]).text).toBe(expected);
269 }
270 }
271 });
272
273 it("gives the same result however the output is split into chunks", () => {
274 const input =
275 "abcdef\rX\u001b[31mred\u001b[0m\nnext line\r\u001b[2Kdone\n" +
276 "\u001b[1;31mbold red\u001b[mplain\u001b[38:2::12:34:56mrgb\u001b[0m\n" +
277 "\u001b[1;31mbold red again\u001b[mplain again\u001b[38:2::12:34:56mrgb again\u001b[0m";
278 for (const maxChars of [3, 1_024]) {
279 const whole = feed([input], maxChars).text;
280 for (let cut = 1; cut < input.length; cut += 1) {
281 expect(feed([input.slice(0, cut), input.slice(cut)], maxChars).text).toBe(whole);
282 }
283 }
284 expect(feed(["abcdef", "\rX"], 3).text).toBe(feed(["abcdef\rX"], 3).text);
285 });
286});
287
288describe("terminalOutputResumeText", () => {
289 it("lets a viewer that starts from it apply later chunks exactly as the source does", () => {
290 const chunks = [
291 "a: 1%\nb: 1%\n",
292 "\u001b[2A\u001b[2K\u001b[33ma: 5",
293 "0%\u001b[0",
294 "m\n\u001b[2Kb: 50%\n",
295 ];
296 const source = feed(chunks.slice(0, 3));
297 const viewer = appendTerminalOutput(
298 appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source)),
299 chunks[3]!,
300 );
301 expect(viewer.text).toBe(feed(chunks).text);
302 expect(terminalOutputPlainText(viewer.text)).toBe("a: 50%\nb: 50%\n");
303 });
304});
305
306describe("terminalOutputResumeText with a saved cursor or trimmed output", () => {
307 it("restores a cursor saved before the resync", () => {
308 const source = feed(["界e\u0301\u001b7def"]);
309 const viewer = appendTerminalOutput(
310 appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source)),
311 "\u001b8X",
312 );
313 expect(viewer.text).toBe("界e\u0301Xef");
314 });
315
316 it("stays on the right line when early output was trimmed away", () => {
317 const lines = Array.from({ length: 40 }, (_, index) => `line ${index}`).join("\n");
318 const source = feed([lines, "\u001b[1A\rLINE"], 120);
319 const viewer = appendTerminalOutput(
320 appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source), 120),
321 " edited",
322 120,
323 );
324 expect(viewer.text).toBe(appendTerminalOutput(source, " edited", 120).text);
325 });
326
327 it("keeps scrollback when a redraw after a cleared screen moves above the live window", () => {
328 const history = "Build started\n";
329 const source = feed([history + "working\n".repeat(63), "\u001b[2J", "Progress: 10%"]);
330 const redraw = "\u001b[1A\r\u001b[2KProgress: 20%";
331 expect(feed([terminalOutputResumeText(source), redraw]).text).toBe(history + "Progress: 20%");
332 });
333
334 it("recovers scrollback hidden by a full output tail once a redraw shortens it", () => {
335 const history = "Build started\n";
336 const progress = "x".repeat(TERMINAL_OUTPUT_TAIL_CHARS);
337 const source = feed([history + "working\n".repeat(63) + "\u001b[2J" + progress]);
338 const viewer = feed([terminalOutputResumeText(source)]);
339 expect(viewer.text).toBe(progress);
340 const redraw = "\r\u001b[2KProgress: done";
341 expect(appendTerminalOutput(viewer, redraw).text).toBe(history + "Progress: done");
342 });
343});
344
345describe("terminalOutputTail", () => {
346 it("never begins on a lone low surrogate", () => {
347 const text = `${"a".repeat(10)}😀${"b".repeat(4)}`;
348 const tail = terminalOutputTail(text, 5);
349 expect(tail.text).toBe("bbbb");
350 });
351});
352
353describe("terminalOutputSpans", () => {
354 it("collapses the rest into plain text past the span limit", () => {
355 const text = normalizeTerminalOutput("\u001b[31mx\u001b[32my".repeat(50)).text;
356 const spans = terminalOutputSpans(text, TERMINAL_PALETTES.light, 10);
357 expect(spans.length).toBe(11);
358 expect(spans.at(-1)?.style).toBeNull();
359 expect(spans.map((span) => span.text).join("")).toBe("xy".repeat(50));
360 });
361
362 it("gives badge text at least 3:1 on the dark palette's coloured backgrounds", () => {
363 const text = normalizeTerminalOutput("\u001b[42m PASS \u001b[1;37;41m FAIL ").text;
364 const spans = terminalOutputSpans(text, TERMINAL_PALETTES.dark);
365 expect(spans.map((span) => span.style?.color)).toEqual(["#1f2328", "#1f2328"]);
366 });
367});