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([false, true])(
541 "uses visibility %s if it changes while WASM initializes",
542 async (visible) => {
543 const harness = createHarness();
544 let markCreated!: () => void;
545 const created = new Promise<void>((resolve) => {
546 markCreated = resolve;
547 });
548 let finishLoading!: () => void;
549 const release = new Promise<void>((resolve) => {
550 finishLoading = resolve;
551 });
552 const create = GhosttyTerminalCore.create;
553 vi.spyOn(GhosttyTerminalCore, "create").mockImplementation(async (...args) => {
554 const core = await create(...args);
555 markCreated();
556 await release;
557 return core;
558 });
559 let currentVisible = !visible;
560 const pending = harness.create({
561 get visible() {
562 return currentVisible;
563 },
564 });
565 await created;
566 currentVisible = visible;
567 harness.paint.mockClear();
568 finishLoading();
569 const surface = await pending;
570
571 expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);
572 if (!visible) expect(harness.paint).not.toHaveBeenCalled();
573 surface.write("ready\x1b[5n");
574 expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");
575 if (!visible) {
576 expect(harness.frames.size).toBe(0);
577 surface.setVisible(true);
578 } else {
579 harness.flushFrame();
580 }
581 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");
582 },
583 );
584});
585
586const cell = (text: string): GhosttyCell => ({
587 text,
588 wide: 0,
589 foreground: { r: 255, g: 255, b: 255 },
590 background: { r: 0, g: 0, b: 0 },
591 bold: false,
592 italic: false,
593 invisible: false,
594 strikethrough: false,
595 overline: false,
596 underline: false,
597 selected: false,
598});
599
600describe("terminalLinkAtPositionWithRange", () => {
601 it.each([
602 { text: "https://example.com/日本", cols: 80, end: { x: 23, y: 0 } },
603 { text: "src/日本/main.ts:3:1", cols: 80, end: { x: 19, y: 0 } },
604 { text: "https://example.com/🙂", cols: 80, end: { x: 21, y: 0 } },
605 { text: "https://example.com/日本", cols: 23, end: { x: 1, y: 1 } },
606 ])("keeps every cell of $text clickable at $cols columns", async ({ text, cols, end }) => {
607 const core = await GhosttyTerminalCore.create(
608 cols,
609 3,
610 8,
611 16,
612 {
613 foreground: { r: 255, g: 255, b: 255 },
614 background: { r: 0, g: 0, b: 0 },
615 cursor: { r: 255, g: 255, b: 255 },
616 },
617 () => {},
618 );
619 try {
620 core.write(text + " next");
621 const rows = core.snapshot().rowData;
622 for (let y = 0; y <= end.y; y += 1) {
623 const lastColumn = y === end.y ? end.x : cols - 2;
624 for (let x = 0; x <= lastColumn; x += 1) {
625 expect(terminalLinkAtPositionWithRange(rows, y, x)).toEqual({
626 text,
627 range: { start: { x: 0, y: 0 }, end },
628 });
629 }
630 }
631 expect(terminalLinkAtPositionWithRange(rows, end.y, end.x + 1)).toBeNull();
632 } finally {
633 core.dispose();
634 }
635 });
636
637 it("activates a wrapped quoted Windows path from its spaces and position suffix", () => {
638 const row = (text: string, isWrapContinuation: boolean): GhosttyRow => ({
639 cells: Array.from(text, (character) => cell(character)),
640 text,
641 isWrapContinuation,
642 wrapsToNext: false,
643 });
644 const first = String.raw`"C:\Users\Jane `;
645 const second = String.raw`Doe\index.ts":12:7`;
646 const rows = [row(first, false), row(second, true)];
647 const expected = {
648 text: String.raw`C:\Users\Jane Doe\index.ts:12:7`,
649 range: { start: { x: 1, y: 0 }, end: { x: second.length - 1, y: 1 } },
650 };
651 expect(terminalLinkAtPositionWithRange(rows, 0, first.length - 1)).toEqual(expected);
652 expect(terminalLinkAtPositionWithRange(rows, 1, second.length - 1)).toEqual(expected);
653 expect(terminalLinkAtPositionWithRange(rows, 0, 0)).toBeNull();
654 });
655
656 it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
657 const cells = [
658 cell("🙂"),
659 cell(""),
660 ...Array.from("https://t3.codes", (character) => cell(character)),
661 ];
662 const row: GhosttyRow = {
663 cells,
664 text: cells
665 .map((value) => value.text || " ")
666 .join("")
667 .trimEnd(),
668 isWrapContinuation: false,
669 wrapsToNext: false,
670 };
671
672 expect(terminalLinkAtPositionWithRange([row], 0, 2)?.text).toBe("https://t3.codes");
673 expect(terminalLinkAtPositionWithRange([row], 0, cells.length - 1)?.text).toBe(
674 "https://t3.codes",
675 );
676 expect(terminalLinkAtPositionWithRange([row], 0, 0)).toBeNull();
677 expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
678 start: { x: 2, y: 0 },
679 end: { x: cells.length - 1, y: 0 },
680 });
681 });
682
683 it("uses shared path matching and reconstructs soft-wrapped links", () => {
684 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
685 cells: Array.from(text.padEnd(16), (character) => cell(character)),
686 text: text.trimEnd(),
687 isWrapContinuation,
688 wrapsToNext,
689 });
690 const rows = [
691 row("https://example.", false),
692 row("com/reference", true),
693 row("~/project/file", false),
694 row("C:\\repo\\file.ts", false),
695 row("PS C:\\repo\\dir 1", false, true),
696 row("\\test> ", true),
697 ];
698
699 expect(terminalLinkAtPositionWithRange(rows, 0, 8)?.text).toBe("https://example.com/reference");
700 expect(terminalLinkAtPositionWithRange(rows, 1, 4)?.text).toBe("https://example.com/reference");
701 expect(terminalLinkAtPositionWithRange(rows, 2, 2)?.text).toBe("~/project/file");
702 expect(terminalLinkAtPositionWithRange(rows, 3, 4)?.text).toBe("C:\\repo\\file.ts");
703 expect(terminalLinkAtPositionWithRange(rows, 4, 13)).toEqual({
704 text: "C:\\repo\\dir 1\\test",
705 range: { start: { x: 3, y: 4 }, end: { x: 4, y: 5 } },
706 });
707 expect(terminalLinkAtPositionWithRange(rows, 5, 2)?.text).toBe("C:\\repo\\dir 1\\test");
708 expect(terminalLinkAtPositionWithRange(rows, 5, 5)).toBeNull();
709 expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
710 text: "https://example.com/reference",
711 range: {
712 start: { x: 0, y: 0 },
713 end: { x: 12, y: 1 },
714 },
715 });
716 });
717
718 it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
719 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
720 cells: Array.from(text.padEnd(16), (character) => cell(character)),
721 text: text.trimEnd(),
722 isWrapContinuation,
723 wrapsToNext,
724 });
725 const headCut = [row("ple.com/missing", true), row("head", true)];
726 expect(terminalLinkAtPositionWithRange(headCut, 0, 4)).toBeNull();
727 const tailCut = [row("https://t3.codes", false, true)];
728 expect(terminalLinkAtPositionWithRange(tailCut, 0, 8)).toBeNull();
729 const complete = [row("https://t3.codes", false), row("", false)];
730 expect(terminalLinkAtPositionWithRange(complete, 0, 8)?.text).toBe("https://t3.codes");
731 const wideFull: GhosttyRow = {
732 cells: [
733 { ...cell("🙂"), wide: 1 },
734 { ...cell(""), wide: 2 },
735 ...Array.from("https://t3.code", (character) => cell(character)),
736 ],
737 text: "🙂 https://t3.code",
738 isWrapContinuation: false,
739 wrapsToNext: true,
740 };
741 expect(terminalLinkAtPositionWithRange([wideFull], 0, 8)).toBeNull();
742 const unwrittenTail: GhosttyRow = {
743 cells: [
744 ...Array.from("https://t3.codes", (character) => cell(character)),
745 cell(""),
746 cell(""),
747 ],
748 text: "https://t3.codes",
749 isWrapContinuation: false,
750 wrapsToNext: false,
751 };
752 expect(terminalLinkAtPositionWithRange([unwrittenTail], 0, 8)?.text).toBe("https://t3.codes");
753 });
754});
755
756describe("isTerminalCopyShortcut", () => {
757 const event = (overrides: Partial<Parameters<typeof isTerminalCopyShortcut>[0]> = {}) => ({
758 ctrlKey: false,
759 key: "c",
760 metaKey: false,
761 shiftKey: false,
762 ...overrides,
763 });
764
765 it("keeps Ctrl+C available for SIGINT on macOS", () => {
766 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
767 expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
768 });
769
770 it("uses the produced character instead of the physical key position", () => {
771 expect(isTerminalCopyShortcut(event({ key: "C", metaKey: true }), "MacIntel")).toBe(true);
772 expect(isTerminalCopyShortcut(event({ key: "j", metaKey: true }), "MacIntel")).toBe(false);
773 });
774});
775
776describe("applyTerminalCopyEvent", () => {
777 // regression: #7678 copying a terminal selection produced a blank clipboard
778 it("leaves the writeText fallback alive when clipboardData is missing", () => {
779 // Electron menu Copy often omits clipboardData.
780 expect(applyTerminalCopyEvent("ls -la", null)).toEqual({
781 preventDefault: false,
782 claimWriteFallback: false,
783 });
784 expect(applyTerminalCopyEvent("", { setData: vi.fn() })).toEqual({
785 preventDefault: false,
786 claimWriteFallback: false,
787 });
788 });
789
790 it("primes the current selection before a copy event with no clipboardData", () => {
791 const input = {
792 value: "stale",
793 selectionStart: 0,
794 selectionEnd: 0,
795 select() {
796 this.selectionStart = 0;
797 this.selectionEnd = this.value.length;
798 },
799 };
800 primeTerminalCopyInput(input, "git status");
801 expect(applyTerminalCopyEvent("git status", null)).toEqual({
802 preventDefault: false,
803 claimWriteFallback: false,
804 });
805 expect(input.value).toBe("git status");
806 expect(input.selectionStart).toBe(0);
807 expect(input.selectionEnd).toBe(10);
808 });
809});
810
811describe("primeTerminalCopyInput", () => {
812 it("does not wipe an IME candidate that replaced the primed copy", () => {
813 const input = { value: "", select() {} };
814 primeTerminalCopyInput(input, "git status");
815 input.value = "あ";
816 clearPrimedTerminalCopyInput(input, "git status");
817 expect(input.value).toBe("あ");
818 });
819});
820
821describe("isTerminalCompositionKey", () => {
822 const event = (
823 overrides: Partial<Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">> = {},
824 ) => ({
825 isComposing: false,
826 key: "a",
827 keyCode: 65,
828 ...overrides,
829 });
830
831 it("treats in-progress IME keydowns as composition so the copy primer cannot wipe them", () => {
832 expect(isTerminalCompositionKey(event({ isComposing: true }), false)).toBe(true);
833 expect(isTerminalCompositionKey(event(), true)).toBe(true);
834 expect(isTerminalCompositionKey(event({ key: "Process" }), false)).toBe(true);
835 expect(isTerminalCompositionKey(event({ keyCode: 229 }), false)).toBe(true);
836 });
837});
838
839describe("application mouse reporting", () => {
840 it("drops repeated motion reports until another mouse action resets the cell", () => {
841 const first = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", "");
842 expect(first).toEqual({ send: true, nextMotionData: "\u001b[<35;8;4M" });
843
844 const duplicate = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", first.nextMotionData);
845 expect(duplicate).toEqual({ send: false, nextMotionData: "\u001b[<35;8;4M" });
846
847 const press = resolveTerminalMouseData("press", "\u001b[<0;8;4M", duplicate.nextMotionData);
848 expect(press).toEqual({ send: true, nextMotionData: "" });
849
850 expect(resolveTerminalMouseData("motion", "\u001b[<35;8;4M", press.nextMotionData)).toEqual({
851 send: true,
852 nextMotionData: "\u001b[<35;8;4M",
853 });
854 });
855});
856
857describe("terminalContentOriginY", () => {
858 it("keeps the prompt stationary while a drag crosses row boundaries", () => {
859 for (let height = 88; height < 104; height += 1) {
860 const rows = Math.max(1, Math.floor((height - 8) / 16));
861 const origin = terminalContentOriginY(height, 4, rows, 16, true);
862 expect(origin + rows * 16).toBe(height - 4);
863 }
864 });
865});
866
867describe("terminalWheelDeltaRows", () => {
868 it("accumulates fractional pixel deltas across events", () => {
869 let remainder = 0;
870 let scrolled = 0;
871 for (let index = 0; index < 4; index += 1) {
872 const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
873 remainder = result.remainder;
874 scrolled += result.rows;
875 }
876 expect(scrolled).toBe(1);
877 expect(remainder).toBeCloseTo(4 / 16);
878 });
879});
880
881// regression: #19492 drag selection scrolled one row per tick however far past the edge
882describe("terminalSelectionAutoscrollRows", () => {
883 it("scrolls more rows per tick the farther the pointer is past an edge", () => {
884 const top = 100;
885 const bottom = 500;
886 expect(terminalSelectionAutoscrollRows(300, top, bottom)).toBe(0);
887 expect(terminalSelectionAutoscrollRows(99, top, bottom)).toBe(-1);
888 expect(terminalSelectionAutoscrollRows(75, top, bottom)).toBe(-8);
889 expect(terminalSelectionAutoscrollRows(501, top, bottom)).toBe(1);
890 expect(terminalSelectionAutoscrollRows(525, top, bottom)).toBe(8);
891 expect(terminalSelectionAutoscrollRows(550, top, bottom)).toBe(15);
892 expect(terminalSelectionAutoscrollRows(2_000, top, bottom)).toBe(15);
893 });
894});
895
896describe("advanceTerminalSelectionClickSequence", () => {
897 it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
898 const first = advanceTerminalSelectionClickSequence(null, {
899 clientX: 20,
900 clientY: 30,
901 timeStamp: 1_000,
902 });
903 const second = advanceTerminalSelectionClickSequence(first, {
904 clientX: 22,
905 clientY: 29,
906 timeStamp: 1_200,
907 });
908 const third = advanceTerminalSelectionClickSequence(second, {
909 clientX: 21,
910 clientY: 31,
911 timeStamp: 1_400,
912 });
913
914 expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
915 });
916});