Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2import {
3 applyTerminalAttachStreamEvent,
4 DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
5 INITIAL_TERMINAL_OUTPUT_CURSOR,
6 nextTerminalAttachSeedState,
7 readTerminalOutputUpdate,
8 terminalOutputText,
9 type TerminalBufferState,
10} from "@t3tools/client-runtime/state/terminal";
11β
12import { writeTerminalOutputUpdate } from "../../components/ThreadTerminalDrawer";
13import { GHOSTTY_CELL_WIDE, GhosttyTerminalCore, ghosttyCellText } from "./core";
14import { loadGhosttyRuntime } from "./runtime";
15β
16vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({
17 default: (await import("./vendor/ghostty-vt.wasm?inline")).default,
18}));
19vi.mock("./vendor/ghostty-write-pty.wasm?url&no-inline", async () => ({
20 default: (await import("./vendor/ghostty-write-pty.wasm?inline")).default,
21}));
22β
23function codepointView(codepoints: ReadonlyArray<number>): DataView {
24 const view = new DataView(new ArrayBuffer(codepoints.length * 4));
25 codepoints.forEach((codepoint, index) => view.setUint32(index * 4, codepoint, true));
26 return view;
27}
28β
29describe("ghosttyCellText", () => {
30 it("converts oversized grapheme clusters without hitting engine spread limits", () => {
31 const graphemeLength = 130_000;
32 const view = new DataView(new ArrayBuffer(graphemeLength * 4));
33 for (let index = 0; index < graphemeLength; index += 1) {
34 view.setUint32(index * 4, index === 0 ? "a".codePointAt(0)! : 0x301, true);
35 }
36 const text = ghosttyCellText(view, graphemeLength);
37 expect(text.length).toBe(graphemeLength);
38 expect(text.codePointAt(0)).toBe("a".codePointAt(0));
39 expect(text.codePointAt(1)).toBe(0x301);
40 expect(text.codePointAt(graphemeLength - 1)).toBe(0x301);
41 });
42β
43 it("converts small clusters including astral codepoints", () => {
44 const text = ghosttyCellText(codepointView([0x1f642, 0x20e3]), 2);
45 expect([...text]).toEqual(["\u{1F642}", "\u{20E3}"]);
46 });
47β
48 it("converts a single astral codepoint", () => {
49 expect(ghosttyCellText(codepointView([0x1f642]), 1)).toBe("π");
50 });
51β
52 it("returns an empty string for empty cells", () => {
53 expect(ghosttyCellText(codepointView([]), 0)).toBe("");
54 });
55});
56β
57describe("GhosttyTerminalCore snapshots", () => {
58 const cores = new Set<GhosttyTerminalCore>();
59β
60 async function createCore(onData: (data: string) => void = () => {}) {
61 const core = await GhosttyTerminalCore.create(
62 12,
63 3,
64 8,
65 16,
66 {
67 foreground: { r: 255, g: 255, b: 255 },
68 background: { r: 0, g: 0, b: 0 },
69 cursor: { r: 255, g: 255, b: 255 },
70 },
71 onData,
72 );
73 cores.add(core);
74 return core;
75 }
76β
77 function createSession(history: string) {
78 return applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
79 type: "snapshot",
80 snapshot: {
81 threadId: "terminal-stream-test",
82 terminalId: "term-1",
83 cwd: "/repo",
84 worktreePath: null,
85 status: "running",
86 pid: 123,
87 history,
88 exitCode: null,
89 exitSignal: null,
90 label: "Terminal",
91 updatedAt: "2026-09-04T00:00:00.000Z",
92 },
93 });
94 }
95β
96 function append(state: TerminalBufferState, data: string) {
97 return applyTerminalAttachStreamEvent(state, {
98 type: "output",
99 threadId: "terminal-stream-test",
100 terminalId: "term-1",
101 data,
102 });
103 }
104β
105 afterEach(() => {
106 for (const core of cores) core.dispose();
107 cores.clear();
108 vi.restoreAllMocks();
109 });
110β
111 it.each([
112 { code: "", key: "Backspace", expected: "\x7f" },
113 { code: "Unidentified", key: "Backspace", expected: "\x7f" },
114 { code: "Backspace", key: "Backspace", expected: "\x7f" },
115 { code: "Delete", key: "Backspace", expected: "\x1b[3~" },
116 { code: "", key: "a", expected: "a" },
117 { code: "", key: "Unidentified", expected: "" },
118 ])("encodes key $key with physical code '$code'", async ({ code, key, expected }) => {
119 const core = await createCore();
120 const event = {
121 code,
122 key,
123 repeat: false,
124 shiftKey: false,
125 ctrlKey: false,
126 altKey: false,
127 metaKey: false,
128 isComposing: false,
129 getModifierState: () => false,
130 } as unknown as KeyboardEvent;
131β
132 expect(core.encodeKey(event)).toBe(expected);
133 });
134β
135 it("preserves styles, wide cells, and selection after shared memory grows", async () => {
136 const core = await createCore();
137 const runtime = await loadGhosttyRuntime();
138 const grapheme = `e${"\u0301".repeat(64)}`;
139 core.write(`\x1b[1;3;4;8;9;53;38;2;123;45;67;48;2;9;8;7m${grapheme}\x1b[0mηπ`);
140 const cells = core.snapshot().rowData[0]!.cells;
141 expect(cells[0]).toEqual({
142 text: grapheme,
143 wide: 0,
144 foreground: { r: 123, g: 45, b: 67 },
145 background: { r: 9, g: 8, b: 7 },
146 bold: true,
147 italic: true,
148 invisible: true,
149 strikethrough: true,
150 overline: true,
151 underline: true,
152 selected: false,
153 });
154 expect(cells.slice(1, 5).map(({ text, wide }) => ({ text, wide }))).toEqual([
155 { text: "η", wide: 0 },
156 { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
157 { text: "π", wide: 0 },
158 { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
159 ]);
160β
161 runtime.memory.grow(1);
162 core.setSelection({ x: 0, y: 0 }, { x: 2, y: 0 });
163 expect(core.snapshot().rowData[0]!.cells[0]).toEqual({ ...cells[0], selected: true });
164 core.clearSelection();
165 expect(core.snapshot().rowData[0]!.cells[0]).toEqual(cells[0]);
166β
167 core.resetAndWrite("\x1b[2;7;38;2;40;100;200;48;2;12;34;56mC\x1b[0m");
168 expect(core.snapshot().rowData[0]!.cells[0]).toMatchObject({
169 text: "C",
170 foreground: { r: 22, g: 59, b: 112 },
171 background: { r: 40, g: 100, b: 200 },
172 bold: false,
173 underline: false,
174 selected: false,
175 });
176 });
177β
178 it("resolves foreground and background independently without retaining prior cell colors", async () => {
179 const core = await createCore();
180 core.write(
181 "\x1b[38;2;123;45;67mF\x1b[39;48;2;9;8;7mB\x1b[0mD\x1b[38;2;12;34;56;48;2;78;90;123mC\x1b[0mE",
182 );
183 expect(
184 core
185 .snapshot()
186 .rowData[0]!.cells.slice(0, 6)
187 .map(({ text, foreground, background }) => ({ text, foreground, background })),
188 ).toEqual([
189 { text: "F", foreground: { r: 123, g: 45, b: 67 }, background: { r: 0, g: 0, b: 0 } },
190 { text: "B", foreground: { r: 255, g: 255, b: 255 }, background: { r: 9, g: 8, b: 7 } },
191 { text: "D", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
192 { text: "C", foreground: { r: 12, g: 34, b: 56 }, background: { r: 78, g: 90, b: 123 } },
193 { text: "E", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
194 { text: "", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
195 ]);
196 });
197β
198 it("paints ANSI colors from the theme palette and repaints them on theme change", async () => {
199 const core = await createCore();
200 const theme = {
201 foreground: { r: 255, g: 255, b: 255 },
202 background: { r: 0, g: 0, b: 0 },
203 cursor: { r: 255, g: 255, b: 255 },
204 };
205 const palette = Array.from({ length: 16 }, (_, index) => ({ r: index, g: 1, b: 2 }));
206 core.write("\x1b[31mR\x1b[38;5;196mX\x1b[0m");
207 core.setTheme({ ...theme, palette });
208 let cells = core.snapshot().rowData[0]!.cells;
209 expect(cells[0]!.foreground).toEqual({ r: 1, g: 1, b: 2 });
210 expect(cells[1]!.foreground).toEqual({ r: 255, g: 0, b: 0 });
211β
212 core.setTheme({ ...theme, palette: palette.map((color) => ({ ...color, g: 9 })) });
213 cells = core.snapshot().rowData[0]!.cells;
214 expect(cells[0]!.foreground).toEqual({ r: 1, g: 9, b: 2 });
215 expect(cells[1]!.foreground).toEqual({ r: 255, g: 0, b: 0 });
216 });
217β
218 it("reuses a grown grapheme buffer and releases it on disposal", async () => {
219 const core = await createCore();
220 const runtime = await loadGhosttyRuntime();
221 core.write("ASCII");
222 core.snapshot();
223β
224 const grapheme = `z${"\u0301".repeat(256)}`;
225 core.resetAndWrite(`${grapheme}X`);
226 const alloc = vi.spyOn(runtime, "alloc");
227 const free = vi.spyOn(runtime, "free");
228 expect(
229 core
230 .snapshot()
231 .rowData[0]!.cells.slice(0, 2)
232 .map((cell) => cell.text),
233 ).toEqual([grapheme, "X"]);
234 expect(alloc).toHaveBeenCalledTimes(1);
235 const allocation = alloc.mock.results[0]!;
236 if (allocation.type !== "return") throw new Error("Grapheme allocation did not return");
237 const buffer = allocation.value;
238 const capacity = alloc.mock.calls[0]![0];
239β
240 core.write("\rQ\u0301");
241 alloc.mockClear();
242 expect(core.snapshot().rowData[0]!.cells[0]!.text).toBe("Q\u0301");
243 expect(alloc).not.toHaveBeenCalled();
244 core.dispose();
245 expect(free).toHaveBeenCalledWith(buffer, capacity);
246 });
247β
248 it.each(["varied", "identical"] as const)(
249 "preserves Ghostty state through a full MiB of %s output without rollover resets",
250 async (kind) => {
251 const [core, reference] = await Promise.all([createCore(), createCore()]);
252 const initial = "\x1b[31m";
253 let state = createSession(initial);
254 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
255 writeTerminalOutputUpdate(core, first);
256 reference.resetAndWrite(initial);
257 let cursor = first.cursor;
258 const reset = vi.spyOn(core, "resetAndWrite");
259 const inputs: string[] = [];
260 let receivedCharacters = 0;
261β
262 for (let index = 0; index < 128; index += 1) {
263 const data =
264 kind === "identical"
265 ? "x".repeat(8192)
266 : `${index.toString().padStart(4, "0")}\r\n${"x".repeat(8186)}`;
267 inputs.push(data);
268 state = append(state, data);
269 const update = readTerminalOutputUpdate(state.output, cursor);
270 if (update.type !== "append") throw new Error(`Expected append, received ${update.type}`);
271 receivedCharacters += update.data.length;
272 writeTerminalOutputUpdate(core, update);
273 cursor = update.cursor;
274 }
275β
276 reference.write(inputs.join(""));
277 expect(receivedCharacters).toBe(1024 * 1024);
278 expect(state.output.retainedBytes).toBe(DEFAULT_MAX_TERMINAL_BUFFER_BYTES);
279 expect(reset).not.toHaveBeenCalled();
280 expect(core.snapshot()).toEqual(reference.snapshot());
281 },
282 );
283β
284 it("preserves Unicode and split ANSI parser state across batched renderer reads", async () => {
285 const [core, reference] = await Promise.all([createCore(), createCore()]);
286 let state = createSession("");
287 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
288 writeTerminalOutputUpdate(core, first);
289 let cursor = first.cursor;
290 const reset = vi.spyOn(core, "resetAndWrite");
291 const inputs = [
292 `${"a".repeat(16_383)}π`,
293 "\x1b[3",
294 "1m",
295 "e",
296 "\u0301ηπ",
297 "\x1b[0",
298 "m\r\n",
299 "\x1b]8;;https://t3.codes\x1b",
300 "\\link",
301 "\x1b]8;;\x1b",
302 "\\\x1b[?1049h",
303 "alternate",
304 "\x1b[?1049l",
305 "\r\nend",
306 ];
307 let received = "";
308 for (const [index, data] of inputs.entries()) {
309 state = append(state, data);
310 if (index % 3 !== 0 && index !== inputs.length - 1) continue;
311 const update = readTerminalOutputUpdate(state.output, cursor);
312 if (update.type !== "append") throw new Error(`Expected append, received ${update.type}`);
313 received += update.data;
314 writeTerminalOutputUpdate(core, update);
315 cursor = update.cursor;
316 }
317β
318 reference.write(inputs.join(""));
319 expect(received).toBe(inputs.join(""));
320 expect(reset).not.toHaveBeenCalled();
321 expect(core.snapshot()).toEqual(reference.snapshot());
322 });
323β
324 it("answers a live VT query when batched reads cross a chunk compaction", async () => {
325 const replies: string[] = [];
326 const core = await createCore((data) => replies.push(data));
327 core.write("\x1b[5n");
328 expect(replies).toEqual(["\x1b[0n"]);
329 replies.length = 0;
330β
331 let state = createSession("");
332 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
333 writeTerminalOutputUpdate(core, initial);
334 let cursor = initial.cursor;
335 for (let index = 0; index < 1000; index += 1) {
336 state = append(state, "x");
337 const update = readTerminalOutputUpdate(state.output, cursor);
338 writeTerminalOutputUpdate(core, update);
339 cursor = update.cursor;
340 }
341 for (let index = 0; index < 24; index += 1) state = append(state, "x");
342 state = append(state, "\x1b[5n");
343 const update = readTerminalOutputUpdate(state.output, cursor);
344 writeTerminalOutputUpdate(core, update);
345β
346 expect({ type: update.type, replies }).toEqual({ type: "append", replies: ["\x1b[0n"] });
347 });
348β
349 it("recovers a lagging renderer once from bounded output and resumes appending", async () => {
350 const [core, reference] = await Promise.all([createCore(), createCore()]);
351 let state = createSession("\x1b[31mold");
352 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
353 writeTerminalOutputUpdate(core, initial);
354 const reset = vi.spyOn(core, "resetAndWrite");
355 const data = "line\r\n".repeat(8192);
356 for (let index = 0; index < 16; index += 1) state = append(state, data);
357β
358 const recovery = readTerminalOutputUpdate(state.output, initial.cursor);
359 if (recovery.type !== "reset") throw new Error(`Expected reset, received ${recovery.type}`);
360 expect(new TextEncoder().encode(recovery.data).byteLength).toBe(
361 DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
362 );
363 writeTerminalOutputUpdate(core, recovery);
364 reference.resetAndWrite(recovery.data);
365 expect(core.snapshot()).toEqual(reference.snapshot());
366β
367 state = append(state, "\r\nlatest");
368 const next = readTerminalOutputUpdate(state.output, recovery.cursor);
369 expect(next.type).toBe("append");
370 writeTerminalOutputUpdate(core, next);
371 reference.write("\r\nlatest");
372 expect(reset).toHaveBeenCalledTimes(1);
373 expect(core.snapshot()).toEqual(reference.snapshot());
374 });
375β
376 it("replays the latest retained output when WASM arrives after several events", async () => {
377 const pendingCore = createCore();
378 let state = createSession("before");
379 state = append(state, "\r\nduring ");
380 state = append(state, "π load");
381 const core = await pendingCore;
382 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
383 writeTerminalOutputUpdate(core, first);
384 const reference = await createCore();
385 reference.resetAndWrite(terminalOutputText(state.output));
386 const reset = vi.spyOn(core, "resetAndWrite");
387β
388 state = append(state, "\r\nafter");
389 const next = readTerminalOutputUpdate(state.output, first.cursor);
390 expect(next).toMatchObject({ type: "append", data: "\r\nafter" });
391 writeTerminalOutputUpdate(core, next);
392 reference.write("\r\nafter");
393 expect(reset).not.toHaveBeenCalled();
394 expect(core.snapshot()).toEqual(reference.snapshot());
395 });
396β
397 it("resets real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => {
398 const [core, reference] = await Promise.all([createCore(), createCore()]);
399 let state = createSession("hello");
400 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
401 writeTerminalOutputUpdate(core, initial);
402 let cursor = initial.cursor;
403β
404 const snapshot = {
405 threadId: "terminal-stream-test",
406 terminalId: "term-1",
407 cwd: "/repo",
408 worktreePath: null,
409 status: "running" as const,
410 pid: 456,
411 history: "hello",
412 exitCode: null,
413 exitSignal: null,
414 label: "Terminal",
415 updatedAt: "2026-09-04T00:00:01.000Z",
416 };
417 const events = [
418 { type: "snapshot", snapshot },
419 { type: "cleared", threadId: snapshot.threadId, terminalId: snapshot.terminalId },
420 { type: "restarted", threadId: snapshot.threadId, terminalId: snapshot.terminalId, snapshot },
421 ] as const;
422 for (const event of events) {
423 core.write("\r\nstale local text");
424 state = applyTerminalAttachStreamEvent(state, event);
425 const update = readTerminalOutputUpdate(state.output, cursor);
426 expect(update.type).toBe("reset");
427 writeTerminalOutputUpdate(core, update);
428 cursor = update.cursor;
429 reference.resetAndWrite(event.type === "cleared" ? "" : "hello");
430 expect(core.snapshot()).toEqual(reference.snapshot());
431 }
432β
433 core.write("\r\nstale local text");
434 state = createSession("hello");
435 const reattached = readTerminalOutputUpdate(state.output, cursor);
436 expect(reattached.type).toBe("reset");
437 writeTerminalOutputUpdate(core, reattached);
438 reference.resetAndWrite("hello");
439 expect(core.snapshot()).toEqual(reference.snapshot());
440 });
441});