Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

core.test.ts

380 lines14.0 KB

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;
28​
29describe("ghosttyCellText", () => {
30 it("converts oversized grapheme clusters without hitting engine spread limits", () => {
31 // A program printing one base character followed by a huge run of
32 // combining marks packs the whole cluster into one cell; spreading that
33 // many arguments into String.fromCodePoint once overflows the call stack.
34 const graphemeLength = 130_000;
35 const view = new DataView(new ArrayBuffer(graphemeLength * 4));
36 for (let index = 0; index < graphemeLength; index += 1) {
37 view.setUint32(index * 4, index === 0 ? "a".codePointAt(0)! : 0x301, true);
38 }
39 const text = ghosttyCellText(view, graphemeLength);
40 expect(text.length).toBe(graphemeLength);
41 expect(text.codePointAt(0)).toBe("a".codePointAt(0));
42 expect(text.codePointAt(1)).toBe(0x301);
43 expect(text.codePointAt(graphemeLength - 1)).toBe(0x301);
44 });
45​
46 it("converts small clusters including astral codepoints", () => {
47 const text = ghosttyCellText(codepointView([0x1f642, 0x20e3]), 2);
48 expect([...text]).toEqual(["\u{1F642}", "\u{20E3}"]);
49 });
50​
51 it("converts a single astral codepoint", () => {
52 expect(ghosttyCellText(codepointView([0x1f642]), 1)).toBe("🙂");
53 });
54​
55 it("returns an empty string for empty cells", () => {
56 expect(ghosttyCellText(codepointView([]), 0)).toBe("");
57 });
58});
59​
60describe("GhosttyTerminalCore snapshots", () => {
61 const cores = new Set<GhosttyTerminalCore>();
62​
63 async function createCore(onData: (data: string) => void = () => {}) {
64 const core = await GhosttyTerminalCore.create(
65 12,
66 3,
67 8,
68 16,
69 {
70 foreground: { r: 255, g: 255, b: 255 },
71 background: { r: 0, g: 0, b: 0 },
72 cursor: { r: 255, g: 255, b: 255 },
73 },
74 onData,
75 );
76 cores.add(core);
77 return core;
78 }
79​
80 function createSession(history: string) {
81 return applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
82 type: "snapshot",
83 snapshot: {
84 threadId: "terminal-stream-test",
85 terminalId: "term-1",
86 cwd: "/repo",
87 worktreePath: null,
88 status: "running",
89 pid: 123,
90 history,
91 exitCode: null,
92 exitSignal: null,
93 label: "Terminal",
94 updatedAt: "2026-09-04T00:00:00.000Z",
95 },
96 });
97 }
98​
99 function append(state: TerminalBufferState, data: string) {
100 return applyTerminalAttachStreamEvent(state, {
101 type: "output",
102 threadId: "terminal-stream-test",
103 terminalId: "term-1",
104 data,
105 });
106 }
107​
108 afterEach(() => {
109 for (const core of cores) core.dispose();
110 cores.clear();
111 vi.restoreAllMocks();
112 });
113​
114 it("preserves styles, wide cells, and selection after shared memory grows", async () => {
115 const core = await createCore();
116 const runtime = await loadGhosttyRuntime();
117 const grapheme = `e${"\u0301".repeat(64)}`;
118 core.write(`\x1b[1;3;4;8;9;53;38;2;123;45;67;48;2;9;8;7m${grapheme}\x1b[0m界🙂`);
119 const cells = core.snapshot().rowData[0]!.cells;
120 expect(cells[0]).toEqual({
121 text: grapheme,
122 wide: 0,
123 foreground: { r: 123, g: 45, b: 67 },
124 background: { r: 9, g: 8, b: 7 },
125 bold: true,
126 italic: true,
127 invisible: true,
128 strikethrough: true,
129 overline: true,
130 underline: true,
131 selected: false,
132 });
133 expect(cells.slice(1, 5).map(({ text, wide }) => ({ text, wide }))).toEqual([
134 { text: "界", wide: 0 },
135 { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
136 { text: "🙂", wide: 0 },
137 { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
138 ]);
139​
140 runtime.memory.grow(1);
141 core.setSelection({ x: 0, y: 0 }, { x: 2, y: 0 });
142 expect(core.snapshot().rowData[0]!.cells[0]).toEqual({ ...cells[0], selected: true });
143 core.clearSelection();
144 expect(core.snapshot().rowData[0]!.cells[0]).toEqual(cells[0]);
145​
146 core.resetAndWrite("\x1b[2;7;38;2;40;100;200;48;2;12;34;56mC\x1b[0m");
147 expect(core.snapshot().rowData[0]!.cells[0]).toMatchObject({
148 text: "C",
149 foreground: { r: 22, g: 59, b: 112 },
150 background: { r: 40, g: 100, b: 200 },
151 bold: false,
152 underline: false,
153 selected: false,
154 });
155 });
156​
157 it("reuses a grown grapheme buffer and releases it on disposal", async () => {
158 const core = await createCore();
159 const runtime = await loadGhosttyRuntime();
160 core.write("ASCII");
161 core.snapshot();
162​
163 const grapheme = `z${"\u0301".repeat(256)}`;
164 core.resetAndWrite(`${grapheme}X`);
165 const alloc = vi.spyOn(runtime, "alloc");
166 const free = vi.spyOn(runtime, "free");
167 expect(
168 core
169 .snapshot()
170 .rowData[0]!.cells.slice(0, 2)
171 .map((cell) => cell.text),
172 ).toEqual([grapheme, "X"]);
173 expect(alloc).toHaveBeenCalledTimes(1);
174 const allocation = alloc.mock.results[0]!;
175 if (allocation.type !== "return") throw new Error("Grapheme allocation did not return");
176 const buffer = allocation.value;
177 const capacity = alloc.mock.calls[0]![0];
178​
179 core.write("\rQ\u0301");
180 alloc.mockClear();
181 expect(core.snapshot().rowData[0]!.cells[0]!.text).toBe("Q\u0301");
182 expect(alloc).not.toHaveBeenCalled();
183 core.dispose();
184 expect(free).toHaveBeenCalledWith(buffer, capacity);
185 });
186​
187 it.each(["varied", "identical"] as const)(
188 "preserves Ghostty state through a full MiB of %s output without rollover resets",
189 async (kind) => {
190 const [core, reference] = await Promise.all([createCore(), createCore()]);
191 const initial = "\x1b[31m";
192 let state = createSession(initial);
193 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
194 writeTerminalOutputUpdate(core, first);
195 reference.resetAndWrite(initial);
196 let cursor = first.cursor;
197 const reset = vi.spyOn(core, "resetAndWrite");
198 const inputs: string[] = [];
199 let receivedCharacters = 0;
200​
201 for (let index = 0; index < 128; index += 1) {
202 const data =
203 kind === "identical"
204 ? "x".repeat(8192)
205 : `${index.toString().padStart(4, "0")}\r\n${"x".repeat(8186)}`;
206 inputs.push(data);
207 state = append(state, data);
208 const update = readTerminalOutputUpdate(state.output, cursor);
209 if (update.type !== "append") throw new Error(`Expected append, received ${update.type}`);
210 receivedCharacters += update.data.length;
211 writeTerminalOutputUpdate(core, update);
212 cursor = update.cursor;
213 }
214​
215 reference.write(inputs.join(""));
216 expect(receivedCharacters).toBe(1024 * 1024);
217 expect(state.output.retainedBytes).toBe(DEFAULT_MAX_TERMINAL_BUFFER_BYTES);
218 expect(reset).not.toHaveBeenCalled();
219 expect(core.snapshot()).toEqual(reference.snapshot());
220 },
221 );
222​
223 it("preserves Unicode and split ANSI parser state across batched renderer reads", async () => {
224 const [core, reference] = await Promise.all([createCore(), createCore()]);
225 let state = createSession("");
226 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
227 writeTerminalOutputUpdate(core, first);
228 let cursor = first.cursor;
229 const reset = vi.spyOn(core, "resetAndWrite");
230 const inputs = [
231 `${"a".repeat(16_383)}🙂`,
232 "\x1b[3",
233 "1m",
234 "e",
235 "\u0301界🙂",
236 "\x1b[0",
237 "m\r\n",
238 "\x1b]8;;https://t3.codes\x1b",
239 "\\link",
240 "\x1b]8;;\x1b",
241 "\\\x1b[?1049h",
242 "alternate",
243 "\x1b[?1049l",
244 "\r\nend",
245 ];
246 let received = "";
247 for (const [index, data] of inputs.entries()) {
248 state = append(state, data);
249 if (index % 3 !== 0 && index !== inputs.length - 1) continue;
250 const update = readTerminalOutputUpdate(state.output, cursor);
251 if (update.type !== "append") throw new Error(`Expected append, received ${update.type}`);
252 received += update.data;
253 writeTerminalOutputUpdate(core, update);
254 cursor = update.cursor;
255 }
256​
257 reference.write(inputs.join(""));
258 expect(received).toBe(inputs.join(""));
259 expect(reset).not.toHaveBeenCalled();
260 expect(core.snapshot()).toEqual(reference.snapshot());
261 });
262​
263 it("answers a live VT query when batched reads cross a chunk compaction", async () => {
264 const replies: string[] = [];
265 const core = await createCore((data) => replies.push(data));
266 core.write("\x1b[5n");
267 expect(replies).toEqual(["\x1b[0n"]);
268 replies.length = 0;
269​
270 let state = createSession("");
271 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
272 writeTerminalOutputUpdate(core, initial);
273 let cursor = initial.cursor;
274 for (let index = 0; index < 1000; index += 1) {
275 state = append(state, "x");
276 const update = readTerminalOutputUpdate(state.output, cursor);
277 writeTerminalOutputUpdate(core, update);
278 cursor = update.cursor;
279 }
280 for (let index = 0; index < 24; index += 1) state = append(state, "x");
281 state = append(state, "\x1b[5n");
282 const update = readTerminalOutputUpdate(state.output, cursor);
283 writeTerminalOutputUpdate(core, update);
284​
285 expect({ type: update.type, replies }).toEqual({ type: "append", replies: ["\x1b[0n"] });
286 });
287​
288 it("recovers a lagging renderer once from bounded output and resumes appending", async () => {
289 const [core, reference] = await Promise.all([createCore(), createCore()]);
290 let state = createSession("\x1b[31mold");
291 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
292 writeTerminalOutputUpdate(core, initial);
293 const reset = vi.spyOn(core, "resetAndWrite");
294 const data = "line\r\n".repeat(8192);
295 for (let index = 0; index < 16; index += 1) state = append(state, data);
296​
297 const recovery = readTerminalOutputUpdate(state.output, initial.cursor);
298 if (recovery.type !== "reset") throw new Error(`Expected reset, received ${recovery.type}`);
299 expect(new TextEncoder().encode(recovery.data).byteLength).toBe(
300 DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
301 );
302 writeTerminalOutputUpdate(core, recovery);
303 reference.resetAndWrite(recovery.data);
304 expect(core.snapshot()).toEqual(reference.snapshot());
305​
306 state = append(state, "\r\nlatest");
307 const next = readTerminalOutputUpdate(state.output, recovery.cursor);
308 expect(next.type).toBe("append");
309 writeTerminalOutputUpdate(core, next);
310 reference.write("\r\nlatest");
311 expect(reset).toHaveBeenCalledTimes(1);
312 expect(core.snapshot()).toEqual(reference.snapshot());
313 });
314​
315 it("replays the latest retained output when WASM arrives after several events", async () => {
316 const pendingCore = createCore();
317 let state = createSession("before");
318 state = append(state, "\r\nduring ");
319 state = append(state, "🙂 load");
320 const core = await pendingCore;
321 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
322 writeTerminalOutputUpdate(core, first);
323 const reference = await createCore();
324 reference.resetAndWrite(terminalOutputText(state.output));
325 const reset = vi.spyOn(core, "resetAndWrite");
326​
327 state = append(state, "\r\nafter");
328 const next = readTerminalOutputUpdate(state.output, first.cursor);
329 expect(next).toMatchObject({ type: "append", data: "\r\nafter" });
330 writeTerminalOutputUpdate(core, next);
331 reference.write("\r\nafter");
332 expect(reset).not.toHaveBeenCalled();
333 expect(core.snapshot()).toEqual(reference.snapshot());
334 });
335​
336 it("resets real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => {
337 const [core, reference] = await Promise.all([createCore(), createCore()]);
338 let state = createSession("hello");
339 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
340 writeTerminalOutputUpdate(core, initial);
341 let cursor = initial.cursor;
342​
343 const snapshot = {
344 threadId: "terminal-stream-test",
345 terminalId: "term-1",
346 cwd: "/repo",
347 worktreePath: null,
348 status: "running" as const,
349 pid: 456,
350 history: "hello",
351 exitCode: null,
352 exitSignal: null,
353 label: "Terminal",
354 updatedAt: "2026-09-04T00:00:01.000Z",
355 };
356 const events = [
357 { type: "snapshot", snapshot },
358 { type: "cleared", threadId: snapshot.threadId, terminalId: snapshot.terminalId },
359 { type: "restarted", threadId: snapshot.threadId, terminalId: snapshot.terminalId, snapshot },
360 ] as const;
361 for (const event of events) {
362 core.write("\r\nstale local text");
363 state = applyTerminalAttachStreamEvent(state, event);
364 const update = readTerminalOutputUpdate(state.output, cursor);
365 expect(update.type).toBe("reset");
366 writeTerminalOutputUpdate(core, update);
367 cursor = update.cursor;
368 reference.resetAndWrite(event.type === "cleared" ? "" : "hello");
369 expect(core.snapshot()).toEqual(reference.snapshot());
370 }
371​
372 core.write("\r\nstale local text");
373 state = createSession("hello");
374 const reattached = readTerminalOutputUpdate(state.output, cursor);
375 expect(reattached.type).toBe("reset");
376 writeTerminalOutputUpdate(core, reattached);
377 reference.resetAndWrite("hello");
378 expect(core.snapshot()).toEqual(reference.snapshot());
379 });
380});