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

core.test.ts

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