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