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 // regression: #7809 oversized terminal graphemes crashed rendering
44 it("converts small clusters including astral codepoints", () => {
45 const text = ghosttyCellText(codepointView([0x1f642, 0x20e3]), 2);
46 expect([...text]).toEqual(["\u{1F642}", "\u{20E3}"]);
47 });
48});
49
50describe("GhosttyTerminalCore snapshots", () => {
51 const cores = new Set<GhosttyTerminalCore>();
52
53 async function createCore(onData: (data: string) => void = () => {}) {
54 const core = await GhosttyTerminalCore.create(
55 12,
56 3,
57 8,
58 16,
59 {
60 foreground: { r: 255, g: 255, b: 255 },
61 background: { r: 0, g: 0, b: 0 },
62 cursor: { r: 255, g: 255, b: 255 },
63 },
64 onData,
65 );
66 cores.add(core);
67 return core;
68 }
69
70 function createSession(history: string) {
71 return applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
72 type: "snapshot",
73 snapshot: {
74 threadId: "terminal-stream-test",
75 terminalId: "term-1",
76 cwd: "/repo",
77 worktreePath: null,
78 status: "running",
79 pid: 123,
80 history,
81 exitCode: null,
82 exitSignal: null,
83 label: "Terminal",
84 updatedAt: "2026-09-04T00:00:00.000Z",
85 },
86 });
87 }
88
89 function append(state: TerminalBufferState, data: string) {
90 return applyTerminalAttachStreamEvent(state, {
91 type: "output",
92 threadId: "terminal-stream-test",
93 terminalId: "term-1",
94 data,
95 });
96 }
97
98 afterEach(() => {
99 for (const core of cores) core.dispose();
100 cores.clear();
101 vi.restoreAllMocks();
102 });
103
104 it.each([
105 { code: "", key: "Backspace", expected: "\x7f" },
106 { code: "Unidentified", key: "Backspace", expected: "\x7f" },
107 { code: "Backspace", key: "Backspace", expected: "\x7f" },
108 { code: "Delete", key: "Backspace", expected: "\x1b[3~" },
109 { code: "", key: "a", expected: "a" },
110 { code: "", key: "Unidentified", expected: "" },
111 ])("encodes key $key with physical code '$code'", async ({ code, key, expected }) => {
112 const core = await createCore();
113 const event = {
114 code,
115 key,
116 repeat: false,
117 shiftKey: false,
118 ctrlKey: false,
119 altKey: false,
120 metaKey: false,
121 isComposing: false,
122 getModifierState: () => false,
123 } as unknown as KeyboardEvent;
124
125 expect(core.encodeKey(event)).toBe(expected);
126 });
127
128 it("preserves styles, wide cells, and selection after shared memory grows", async () => {
129 const core = await createCore();
130 const runtime = await loadGhosttyRuntime();
131 const grapheme = `e${"\u0301".repeat(64)}`;
132 core.write(`\x1b[1;3;4;8;9;53;38;2;123;45;67;48;2;9;8;7m${grapheme}\x1b[0m界🙂`);
133 const cells = core.snapshot().rowData[0]!.cells;
134 expect(cells[0]).toEqual({
135 text: grapheme,
136 wide: 0,
137 foreground: { r: 123, g: 45, b: 67 },
138 background: { r: 9, g: 8, b: 7 },
139 bold: true,
140 italic: true,
141 invisible: true,
142 strikethrough: true,
143 overline: true,
144 underline: true,
145 selected: false,
146 });
147 expect(cells.slice(1, 5).map(({ text, wide }) => ({ text, wide }))).toEqual([
148 { text: "界", wide: 0 },
149 { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
150 { text: "🙂", wide: 0 },
151 { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
152 ]);
153
154 runtime.memory.grow(1);
155 core.setSelection({ x: 0, y: 0 }, { x: 2, y: 0 });
156 expect(core.snapshot().rowData[0]!.cells[0]).toEqual({ ...cells[0], selected: true });
157 core.clearSelection();
158 expect(core.snapshot().rowData[0]!.cells[0]).toEqual(cells[0]);
159
160 core.resetAndWrite("\x1b[2;7;38;2;40;100;200;48;2;12;34;56mC\x1b[0m");
161 expect(core.snapshot().rowData[0]!.cells[0]).toMatchObject({
162 text: "C",
163 foreground: { r: 22, g: 59, b: 112 },
164 background: { r: 40, g: 100, b: 200 },
165 bold: false,
166 underline: false,
167 selected: false,
168 });
169 });
170
171 it("resolves foreground and background independently without retaining prior cell colors", async () => {
172 const core = await createCore();
173 core.write(
174 "\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",
175 );
176 expect(
177 core
178 .snapshot()
179 .rowData[0]!.cells.slice(0, 6)
180 .map(({ text, foreground, background }) => ({ text, foreground, background })),
181 ).toEqual([
182 { text: "F", foreground: { r: 123, g: 45, b: 67 }, background: { r: 0, g: 0, b: 0 } },
183 { text: "B", foreground: { r: 255, g: 255, b: 255 }, background: { r: 9, g: 8, b: 7 } },
184 { text: "D", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
185 { text: "C", foreground: { r: 12, g: 34, b: 56 }, background: { r: 78, g: 90, b: 123 } },
186 { text: "E", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
187 { text: "", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
188 ]);
189 });
190
191 it("paints ANSI colors from the theme palette and repaints them on theme change", async () => {
192 const core = await createCore();
193 const theme = {
194 foreground: { r: 255, g: 255, b: 255 },
195 background: { r: 0, g: 0, b: 0 },
196 cursor: { r: 255, g: 255, b: 255 },
197 };
198 const palette = Array.from({ length: 16 }, (_, index) => ({ r: index, g: 1, b: 2 }));
199 core.write("\x1b[31mR\x1b[38;5;196mX\x1b[0m");
200 core.setTheme({ ...theme, palette });
201 let cells = core.snapshot().rowData[0]!.cells;
202 expect(cells[0]!.foreground).toEqual({ r: 1, g: 1, b: 2 });
203 expect(cells[1]!.foreground).toEqual({ r: 255, g: 0, b: 0 });
204
205 core.setTheme({ ...theme, palette: palette.map((color) => ({ ...color, g: 9 })) });
206 cells = core.snapshot().rowData[0]!.cells;
207 expect(cells[0]!.foreground).toEqual({ r: 1, g: 9, b: 2 });
208 expect(cells[1]!.foreground).toEqual({ r: 255, g: 0, b: 0 });
209 });
210
211 it("preserves Unicode and split ANSI parser state across batched renderer reads", async () => {
212 const [core, reference] = await Promise.all([createCore(), createCore()]);
213 let state = createSession("");
214 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
215 writeTerminalOutputUpdate(core, first);
216 let cursor = first.cursor;
217 const reset = vi.spyOn(core, "resetAndWrite");
218 const inputs = [
219 `${"a".repeat(16_383)}🙂`,
220 "\x1b[3",
221 "1m",
222 "e",
223 "\u0301界🙂",
224 "\x1b[0",
225 "m\r\n",
226 "\x1b]8;;https://t3.codes\x1b",
227 "\\link",
228 "\x1b]8;;\x1b",
229 "\\\x1b[?1049h",
230 "alternate",
231 "\x1b[?1049l",
232 "\r\nend",
233 ];
234 let received = "";
235 for (const [index, data] of inputs.entries()) {
236 state = append(state, data);
237 if (index % 3 !== 0 && index !== inputs.length - 1) continue;
238 const update = readTerminalOutputUpdate(state.output, cursor);
239 if (update.type !== "append") throw new Error(`Expected append, received ${update.type}`);
240 received += update.data;
241 writeTerminalOutputUpdate(core, update);
242 cursor = update.cursor;
243 }
244
245 reference.write(inputs.join(""));
246 expect(received).toBe(inputs.join(""));
247 expect(reset).not.toHaveBeenCalled();
248 expect(core.snapshot()).toEqual(reference.snapshot());
249 });
250
251 it("answers a live VT query when batched reads cross a chunk compaction", async () => {
252 const replies: string[] = [];
253 const core = await createCore((data) => replies.push(data));
254 core.write("\x1b[5n");
255 expect(replies).toEqual(["\x1b[0n"]);
256 replies.length = 0;
257
258 let state = createSession("");
259 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
260 writeTerminalOutputUpdate(core, initial);
261 let cursor = initial.cursor;
262 for (let index = 0; index < 1000; index += 1) {
263 state = append(state, "x");
264 const update = readTerminalOutputUpdate(state.output, cursor);
265 writeTerminalOutputUpdate(core, update);
266 cursor = update.cursor;
267 }
268 for (let index = 0; index < 24; index += 1) state = append(state, "x");
269 state = append(state, "\x1b[5n");
270 const update = readTerminalOutputUpdate(state.output, cursor);
271 writeTerminalOutputUpdate(core, update);
272
273 expect({ type: update.type, replies }).toEqual({ type: "append", replies: ["\x1b[0n"] });
274 });
275
276 it("recovers a lagging renderer once from bounded output and resumes appending", async () => {
277 const [core, reference] = await Promise.all([createCore(), createCore()]);
278 let state = createSession("\x1b[31mold");
279 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
280 writeTerminalOutputUpdate(core, initial);
281 const reset = vi.spyOn(core, "resetAndWrite");
282 const data = "line\r\n".repeat(8192);
283 for (let index = 0; index < 16; index += 1) state = append(state, data);
284
285 const recovery = readTerminalOutputUpdate(state.output, initial.cursor);
286 if (recovery.type !== "reset") throw new Error(`Expected reset, received ${recovery.type}`);
287 expect(new TextEncoder().encode(recovery.data).byteLength).toBe(
288 DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
289 );
290 writeTerminalOutputUpdate(core, recovery);
291 reference.resetAndWrite(recovery.data);
292 expect(core.snapshot()).toEqual(reference.snapshot());
293
294 state = append(state, "\r\nlatest");
295 const next = readTerminalOutputUpdate(state.output, recovery.cursor);
296 expect(next.type).toBe("append");
297 writeTerminalOutputUpdate(core, next);
298 reference.write("\r\nlatest");
299 expect(reset).toHaveBeenCalledTimes(1);
300 expect(core.snapshot()).toEqual(reference.snapshot());
301 });
302
303 it("replays the latest retained output when WASM arrives after several events", async () => {
304 const pendingCore = createCore();
305 let state = createSession("before");
306 state = append(state, "\r\nduring ");
307 state = append(state, "🙂 load");
308 const core = await pendingCore;
309 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
310 writeTerminalOutputUpdate(core, first);
311 const reference = await createCore();
312 reference.resetAndWrite(terminalOutputText(state.output));
313 const reset = vi.spyOn(core, "resetAndWrite");
314
315 state = append(state, "\r\nafter");
316 const next = readTerminalOutputUpdate(state.output, first.cursor);
317 expect(next).toMatchObject({ type: "append", data: "\r\nafter" });
318 writeTerminalOutputUpdate(core, next);
319 reference.write("\r\nafter");
320 expect(reset).not.toHaveBeenCalled();
321 expect(core.snapshot()).toEqual(reference.snapshot());
322 });
323
324 it("resets real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => {
325 const [core, reference] = await Promise.all([createCore(), createCore()]);
326 let state = createSession("hello");
327 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
328 writeTerminalOutputUpdate(core, initial);
329 let cursor = initial.cursor;
330
331 const snapshot = {
332 threadId: "terminal-stream-test",
333 terminalId: "term-1",
334 cwd: "/repo",
335 worktreePath: null,
336 status: "running" as const,
337 pid: 456,
338 history: "hello",
339 exitCode: null,
340 exitSignal: null,
341 label: "Terminal",
342 updatedAt: "2026-09-04T00:00:01.000Z",
343 };
344 const events = [
345 { type: "snapshot", snapshot },
346 { type: "cleared", threadId: snapshot.threadId, terminalId: snapshot.terminalId },
347 { type: "restarted", threadId: snapshot.threadId, terminalId: snapshot.terminalId, snapshot },
348 ] as const;
349 for (const event of events) {
350 core.write("\r\nstale local text");
351 state = applyTerminalAttachStreamEvent(state, event);
352 const update = readTerminalOutputUpdate(state.output, cursor);
353 expect(update.type).toBe("reset");
354 writeTerminalOutputUpdate(core, update);
355 cursor = update.cursor;
356 reference.resetAndWrite(event.type === "cleared" ? "" : "hello");
357 expect(core.snapshot()).toEqual(reference.snapshot());
358 }
359
360 core.write("\r\nstale local text");
361 state = createSession("hello");
362 const reattached = readTerminalOutputUpdate(state.output, cursor);
363 expect(reattached.type).toBe("reset");
364 writeTerminalOutputUpdate(core, reattached);
365 reference.resetAndWrite("hello");
366 expect(core.snapshot()).toEqual(reference.snapshot());
367 });
368});