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

surface.test.ts

1,079 lines37.7 KB

1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2import {
3 applyTerminalAttachStreamEvent,
4 INITIAL_TERMINAL_OUTPUT_CURSOR,
5 nextTerminalAttachSeedState,
6} from "@t3tools/client-runtime/state/terminal";
7import { synchronizeTerminalSession } from "../../components/ThreadTerminalDrawer";
8​
9import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";
10import {
11 advanceTerminalSelectionClickSequence,
12 applyTerminalCopyEvent,
13 clearPrimedTerminalCopyInput,
14 isTerminalCompositionKey,
15 isTerminalCopyShortcut,
16 primeTerminalCopyInput,
17 resolveTerminalMouseData,
18 terminalLinkAtPositionWithRange,
19 terminalContentOriginY,
20 terminalSelectionAutoscrollRows,
21 terminalWheelDeltaRows,
22 GhosttyTerminalSurface,
23 type GhosttyTerminalSurfaceOptions,
24} from "./surface";
25​
26vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({
27 default: (await import("./vendor/ghostty-vt.wasm?inline")).default,
28}));
29vi.mock("./vendor/ghostty-write-pty.wasm?url&no-inline", async () => ({
30 default: (await import("./vendor/ghostty-write-pty.wasm?inline")).default,
31}));
32​
33describe("GhosttyTerminalSurface visibility", () => {
34 const surfaces = new Set<GhosttyTerminalSurface>();
35​
36 function key(
37 surface: GhosttyTerminalSurface,
38 key: string,
39 code: string,
40 modifiers: Partial<
41 Pick<
42 KeyboardEvent,
43 | "altKey"
44 | "ctrlKey"
45 | "metaKey"
46 | "shiftKey"
47 | "isComposing"
48 | "repeat"
49 | "keyCode"
50 | "getModifierState"
51 >
52 > = {},
53 type = "keydown",
54 target: EventTarget = surface.input,
55 ) {
56 const event = Object.assign(new Event(type, { cancelable: true }), {
57 key,
58 code,
59 altKey: false,
60 ctrlKey: false,
61 metaKey: false,
62 shiftKey: false,
63 isComposing: false,
64 repeat: false,
65 keyCode: 0,
66 getModifierState: () => false,
67 ...modifiers,
68 });
69 target.dispatchEvent(event);
70 return event;
71 }
72​
73 function createHarness() {
74 vi.useFakeTimers();
75 const frames = new Map<number, FrameRequestCallback>();
76 const resizeTargets = new Map<(entries: { target: Element }[]) => void, Set<Element>>();
77 const paint = vi.fn((_operation: string, _args: ReadonlyArray<unknown>) => {});
78 let frameId = 0;
79 const requestFrame = vi.fn((callback: FrameRequestCallback) => {
80 frames.set(++frameId, callback);
81 return frameId;
82 });
83​
84 class TerminalTestElement extends EventTarget {
85 style: Record<string, string> = {};
86 parentElement: TerminalTestElement | null = null;
87 clientWidth = 168;
88 clientHeight = 104;
89 width = 300;
90 height = 150;
91 value = "";
92 private readonly captures = new Set<number>();
93​
94 setAttribute() {}
95 append(...children: TerminalTestElement[]) {
96 for (const child of children) child.parentElement = this;
97 }
98 replaceChildren(...children: TerminalTestElement[]) {
99 this.append(...children);
100 }
101 remove() {
102 this.parentElement = null;
103 }
104 getContext() {
105 return context;
106 }
107 focus() {
108 this.dispatchEvent(new Event("focus"));
109 }
110 setPointerCapture(pointerId: number) {
111 this.captures.add(pointerId);
112 }
113 hasPointerCapture(pointerId: number) {
114 return this.captures.has(pointerId);
115 }
116 releasePointerCapture(pointerId: number) {
117 this.captures.delete(pointerId);
118 }
119 getBoundingClientRect() {
120 return { left: 0, top: 0, right: 168, bottom: 104, width: 168, height: 104 };
121 }
122 }
123​
124 const canvas = new TerminalTestElement();
125 const mount = new TerminalTestElement();
126 const context = {
127 canvas,
128 beginPath() {},
129 clip() {},
130 getTransform: () => ({ a: 1, d: 1 }),
131 rect() {},
132 resetTransform() {},
133 restore() {},
134 save() {},
135 setTransform() {},
136 fillRect: (...args: number[]) => paint("fillRect", args),
137 strokeRect: (...args: number[]) => paint("strokeRect", args),
138 fillText: (...args: [string, number, number, number?]) => paint("fillText", args),
139 measureText: (text: string) => ({
140 width: text.length * 8,
141 actualBoundingBoxAscent: 9,
142 actualBoundingBoxDescent: 3,
143 }),
144 };
145 vi.stubGlobal("document", {
146 createElement: (tag: string) => (tag === "canvas" ? canvas : new TerminalTestElement()),
147 fonts: Object.assign(new EventTarget(), { load: async () => [], add() {} }),
148 });
149 vi.stubGlobal(
150 "window",
151 Object.assign(new EventTarget(), {
152 devicePixelRatio: 1,
153 innerHeight: 104,
154 requestAnimationFrame: requestFrame,
155 cancelAnimationFrame: (id: number) => frames.delete(id),
156 setTimeout,
157 clearTimeout,
158 setInterval,
159 clearInterval,
160 matchMedia: () => Object.assign(new EventTarget(), { matches: false }),
161 }),
162 );
163 vi.stubGlobal(
164 "ResizeObserver",
165 class {
166 constructor(private readonly callback: (entries: { target: Element }[]) => void) {
167 resizeTargets.set(callback, new Set());
168 }
169 observe(target: Element) {
170 resizeTargets.get(this.callback)?.add(target);
171 }
172 unobserve(target: Element) {
173 resizeTargets.get(this.callback)?.delete(target);
174 }
175 disconnect() {
176 resizeTargets.delete(this.callback);
177 }
178 },
179 );
180 const snapshot = vi.spyOn(GhosttyTerminalCore.prototype, "snapshot");
181 const onData = vi.fn<(data: string) => void>();
182​
183 return {
184 canvas,
185 mount,
186 frames,
187 paint,
188 requestFrame,
189 snapshot,
190 onData,
191 get renderedSnapshot() {
192 const result = snapshot.mock.results.at(-1);
193 if (result?.type !== "return") throw new Error("No terminal snapshot was rendered");
194 return result.value;
195 },
196 flushFrame() {
197 const queued = [...frames.values()];
198 frames.clear();
199 for (const callback of queued) callback(0);
200 },
201 resize() {
202 for (const [callback, targets] of resizeTargets) {
203 callback([...targets].map((target) => ({ target })));
204 }
205 },
206 pointer(
207 type: string,
208 clientX: number,
209 buttons: number,
210 modifiers: boolean | Partial<Pick<MouseEvent, "ctrlKey" | "metaKey" | "shiftKey">> = {},
211 button = 0,
212 clientY = 5,
213 ) {
214 canvas.dispatchEvent(
215 Object.assign(new Event(type, { cancelable: true }), {
216 clientX,
217 clientY,
218 pointerId: 1,
219 button,
220 buttons,
221 ...(typeof modifiers === "boolean" ? { shiftKey: modifiers } : modifiers),
222 }),
223 );
224 },
225 touch(type: string, clientY: number, pointerId = 2) {
226 canvas.dispatchEvent(
227 Object.assign(new Event(type, { cancelable: true }), {
228 clientX: 40,
229 clientY,
230 pointerId,
231 pointerType: "touch",
232 isPrimary: pointerId === 2,
233 button: 0,
234 buttons: type === "pointerup" ? 0 : 1,
235 shiftKey: false,
236 }),
237 );
238 },
239 async create(options: Partial<GhosttyTerminalSurfaceOptions> = {}) {
240 const surface = await GhosttyTerminalSurface.create(mount as unknown as HTMLElement, {
241 theme: {
242 foreground: { r: 255, g: 255, b: 255 },
243 background: { r: 0, g: 0, b: 0 },
244 cursor: { r: 255, g: 255, b: 255 },
245 },
246 onData,
247 onResize() {},
248 onSelectionChange() {},
249 beforeKey: () => false,
250 onLinkActivate() {},
251 ...options,
252 get visible() {
253 return options.visible ?? true;
254 },
255 });
256 surfaces.add(surface);
257 return surface;
258 },
259 };
260 }
261​
262 afterEach(() => {
263 for (const surface of surfaces) surface.dispose();
264 surfaces.clear();
265 vi.useRealTimers();
266 vi.unstubAllGlobals();
267 vi.restoreAllMocks();
268 });
269​
270 it("preserves shell Ctrl+A and ordinary application navigation", async () => {
271 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
272 const harness = createHarness();
273 const surface = await harness.create({ beforeKey: () => true });
274 key(surface, "a", "KeyA", { ctrlKey: true });
275 key(surface, "PageUp", "PageUp");
276 key(surface, "PageDown", "PageDown");
277 key(surface, "Home", "Home");
278 key(surface, "End", "End");
279 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([
280 "\x01",
281 "\x1b[5~",
282 "\x1b[6~",
283 "\x1b[H",
284 "\x1b[F",
285 ]);
286 expect(surface.hasSelection()).toBe(false);
287 });
288​
289 it("skips middle-click selection paste when the desktop turned primary paste off", async () => {
290 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
291 const harness = createHarness();
292 const surface = await harness.create();
293 surface.write("echo hi");
294 surface.selectAll();
295 const pasteFromClipboard = vi.spyOn(surface, "pasteFromClipboard");
296​
297 let primaryPasteEnabled = false;
298 Object.assign(window, { desktopBridge: { getPrimaryPasteEnabled: () => primaryPasteEnabled } });
299 harness.pointer("pointerdown", 5, 4, {}, 1);
300 expect(pasteFromClipboard).not.toHaveBeenCalled();
301​
302 primaryPasteEnabled = true;
303 harness.pointer("pointerdown", 5, 4, {}, 1);
304 expect(pasteFromClipboard).toHaveBeenCalledOnce();
305 });
306​
307 it("leaves modified history keys with alternate-screen applications", async () => {
308 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
309 const harness = createHarness();
310 const surface = await harness.create({ beforeKey: () => true });
311 surface.write("\x1b[?1049happ");
312 key(surface, "PageUp", "PageUp", { shiftKey: true });
313 key(surface, "End", "End", { ctrlKey: true, shiftKey: true });
314 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual(["\x1b[5;2~", "\x1b[1;6F"]);
315 surface.selectAll();
316 expect(surface.getSelection()).toBe("app");
317 surface.write("\x1b[?1049l");
318 expect(surface.getSelection()).toBe("");
319 });
320​
321 it("suppresses local shortcut releases in Kitty sessions, including read-only observers", async () => {
322 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
323 const harness = createHarness();
324 const surface = await harness.create({ beforeKey: () => true });
325 surface.input.readOnly = true;
326 surface.write("history\x1b[>31u");
327 for (const [name, code, modifiers] of [
328 ["PageUp", "PageUp", { shiftKey: true }],
329 ["Home", "Home", { ctrlKey: true, shiftKey: true }],
330 ["a", "KeyA", { ctrlKey: true, shiftKey: true }],
331 ] as const) {
332 key(surface, name, code, modifiers);
333 key(surface, name, code, modifiers, "keyup");
334 }
335 expect(surface.getSelection()).toBe("history");
336 expect(harness.onData).not.toHaveBeenCalled();
337​
338 key(surface, "PageUp", "PageUp");
339 key(surface, "PageUp", "PageUp", {}, "keyup");
340 expect(harness.onData).toHaveBeenCalledTimes(2);
341 expect(harness.onData.mock.calls[1]?.[0]).toContain(":3");
342 });
343​
344 it("reports Kitty releases only for presses encoded by this surface", async () => {
345 const harness = createHarness();
346 const surface = await harness.create({ beforeKey: () => true });
347 surface.write("\x1b[>11u");
348​
349 key(surface, "a", "KeyA");
350 key(surface, "a", "KeyA", {}, "keyup");
351 key(surface, "Control", "ControlLeft", { ctrlKey: true });
352 // App capture stops Ctrl+D before it reaches the terminal input.
353 key(surface, "d", "KeyD", { ctrlKey: true }, "keydown", window);
354 key(surface, "d", "KeyD", { ctrlKey: true }, "keyup");
355 key(surface, "Control", "ControlLeft", {}, "keyup");
356​
357 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([
358 "\x1b[97u",
359 "\x1b[97;1:3u",
360 "\x1b[57442;5u",
361 "\x1b[57442;1:3u",
362 ]);
363 });
364​
365 it("keeps a held Kitty press through focus changes and an app-consumed repeat", async () => {
366 const harness = createHarness();
367 let consumeRepeat = false;
368 const surface = await harness.create({ beforeKey: () => !consumeRepeat });
369 surface.write("\x1b[>11u");
370​
371 key(surface, "a", "KeyA");
372 key(surface, "a", "KeyA", { repeat: true });
373 surface.input.dispatchEvent(new Event("blur"));
374 window.dispatchEvent(new Event("blur"));
375 window.dispatchEvent(new Event("focus"));
376 surface.input.dispatchEvent(new Event("focus"));
377 consumeRepeat = true;
378 key(surface, "a", "KeyA", { repeat: true });
379 key(surface, "a", "KeyA", {}, "keyup");
380​
381 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([
382 "\x1b[97u",
383 "\x1b[97;1:2u",
384 "\x1b[97;1:3u",
385 ]);
386 });
387​
388 it("honors host interception, IME candidates, and AltGr before local shortcuts", async () => {
389 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
390 const harness = createHarness();
391 let allow = false;
392 const surface = await harness.create({ beforeKey: () => allow });
393 surface.write("hello\x1b[>31u");
394 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true });
395 key(surface, "a", "KeyA", {}, "keyup");
396 expect(surface.hasSelection()).toBe(false);
397 allow = true;
398 surface.input.value = "候補";
399 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true, isComposing: true });
400 key(surface, "a", "KeyA", {}, "keyup");
401 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true, keyCode: 229 });
402 key(surface, "a", "KeyA", {}, "keyup");
403 key(surface, "a", "KeyA", {
404 ctrlKey: true,
405 shiftKey: true,
406 altKey: true,
407 getModifierState: (modifier) => modifier === "AltGraph",
408 });
409 key(surface, "a", "KeyA", {}, "keyup");
410 expect(surface.input.value).toBe("候補");
411 expect(surface.hasSelection()).toBe(false);
412 expect(harness.onData).not.toHaveBeenCalled();
413 });
414​
415 function paste(surface: GhosttyTerminalSurface, text: string) {
416 surface.input.dispatchEvent(
417 Object.assign(new Event("paste", { cancelable: true }), {
418 clipboardData: { getData: () => text },
419 }),
420 );
421 }
422​
423 it.each(["native", "clipboard"])("pastes once when %s arrives first", async (first) => {
424 const harness = createHarness();
425 const read = Promise.resolve("echo hi");
426 vi.stubGlobal("navigator", {
427 platform: "MacIntel",
428 clipboard: { readText: () => read },
429 });
430 const surface = await harness.create({ beforeKey: () => true });
431​
432 key(surface, "v", "KeyV", { metaKey: true });
433 if (first === "native") paste(surface, "echo hi");
434 await read;
435 if (first === "clipboard") paste(surface, "echo hi");
436​
437 expect(harness.onData.mock.calls).toEqual([["echo hi"]]);
438 });
439​
440 it.each(["V keyup", "blur", "Meta keyup without V keyup"])(
441 "accepts a later identical menu paste after %s",
442 async (end) => {
443 const harness = createHarness();
444 const read = Promise.resolve("echo hi");
445 vi.stubGlobal("navigator", {
446 platform: "MacIntel",
447 clipboard: { readText: () => read },
448 });
449 const surface = await harness.create({ beforeKey: () => true });
450​
451 key(surface, "v", "KeyV", { metaKey: true });
452 await read;
453 expect(harness.onData.mock.calls).toEqual([["echo hi"]]);
454 if (end === "blur") surface.input.dispatchEvent(new Event("blur"));
455 else if (end === "V keyup") key(surface, "v", "KeyV", { metaKey: true }, "keyup");
456 // macOS can omit V keyup while Command is held.
457 else key(surface, "Meta", "MetaLeft", {}, "keyup");
458 paste(surface, "echo hi");
459​
460 expect(harness.onData.mock.calls).toEqual([["echo hi"], ["echo hi"]]);
461 },
462 );
463​
464 it("keeps a selection through redraws until the selected text changes", async () => {
465 const harness = createHarness();
466 const surface = await harness.create();
467 const seed = nextTerminalAttachSeedState();
468 let state = applyTerminalAttachStreamEvent(seed, {
469 type: "snapshot",
470 snapshot: {
471 threadId: "thread",
472 terminalId: "term-1",
473 cwd: "/repo",
474 worktreePath: null,
475 status: "running",
476 pid: 123,
477 history: "* Working |",
478 exitCode: null,
479 exitSignal: null,
480 label: "Terminal",
481 updatedAt: "2026-10-20T00:00:00.000Z",
482 },
483 });
484 let cursor = synchronizeTerminalSession(surface, seed, state, INITIAL_TERMINAL_OUTPUT_CURSOR);
485 harness.flushFrame();
486 harness.pointer("pointerdown", 5, 1);
487 harness.pointer("pointermove", 85, 1);
488 harness.pointer("pointerup", 85, 0);
489 expect(surface.getSelection()).toBe("* Working |");
490​
491 // A TUI repaints its spinner line in place, the way Claude Code redraws.
492 const redraw = (data: string) => {
493 const previous = state;
494 state = applyTerminalAttachStreamEvent(state, {
495 type: "output",
496 threadId: "thread",
497 terminalId: "term-1",
498 data,
499 });
500 cursor = synchronizeTerminalSession(surface, previous, state, cursor);
501 };
502 redraw("\r\x1b[2K* Working |");
503 expect(surface.getSelection()).toBe("* Working |");
504​
505 redraw("\r\x1b[2K* Working /");
506 expect(surface.getSelection()).toBe("");
507 expect(surface.getSelectionPosition()).toBeNull();
508 });
509​
510 it("reports where a selection sits after output scrolls it", async () => {
511 const harness = createHarness();
512 const surface = await harness.create();
513 const rows = Array.from({ length: 10 }, (_, index) => `row ${index}`);
514 surface.write(`\x1b[?1049h\x1b[H${rows.join("\r\n")}`);
515 harness.flushFrame();
516 harness.pointer("pointerdown", 5, 1, {}, 0, 50);
517 harness.pointer("pointermove", 45, 1, {}, 0, 50);
518 harness.pointer("pointerup", 45, 0, {}, 0, 50);
519 const text = surface.getSelection();
520 const before = surface.getSelectionPosition();
521 expect(text).toMatch(/^row \d$/);
522​
523 surface.write("\r\nrow 10\r\nrow 11");
524 expect(surface.getSelection()).toBe(text);
525 expect(surface.getSelectionPosition()?.start.y).toBe(before!.start.y - 2);
526 });
527​
528 it("keeps a drag anchored to its text when output scrolls it mid-drag", async () => {
529 const harness = createHarness();
530 const surface = await harness.create();
531 const rows = Array.from({ length: 10 }, (_, index) => `row ${index}`);
532 surface.write(`\x1b[?1049h\x1b[H${rows.join("\r\n")}`);
533 harness.flushFrame();
534 harness.pointer("pointerdown", 5, 1, {}, 0, 50);
535 harness.pointer("pointermove", 45, 1, {}, 0, 50);
536 expect(surface.getSelection()).toBe("row 6");
537​
538 // The pointer stays over the row that output scrolls "row 8" into.
539 surface.write("\r\nrow 10\r\nrow 11");
540 harness.pointer("pointermove", 53, 1, {}, 0, 50);
541 expect(surface.getSelection()).toBe("row 6\nrow 7\nrow 8");
542 });
543​
544 it("does not activate a link replaced before pointer release", async () => {
545 const harness = createHarness();
546 const onLinkActivate = vi.fn();
547 const surface = await harness.create({ onLinkActivate });
548 surface.write("https://first.example");
549 harness.flushFrame();
550​
551 harness.pointer("pointerdown", 5, 1);
552 surface.write("\x1b[2J\x1b[Hhttps://second.example");
553 harness.flushFrame();
554 harness.pointer("pointerup", 5, 0);
555​
556 expect(onLinkActivate).not.toHaveBeenCalled();
557 });
558​
559 it.each([
560 { scenario: "missing", exists: false },
561 { scenario: "file", exists: true },
562 { scenario: "replaced", exists: true },
563 { scenario: "superseded", exists: false },
564 { scenario: "hidden", exists: false },
565 { scenario: "dragged", exists: true },
566 { scenario: "keyboard-selected", exists: false },
567 { scenario: "selection-cleared", exists: true },
568 { scenario: "output-cleaned", exists: true },
569 ])(
570 "validates a quick click without waiting for hover: $scenario",
571 async ({ scenario, exists }) => {
572 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
573 const harness = createHarness();
574 let resolveValidation!: (exists: boolean) => void;
575 const validation = new Promise<boolean>((resolve) => {
576 resolveValidation = resolve;
577 });
578 const validateLink = vi.fn(() => validation);
579 const onLinkActivate = vi.fn();
580 const surface = await harness.create({
581 beforeKey: () => true,
582 canActivateLink: () => false,
583 validateLink,
584 onLinkActivate,
585 });
586 surface.write("src/main.ts");
587 harness.flushFrame();
588 surface.selectAll();
589 expect(surface.getSelection()).toBe("src/main.ts");
590 harness.pointer("pointerdown", 5, 1);
591 expect(validateLink).toHaveBeenCalledWith("src/main.ts");
592 if (scenario === "dragged") harness.pointer("pointermove", 45, 1);
593 harness.pointer("pointerup", 5, 0);
594 expect(onLinkActivate).not.toHaveBeenCalled();
595 if (scenario === "replaced") {
596 surface.write("\r\x1b[2Ksrc/other.ts");
597 harness.flushFrame();
598 }
599 if (scenario === "superseded") harness.pointer("pointerdown", 5, 1);
600 if (scenario === "hidden") {
601 surface.setVisible(false);
602 surface.setVisible(true);
603 }
604 if (scenario === "keyboard-selected")
605 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true });
606 if (scenario === "selection-cleared") surface.clearSelection();
607 if (scenario === "output-cleaned") surface.clearSelection({ source: "output" });
608 resolveValidation(exists);
609 await validation;
610 expect(onLinkActivate).toHaveBeenCalledTimes(
611 scenario === "file" || scenario === "output-cleaned" ? 1 : 0,
612 );
613 if (scenario === "missing" || scenario === "selection-cleared")
614 expect(surface.getSelection()).toBe("");
615 if (
616 scenario === "file" ||
617 scenario === "hidden" ||
618 scenario === "superseded" ||
619 scenario === "keyboard-selected"
620 ) {
621 expect(surface.getSelection()).not.toBe("");
622 }
623 },
624 );
625​
626 it("only requests validation for a stable visible link under the pointer", async () => {
627 const harness = createHarness();
628 const onLinkHover = vi.fn();
629 const surface = await harness.create({ onLinkHover, canActivateLink: () => false });
630 surface.write("\x1b[?1049h\x1b[Hsrc/first.ts");
631 harness.flushFrame();
632 vi.advanceTimersByTime(250);
633 expect(onLinkHover).not.toHaveBeenCalled();
634​
635 harness.pointer("pointermove", 5, 0);
636 expect(onLinkHover).toHaveBeenLastCalledWith("src/first.ts");
637 onLinkHover.mockClear();
638 for (let index = 0; index < 100; index++) {
639 surface.write(`\r\x1b[2Ksrc/file-${index}.ts`);
640 harness.flushFrame();
641 vi.advanceTimersByTime(10);
642 }
643 vi.advanceTimersByTime(239);
644 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
645 vi.advanceTimersByTime(1);
646 harness.flushFrame();
647 vi.advanceTimersByTime(1_000);
648 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([["src/file-99.ts"]]);
649 onLinkHover.mockClear();
650​
651 harness.pointer("pointerleave", 5, 0);
652 surface.write("\r\x1b[2Ksrc/recent.ts");
653 harness.flushFrame();
654 vi.advanceTimersByTime(150);
655 harness.pointer("pointermove", 5, 0);
656 vi.advanceTimersByTime(99);
657 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
658 vi.advanceTimersByTime(1);
659 expect(onLinkHover).toHaveBeenLastCalledWith("src/recent.ts");
660 onLinkHover.mockClear();
661​
662 harness.pointer("pointerleave", 5, 0);
663 surface.write("\r\x1b[2Ksrc/still.ts");
664 harness.flushFrame();
665 vi.advanceTimersByTime(250);
666 surface.write("\x1b[2;1Hother output");
667 harness.flushFrame();
668 harness.pointer("pointermove", 5, 0);
669 expect(onLinkHover).toHaveBeenLastCalledWith("src/still.ts");
670 onLinkHover.mockClear();
671​
672 surface.write("\x1b[H\x1b[2Ksrc/move.ts");
673 harness.flushFrame();
674 harness.pointer("pointermove", 45, 0);
675 vi.advanceTimersByTime(150);
676 surface.write("\r\x1b[2K src/move.ts");
677 harness.flushFrame();
678 vi.advanceTimersByTime(249);
679 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
680 vi.advanceTimersByTime(1);
681 expect(onLinkHover).toHaveBeenLastCalledWith("src/move.ts");
682 onLinkHover.mockClear();
683​
684 for (const [index, cancel] of [
685 () => {
686 surface.write("\r\x1b[2Kplain text");
687 harness.flushFrame();
688 },
689 () => harness.pointer("pointerleave", 5, 0),
690 () => surface.setVisible(false),
691 () => surface.dispose(),
692 ].entries()) {
693 surface.setVisible(true);
694 surface.write(`\x1b[H\x1b[2Ksrc/next-${index}.ts`);
695 harness.flushFrame();
696 harness.pointer("pointermove", 5, 0);
697 cancel();
698 vi.advanceTimersByTime(250);
699 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
700 }
701 });
702​
703 it.each([false, true])(
704 "uses visibility %s if it changes while WASM initializes",
705 async (visible) => {
706 const harness = createHarness();
707 let markCreated!: () => void;
708 const created = new Promise<void>((resolve) => {
709 markCreated = resolve;
710 });
711 let finishLoading!: () => void;
712 const release = new Promise<void>((resolve) => {
713 finishLoading = resolve;
714 });
715 const create = GhosttyTerminalCore.create;
716 vi.spyOn(GhosttyTerminalCore, "create").mockImplementation(async (...args) => {
717 const core = await create(...args);
718 markCreated();
719 await release;
720 return core;
721 });
722 let currentVisible = !visible;
723 const pending = harness.create({
724 get visible() {
725 return currentVisible;
726 },
727 });
728 await created;
729 currentVisible = visible;
730 harness.paint.mockClear();
731 finishLoading();
732 const surface = await pending;
733​
734 expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);
735 if (!visible) expect(harness.paint).not.toHaveBeenCalled();
736 surface.write("ready\x1b[5n");
737 expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");
738 if (!visible) {
739 expect(harness.frames.size).toBe(0);
740 surface.setVisible(true);
741 } else {
742 harness.flushFrame();
743 }
744 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");
745 },
746 );
747});
748​
749const cell = (text: string): GhosttyCell => ({
750 text,
751 wide: 0,
752 foreground: { r: 255, g: 255, b: 255 },
753 background: { r: 0, g: 0, b: 0 },
754 bold: false,
755 italic: false,
756 invisible: false,
757 strikethrough: false,
758 overline: false,
759 underline: false,
760 selected: false,
761});
762​
763describe("terminalLinkAtPositionWithRange", () => {
764 it.each([
765 { text: "https://example.com/日本", cols: 80, end: { x: 23, y: 0 } },
766 { text: "src/日本/main.ts:3:1", cols: 80, end: { x: 19, y: 0 } },
767 { text: "https://example.com/🙂", cols: 80, end: { x: 21, y: 0 } },
768 { text: "https://example.com/日本", cols: 23, end: { x: 1, y: 1 } },
769 ])("keeps every cell of $text clickable at $cols columns", async ({ text, cols, end }) => {
770 const core = await GhosttyTerminalCore.create(
771 cols,
772 3,
773 8,
774 16,
775 {
776 foreground: { r: 255, g: 255, b: 255 },
777 background: { r: 0, g: 0, b: 0 },
778 cursor: { r: 255, g: 255, b: 255 },
779 },
780 () => {},
781 );
782 try {
783 core.write(text + " next");
784 const rows = core.snapshot().rowData;
785 for (let y = 0; y <= end.y; y += 1) {
786 const lastColumn = y === end.y ? end.x : cols - 2;
787 for (let x = 0; x <= lastColumn; x += 1) {
788 expect(terminalLinkAtPositionWithRange(rows, y, x)).toEqual({
789 text,
790 range: { start: { x: 0, y: 0 }, end },
791 });
792 }
793 }
794 expect(terminalLinkAtPositionWithRange(rows, end.y, end.x + 1)).toBeNull();
795 } finally {
796 core.dispose();
797 }
798 });
799​
800 it("activates a wrapped quoted Windows path from its spaces and position suffix", () => {
801 const row = (text: string, isWrapContinuation: boolean): GhosttyRow => ({
802 cells: Array.from(text, (character) => cell(character)),
803 text,
804 isWrapContinuation,
805 wrapsToNext: false,
806 });
807 const first = String.raw`"C:\Users\Jane `;
808 const second = String.raw`Doe\index.ts":12:7`;
809 const rows = [row(first, false), row(second, true)];
810 const expected = {
811 text: String.raw`C:\Users\Jane Doe\index.ts:12:7`,
812 range: { start: { x: 1, y: 0 }, end: { x: second.length - 1, y: 1 } },
813 };
814 expect(terminalLinkAtPositionWithRange(rows, 0, first.length - 1)).toEqual(expected);
815 expect(terminalLinkAtPositionWithRange(rows, 1, second.length - 1)).toEqual(expected);
816 expect(terminalLinkAtPositionWithRange(rows, 0, 0)).toBeNull();
817 });
818​
819 it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
820 const cells = [
821 cell("🙂"),
822 cell(""),
823 ...Array.from("https://t3.codes", (character) => cell(character)),
824 ];
825 const row: GhosttyRow = {
826 cells,
827 text: cells
828 .map((value) => value.text || " ")
829 .join("")
830 .trimEnd(),
831 isWrapContinuation: false,
832 wrapsToNext: false,
833 };
834​
835 expect(terminalLinkAtPositionWithRange([row], 0, 2)?.text).toBe("https://t3.codes");
836 expect(terminalLinkAtPositionWithRange([row], 0, cells.length - 1)?.text).toBe(
837 "https://t3.codes",
838 );
839 expect(terminalLinkAtPositionWithRange([row], 0, 0)).toBeNull();
840 expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
841 start: { x: 2, y: 0 },
842 end: { x: cells.length - 1, y: 0 },
843 });
844 });
845​
846 it("uses shared path matching and reconstructs soft-wrapped links", () => {
847 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
848 cells: Array.from(text.padEnd(16), (character) => cell(character)),
849 text: text.trimEnd(),
850 isWrapContinuation,
851 wrapsToNext,
852 });
853 const rows = [
854 row("https://example.", false),
855 row("com/reference", true),
856 row("~/project/file", false),
857 row("C:\\repo\\file.ts", false),
858 row("PS C:\\repo\\dir 1", false, true),
859 row("\\test> ", true),
860 ];
861​
862 expect(terminalLinkAtPositionWithRange(rows, 0, 8)?.text).toBe("https://example.com/reference");
863 expect(terminalLinkAtPositionWithRange(rows, 1, 4)?.text).toBe("https://example.com/reference");
864 expect(terminalLinkAtPositionWithRange(rows, 2, 2)?.text).toBe("~/project/file");
865 expect(terminalLinkAtPositionWithRange(rows, 3, 4)?.text).toBe("C:\\repo\\file.ts");
866 expect(terminalLinkAtPositionWithRange(rows, 4, 13)).toEqual({
867 text: "C:\\repo\\dir 1\\test",
868 range: { start: { x: 3, y: 4 }, end: { x: 4, y: 5 } },
869 });
870 expect(terminalLinkAtPositionWithRange(rows, 5, 2)?.text).toBe("C:\\repo\\dir 1\\test");
871 expect(terminalLinkAtPositionWithRange(rows, 5, 5)).toBeNull();
872 expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
873 text: "https://example.com/reference",
874 range: {
875 start: { x: 0, y: 0 },
876 end: { x: 12, y: 1 },
877 },
878 });
879 });
880​
881 it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
882 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
883 cells: Array.from(text.padEnd(16), (character) => cell(character)),
884 text: text.trimEnd(),
885 isWrapContinuation,
886 wrapsToNext,
887 });
888 const headCut = [row("ple.com/missing", true), row("head", true)];
889 expect(terminalLinkAtPositionWithRange(headCut, 0, 4)).toBeNull();
890 const tailCut = [row("https://t3.codes", false, true)];
891 expect(terminalLinkAtPositionWithRange(tailCut, 0, 8)).toBeNull();
892 const complete = [row("https://t3.codes", false), row("", false)];
893 expect(terminalLinkAtPositionWithRange(complete, 0, 8)?.text).toBe("https://t3.codes");
894 const wideFull: GhosttyRow = {
895 cells: [
896 { ...cell("🙂"), wide: 1 },
897 { ...cell(""), wide: 2 },
898 ...Array.from("https://t3.code", (character) => cell(character)),
899 ],
900 text: "🙂 https://t3.code",
901 isWrapContinuation: false,
902 wrapsToNext: true,
903 };
904 expect(terminalLinkAtPositionWithRange([wideFull], 0, 8)).toBeNull();
905 const unwrittenTail: GhosttyRow = {
906 cells: [
907 ...Array.from("https://t3.codes", (character) => cell(character)),
908 cell(""),
909 cell(""),
910 ],
911 text: "https://t3.codes",
912 isWrapContinuation: false,
913 wrapsToNext: false,
914 };
915 expect(terminalLinkAtPositionWithRange([unwrittenTail], 0, 8)?.text).toBe("https://t3.codes");
916 });
917});
918​
919describe("isTerminalCopyShortcut", () => {
920 const event = (overrides: Partial<Parameters<typeof isTerminalCopyShortcut>[0]> = {}) => ({
921 ctrlKey: false,
922 key: "c",
923 metaKey: false,
924 shiftKey: false,
925 ...overrides,
926 });
927​
928 it("keeps Ctrl+C available for SIGINT on macOS", () => {
929 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
930 expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
931 });
932​
933 it("uses the produced character instead of the physical key position", () => {
934 expect(isTerminalCopyShortcut(event({ key: "C", metaKey: true }), "MacIntel")).toBe(true);
935 expect(isTerminalCopyShortcut(event({ key: "j", metaKey: true }), "MacIntel")).toBe(false);
936 });
937});
938​
939describe("applyTerminalCopyEvent", () => {
940 // regression: #7678 copying a terminal selection produced a blank clipboard
941 it("leaves the writeText fallback alive when clipboardData is missing", () => {
942 // Electron menu Copy often omits clipboardData.
943 expect(applyTerminalCopyEvent("ls -la", null)).toEqual({
944 preventDefault: false,
945 claimWriteFallback: false,
946 });
947 expect(applyTerminalCopyEvent("", { setData: vi.fn() })).toEqual({
948 preventDefault: false,
949 claimWriteFallback: false,
950 });
951 });
952​
953 it("primes the current selection before a copy event with no clipboardData", () => {
954 const input = {
955 value: "stale",
956 selectionStart: 0,
957 selectionEnd: 0,
958 select() {
959 this.selectionStart = 0;
960 this.selectionEnd = this.value.length;
961 },
962 };
963 primeTerminalCopyInput(input, "git status");
964 expect(applyTerminalCopyEvent("git status", null)).toEqual({
965 preventDefault: false,
966 claimWriteFallback: false,
967 });
968 expect(input.value).toBe("git status");
969 expect(input.selectionStart).toBe(0);
970 expect(input.selectionEnd).toBe(10);
971 });
972});
973​
974describe("primeTerminalCopyInput", () => {
975 it("does not wipe an IME candidate that replaced the primed copy", () => {
976 const input = { value: "", select() {} };
977 primeTerminalCopyInput(input, "git status");
978 input.value = "あ";
979 clearPrimedTerminalCopyInput(input, "git status");
980 expect(input.value).toBe("あ");
981 });
982});
983​
984describe("isTerminalCompositionKey", () => {
985 const event = (
986 overrides: Partial<Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">> = {},
987 ) => ({
988 isComposing: false,
989 key: "a",
990 keyCode: 65,
991 ...overrides,
992 });
993​
994 it("treats in-progress IME keydowns as composition so the copy primer cannot wipe them", () => {
995 expect(isTerminalCompositionKey(event({ isComposing: true }), false)).toBe(true);
996 expect(isTerminalCompositionKey(event(), true)).toBe(true);
997 expect(isTerminalCompositionKey(event({ key: "Process" }), false)).toBe(true);
998 expect(isTerminalCompositionKey(event({ keyCode: 229 }), false)).toBe(true);
999 });
1000});
1001​
1002describe("application mouse reporting", () => {
1003 it("drops repeated motion reports until another mouse action resets the cell", () => {
1004 const first = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", "");
1005 expect(first).toEqual({ send: true, nextMotionData: "\u001b[<35;8;4M" });
1006​
1007 const duplicate = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", first.nextMotionData);
1008 expect(duplicate).toEqual({ send: false, nextMotionData: "\u001b[<35;8;4M" });
1009​
1010 const press = resolveTerminalMouseData("press", "\u001b[<0;8;4M", duplicate.nextMotionData);
1011 expect(press).toEqual({ send: true, nextMotionData: "" });
1012​
1013 expect(resolveTerminalMouseData("motion", "\u001b[<35;8;4M", press.nextMotionData)).toEqual({
1014 send: true,
1015 nextMotionData: "\u001b[<35;8;4M",
1016 });
1017 });
1018});
1019​
1020describe("terminalContentOriginY", () => {
1021 it("keeps the prompt stationary while a drag crosses row boundaries", () => {
1022 for (let height = 88; height < 104; height += 1) {
1023 const rows = Math.max(1, Math.floor((height - 8) / 16));
1024 const origin = terminalContentOriginY(height, 4, rows, 16, true);
1025 expect(origin + rows * 16).toBe(height - 4);
1027 });
1028});
1029​
1030describe("terminalWheelDeltaRows", () => {
1031 it("accumulates fractional pixel deltas across events", () => {
1032 let remainder = 0;
1033 let scrolled = 0;
1034 for (let index = 0; index < 4; index += 1) {
1035 const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
1036 remainder = result.remainder;
1037 scrolled += result.rows;
1039 expect(scrolled).toBe(1);
1040 expect(remainder).toBeCloseTo(4 / 16);
1041 });
1042});
1043​
1044// regression: #19492 drag selection scrolled one row per tick however far past the edge
1045describe("terminalSelectionAutoscrollRows", () => {
1046 it("scrolls more rows per tick the farther the pointer is past an edge", () => {
1047 const top = 100;
1048 const bottom = 500;
1049 expect(terminalSelectionAutoscrollRows(300, top, bottom)).toBe(0);
1050 expect(terminalSelectionAutoscrollRows(99, top, bottom)).toBe(-1);
1051 expect(terminalSelectionAutoscrollRows(75, top, bottom)).toBe(-8);
1052 expect(terminalSelectionAutoscrollRows(501, top, bottom)).toBe(1);
1053 expect(terminalSelectionAutoscrollRows(525, top, bottom)).toBe(8);
1054 expect(terminalSelectionAutoscrollRows(550, top, bottom)).toBe(15);
1055 expect(terminalSelectionAutoscrollRows(2_000, top, bottom)).toBe(15);
1056 });
1057});
1058​
1059describe("advanceTerminalSelectionClickSequence", () => {
1060 it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
1061 const first = advanceTerminalSelectionClickSequence(null, {
1062 clientX: 20,
1063 clientY: 30,
1064 timeStamp: 1_000,
1065 });
1066 const second = advanceTerminalSelectionClickSequence(first, {
1067 clientX: 22,
1068 clientY: 29,
1069 timeStamp: 1_200,
1070 });
1071 const third = advanceTerminalSelectionClickSequence(second, {
1072 clientX: 21,
1073 clientY: 31,
1074 timeStamp: 1_400,
1075 });
1076​
1077 expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
1078 });
1079});