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

core.test.ts

409 lines15.1 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.each(["", "\x1b[>1u"])("encodes macOS Option text with keyboard mode %j", async (mode) => {
150 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
151 const core = await createCore();
152 core.write(mode);
153 const option = {
154 code: "KeyL",
155 key: "@",
156 repeat: false,
157 shiftKey: false,
158 ctrlKey: false,
159 altKey: true,
160 metaKey: false,
161 isComposing: false,
162 getModifierState: () => false,
163 } as unknown as KeyboardEvent;
164​
165 expect(core.encodeKey(option)).toBe("@");
166 expect(core.encodeKey({ ...option, code: "KeyA", key: "Å", shiftKey: true })).toBe("Å");
167 });
168​
169 it("preserves styles, wide cells, and selection after shared memory grows", async () => {
170 const core = await createCore();
171 const runtime = await loadGhosttyRuntime();
172 const grapheme = `e${"\u0301".repeat(64)}`;
173 core.write(`\x1b[1;3;4;8;9;53;38;2;123;45;67;48;2;9;8;7m${grapheme}\x1b[0m界🙂`);
174 const cells = core.snapshot().rowData[0]!.cells;
175 expect(cells[0]).toEqual({
176 text: grapheme,
177 wide: 0,
178 foreground: { r: 123, g: 45, b: 67 },
179 background: { r: 9, g: 8, b: 7 },
180 bold: true,
181 italic: true,
182 invisible: true,
183 strikethrough: true,
184 overline: true,
185 underline: true,
186 selected: false,
187 });
188 expect(cells.slice(1, 5).map(({ text, wide }) => ({ text, wide }))).toEqual([
189 { text: "界", wide: 0 },
190 { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
191 { text: "🙂", wide: 0 },
192 { text: "", wide: GHOSTTY_CELL_WIDE.spacerTail },
193 ]);
194​
195 runtime.memory.grow(1);
196 core.setSelection({ x: 0, y: 0 }, { x: 2, y: 0 });
197 expect(core.snapshot().rowData[0]!.cells[0]).toEqual({ ...cells[0], selected: true });
198 core.clearSelection();
199 expect(core.snapshot().rowData[0]!.cells[0]).toEqual(cells[0]);
200​
201 core.resetAndWrite("\x1b[2;7;38;2;40;100;200;48;2;12;34;56mC\x1b[0m");
202 expect(core.snapshot().rowData[0]!.cells[0]).toMatchObject({
203 text: "C",
204 foreground: { r: 22, g: 59, b: 112 },
205 background: { r: 40, g: 100, b: 200 },
206 bold: false,
207 underline: false,
208 selected: false,
209 });
210 });
211​
212 it("resolves foreground and background independently without retaining prior cell colors", async () => {
213 const core = await createCore();
214 core.write(
215 "\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",
216 );
217 expect(
218 core
219 .snapshot()
220 .rowData[0]!.cells.slice(0, 6)
221 .map(({ text, foreground, background }) => ({ text, foreground, background })),
222 ).toEqual([
223 { text: "F", foreground: { r: 123, g: 45, b: 67 }, background: { r: 0, g: 0, b: 0 } },
224 { text: "B", foreground: { r: 255, g: 255, b: 255 }, background: { r: 9, g: 8, b: 7 } },
225 { text: "D", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
226 { text: "C", foreground: { r: 12, g: 34, b: 56 }, background: { r: 78, g: 90, b: 123 } },
227 { text: "E", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
228 { text: "", foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 } },
229 ]);
230 });
231​
232 it("paints ANSI colors from the theme palette and repaints them on theme change", async () => {
233 const core = await createCore();
234 const theme = {
235 foreground: { r: 255, g: 255, b: 255 },
236 background: { r: 0, g: 0, b: 0 },
237 cursor: { r: 255, g: 255, b: 255 },
238 };
239 const palette = Array.from({ length: 16 }, (_, index) => ({ r: index, g: 1, b: 2 }));
240 core.write("\x1b[31mR\x1b[38;5;196mX\x1b[0m");
241 core.setTheme({ ...theme, palette });
242 let cells = core.snapshot().rowData[0]!.cells;
243 expect(cells[0]!.foreground).toEqual({ r: 1, g: 1, b: 2 });
244 expect(cells[1]!.foreground).toEqual({ r: 255, g: 0, b: 0 });
245​
246 core.setTheme({ ...theme, palette: palette.map((color) => ({ ...color, g: 9 })) });
247 cells = core.snapshot().rowData[0]!.cells;
248 expect(cells[0]!.foreground).toEqual({ r: 1, g: 9, b: 2 });
249 expect(cells[1]!.foreground).toEqual({ r: 255, g: 0, b: 0 });
250 });
251​
252 it("preserves Unicode and split ANSI parser state across batched renderer reads", async () => {
253 const [core, reference] = await Promise.all([createCore(), createCore()]);
254 let state = createSession("");
255 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
256 writeTerminalOutputUpdate(core, first);
257 let cursor = first.cursor;
258 const reset = vi.spyOn(core, "resetAndWrite");
259 const inputs = [
260 `${"a".repeat(16_383)}🙂`,
261 "\x1b[3",
262 "1m",
263 "e",
264 "\u0301界🙂",
265 "\x1b[0",
266 "m\r\n",
267 "\x1b]8;;https://t3.codes\x1b",
268 "\\link",
269 "\x1b]8;;\x1b",
270 "\\\x1b[?1049h",
271 "alternate",
272 "\x1b[?1049l",
273 "\r\nend",
274 ];
275 let received = "";
276 for (const [index, data] of inputs.entries()) {
277 state = append(state, data);
278 if (index % 3 !== 0 && index !== inputs.length - 1) continue;
279 const update = readTerminalOutputUpdate(state.output, cursor);
280 if (update.type !== "append") throw new Error(`Expected append, received ${update.type}`);
281 received += update.data;
282 writeTerminalOutputUpdate(core, update);
283 cursor = update.cursor;
284 }
285​
286 reference.write(inputs.join(""));
287 expect(received).toBe(inputs.join(""));
288 expect(reset).not.toHaveBeenCalled();
289 expect(core.snapshot()).toEqual(reference.snapshot());
290 });
291​
292 it("answers a live VT query when batched reads cross a chunk compaction", async () => {
293 const replies: string[] = [];
294 const core = await createCore((data) => replies.push(data));
295 core.write("\x1b[5n");
296 expect(replies).toEqual(["\x1b[0n"]);
297 replies.length = 0;
298​
299 let state = createSession("");
300 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
301 writeTerminalOutputUpdate(core, initial);
302 let cursor = initial.cursor;
303 for (let index = 0; index < 1000; index += 1) {
304 state = append(state, "x");
305 const update = readTerminalOutputUpdate(state.output, cursor);
306 writeTerminalOutputUpdate(core, update);
307 cursor = update.cursor;
308 }
309 for (let index = 0; index < 24; index += 1) state = append(state, "x");
310 state = append(state, "\x1b[5n");
311 const update = readTerminalOutputUpdate(state.output, cursor);
312 writeTerminalOutputUpdate(core, update);
313​
314 expect({ type: update.type, replies }).toEqual({ type: "append", replies: ["\x1b[0n"] });
315 });
316​
317 it("recovers a lagging renderer once from bounded output and resumes appending", async () => {
318 const [core, reference] = await Promise.all([createCore(), createCore()]);
319 let state = createSession("\x1b[31mold");
320 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
321 writeTerminalOutputUpdate(core, initial);
322 const reset = vi.spyOn(core, "resetAndWrite");
323 const data = "line\r\n".repeat(8192);
324 for (let index = 0; index < 16; index += 1) state = append(state, data);
325​
326 const recovery = readTerminalOutputUpdate(state.output, initial.cursor);
327 if (recovery.type !== "reset") throw new Error(`Expected reset, received ${recovery.type}`);
328 expect(new TextEncoder().encode(recovery.data).byteLength).toBe(
329 DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
330 );
331 writeTerminalOutputUpdate(core, recovery);
332 reference.resetAndWrite(recovery.data);
333 expect(core.snapshot()).toEqual(reference.snapshot());
334​
335 state = append(state, "\r\nlatest");
336 const next = readTerminalOutputUpdate(state.output, recovery.cursor);
337 expect(next.type).toBe("append");
338 writeTerminalOutputUpdate(core, next);
339 reference.write("\r\nlatest");
340 expect(reset).toHaveBeenCalledTimes(1);
341 expect(core.snapshot()).toEqual(reference.snapshot());
342 });
343​
344 it("replays the latest retained output when WASM arrives after several events", async () => {
345 const pendingCore = createCore();
346 let state = createSession("before");
347 state = append(state, "\r\nduring ");
348 state = append(state, "🙂 load");
349 const core = await pendingCore;
350 const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
351 writeTerminalOutputUpdate(core, first);
352 const reference = await createCore();
353 reference.resetAndWrite(terminalOutputText(state.output));
354 const reset = vi.spyOn(core, "resetAndWrite");
355​
356 state = append(state, "\r\nafter");
357 const next = readTerminalOutputUpdate(state.output, first.cursor);
358 expect(next).toMatchObject({ type: "append", data: "\r\nafter" });
359 writeTerminalOutputUpdate(core, next);
360 reference.write("\r\nafter");
361 expect(reset).not.toHaveBeenCalled();
362 expect(core.snapshot()).toEqual(reference.snapshot());
363 });
364​
365 it("resets real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => {
366 const [core, reference] = await Promise.all([createCore(), createCore()]);
367 let state = createSession("hello");
368 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
369 writeTerminalOutputUpdate(core, initial);
370 let cursor = initial.cursor;
371​
372 const snapshot = {
373 threadId: "terminal-stream-test",
374 terminalId: "term-1",
375 cwd: "/repo",
376 worktreePath: null,
377 status: "running" as const,
378 pid: 456,
379 history: "hello",
380 exitCode: null,
381 exitSignal: null,
382 label: "Terminal",
383 updatedAt: "2026-09-04T00:00:01.000Z",
384 };
385 const events = [
386 { type: "snapshot", snapshot },
387 { type: "cleared", threadId: snapshot.threadId, terminalId: snapshot.terminalId },
388 { type: "restarted", threadId: snapshot.threadId, terminalId: snapshot.terminalId, snapshot },
389 ] as const;
390 for (const event of events) {
391 core.write("\r\nstale local text");
392 state = applyTerminalAttachStreamEvent(state, event);
393 const update = readTerminalOutputUpdate(state.output, cursor);
394 expect(update.type).toBe("reset");
395 writeTerminalOutputUpdate(core, update);
396 cursor = update.cursor;
397 reference.resetAndWrite(event.type === "cleared" ? "" : "hello");
398 expect(core.snapshot()).toEqual(reference.snapshot());
399 }
400​
401 core.write("\r\nstale local text");
402 state = createSession("hello");
403 const reattached = readTerminalOutputUpdate(state.output, cursor);
404 expect(reattached.type).toBe("reset");
405 writeTerminalOutputUpdate(core, reattached);
406 reference.resetAndWrite("hello");
407 expect(core.snapshot()).toEqual(reference.snapshot());
408 });
409});