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