@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,144 lines 40.3 KB
Raw
1 import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2 import {
3 applyTerminalAttachStreamEvent,
4 INITIAL_TERMINAL_OUTPUT_CURSOR,
5 nextTerminalAttachSeedState,
6 } from "@t3tools/client-runtime/state/terminal";
7 import { synchronizeTerminalSession } from "../../components/ThreadTerminalDrawer";
8
9 import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";
10 import {
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
26 vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({
27 default: (await import("./vendor/ghostty-vt.wasm?inline")).default,
28 }));
29 vi.mock("./vendor/ghostty-write-pty.wasm?url&no-inline", async () => ({
30 default: (await import("./vendor/ghostty-write-pty.wasm?inline")).default,
31 }));
32
33 describe("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("skips middle-click selection paste when the desktop turned primary paste off", async () => {
312 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
313 const harness = createHarness();
314 const surface = await harness.create();
315 surface.write("echo hi");
316 surface.selectAll();
317 const pasteFromClipboard = vi.spyOn(surface, "pasteFromClipboard");
318
319 let primaryPasteEnabled = false;
320 Object.assign(window, { desktopBridge: { getPrimaryPasteEnabled: () => primaryPasteEnabled } });
321 harness.pointer("pointerdown", 5, 4, {}, 1);
322 expect(pasteFromClipboard).not.toHaveBeenCalled();
323
324 primaryPasteEnabled = true;
325 harness.pointer("pointerdown", 5, 4, {}, 1);
326 expect(pasteFromClipboard).toHaveBeenCalledOnce();
327 });
328
329 it("leaves modified history keys with alternate-screen applications", async () => {
330 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
331 const harness = createHarness();
332 const surface = await harness.create({ beforeKey: () => true });
333 surface.write("\x1b[?1049happ");
334 key(surface, "PageUp", "PageUp", { shiftKey: true });
335 key(surface, "End", "End", { ctrlKey: true, shiftKey: true });
336 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual(["\x1b[5;2~", "\x1b[1;6F"]);
337 surface.selectAll();
338 expect(surface.getSelection()).toBe("app");
339 surface.write("\x1b[?1049l");
340 expect(surface.getSelection()).toBe("");
341 });
342
343 it("suppresses local shortcut releases in Kitty sessions, including read-only observers", async () => {
344 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
345 const harness = createHarness();
346 const surface = await harness.create({ beforeKey: () => true });
347 surface.input.readOnly = true;
348 surface.write("history\x1b[>31u");
349 for (const [name, code, modifiers] of [
350 ["PageUp", "PageUp", { shiftKey: true }],
351 ["Home", "Home", { ctrlKey: true, shiftKey: true }],
352 ["a", "KeyA", { ctrlKey: true, shiftKey: true }],
353 ] as const) {
354 key(surface, name, code, modifiers);
355 key(surface, name, code, modifiers, "keyup");
356 }
357 expect(surface.getSelection()).toBe("history");
358 expect(harness.onData).not.toHaveBeenCalled();
359
360 key(surface, "PageUp", "PageUp");
361 key(surface, "PageUp", "PageUp", {}, "keyup");
362 expect(harness.onData).toHaveBeenCalledTimes(2);
363 expect(harness.onData.mock.calls[1]?.[0]).toContain(":3");
364 });
365
366 it("reports Kitty releases only for presses encoded by this surface", async () => {
367 const harness = createHarness();
368 const surface = await harness.create({ beforeKey: () => true });
369 surface.write("\x1b[>11u");
370
371 key(surface, "a", "KeyA");
372 key(surface, "a", "KeyA", {}, "keyup");
373 key(surface, "Control", "ControlLeft", { ctrlKey: true });
374 // App capture stops Ctrl+D before it reaches the terminal input.
375 key(surface, "d", "KeyD", { ctrlKey: true }, "keydown", window);
376 key(surface, "d", "KeyD", { ctrlKey: true }, "keyup");
377 key(surface, "Control", "ControlLeft", {}, "keyup");
378
379 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([
380 "\x1b[97u",
381 "\x1b[97;1:3u",
382 "\x1b[57442;5u",
383 "\x1b[57442;1:3u",
384 ]);
385 });
386
387 it("keeps a held Kitty press through focus changes and an app-consumed repeat", async () => {
388 const harness = createHarness();
389 let consumeRepeat = false;
390 const surface = await harness.create({ beforeKey: () => !consumeRepeat });
391 surface.write("\x1b[>11u");
392
393 key(surface, "a", "KeyA");
394 key(surface, "a", "KeyA", { repeat: true });
395 surface.input.dispatchEvent(new Event("blur"));
396 window.dispatchEvent(new Event("blur"));
397 window.dispatchEvent(new Event("focus"));
398 surface.input.dispatchEvent(new Event("focus"));
399 consumeRepeat = true;
400 key(surface, "a", "KeyA", { repeat: true });
401 key(surface, "a", "KeyA", {}, "keyup");
402
403 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([
404 "\x1b[97u",
405 "\x1b[97;1:2u",
406 "\x1b[97;1:3u",
407 ]);
408 });
409
410 it("reports focus transitions only while DEC 1004 is enabled", async () => {
411 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
412 const harness = createHarness();
413 const surface = await harness.create();
414 const blur = () => surface.input.dispatchEvent(new Event("blur"));
415 const reports = () => harness.onData.mock.calls.map(([data]) => data);
416
417 surface.write("\x1b[?1004h");
418 surface.focus();
419 surface.focus();
420 blur();
421 blur();
422 expect(reports()).toEqual(["\x1b[I", "\x1b[O"]);
423
424 harness.onData.mockClear();
425 surface.write("\x1b[?1004l");
426 surface.focus();
427 blur();
428 expect(reports()).toEqual([]);
429 });
430
431 it("reports the blur of an input focused while the surface was still loading", async () => {
432 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
433 const harness = createHarness();
434 const pending = harness.create();
435 harness.mount.children[1]?.focus();
436 const surface = await pending;
437
438 surface.write("\x1b[?1004h");
439 surface.input.dispatchEvent(new Event("blur"));
440 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual(["\x1b[O"]);
441 });
442
443 it("honors host interception, IME candidates, and AltGr before local shortcuts", async () => {
444 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
445 const harness = createHarness();
446 let allow = false;
447 const surface = await harness.create({ beforeKey: () => allow });
448 surface.write("hello\x1b[>31u");
449 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true });
450 key(surface, "a", "KeyA", {}, "keyup");
451 expect(surface.hasSelection()).toBe(false);
452 allow = true;
453 surface.input.value = "候補";
454 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true, isComposing: true });
455 key(surface, "a", "KeyA", {}, "keyup");
456 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true, keyCode: 229 });
457 key(surface, "a", "KeyA", {}, "keyup");
458 key(surface, "a", "KeyA", {
459 ctrlKey: true,
460 shiftKey: true,
461 altKey: true,
462 getModifierState: (modifier) => modifier === "AltGraph",
463 });
464 key(surface, "a", "KeyA", {}, "keyup");
465 expect(surface.input.value).toBe("候補");
466 expect(surface.hasSelection()).toBe(false);
467 expect(harness.onData).not.toHaveBeenCalled();
468 });
469
470 function paste(surface: GhosttyTerminalSurface, text: string) {
471 surface.input.dispatchEvent(
472 Object.assign(new Event("paste", { cancelable: true }), {
473 clipboardData: { getData: () => text },
474 }),
475 );
476 }
477
478 it.each(["native", "clipboard"])("pastes once when %s arrives first", async (first) => {
479 const harness = createHarness();
480 const read = Promise.resolve("echo hi");
481 vi.stubGlobal("navigator", {
482 platform: "MacIntel",
483 clipboard: { readText: () => read },
484 });
485 const surface = await harness.create({ beforeKey: () => true });
486
487 key(surface, "v", "KeyV", { metaKey: true });
488 if (first === "native") paste(surface, "echo hi");
489 await read;
490 if (first === "clipboard") paste(surface, "echo hi");
491
492 expect(harness.onData.mock.calls).toEqual([["echo hi"]]);
493 });
494
495 it.each(["V keyup", "blur", "Meta keyup without V keyup"])(
496 "accepts a later identical menu paste after %s",
497 async (end) => {
498 const harness = createHarness();
499 const read = Promise.resolve("echo hi");
500 vi.stubGlobal("navigator", {
501 platform: "MacIntel",
502 clipboard: { readText: () => read },
503 });
504 const surface = await harness.create({ beforeKey: () => true });
505
506 key(surface, "v", "KeyV", { metaKey: true });
507 await read;
508 expect(harness.onData.mock.calls).toEqual([["echo hi"]]);
509 if (end === "blur") surface.input.dispatchEvent(new Event("blur"));
510 else if (end === "V keyup") key(surface, "v", "KeyV", { metaKey: true }, "keyup");
511 // macOS can omit V keyup while Command is held.
512 else key(surface, "Meta", "MetaLeft", {}, "keyup");
513 paste(surface, "echo hi");
514
515 expect(harness.onData.mock.calls).toEqual([["echo hi"], ["echo hi"]]);
516 },
517 );
518
519 it("keeps a selection through redraws until the selected text changes", async () => {
520 const harness = createHarness();
521 const surface = await harness.create();
522 const seed = nextTerminalAttachSeedState();
523 let state = applyTerminalAttachStreamEvent(seed, {
524 type: "snapshot",
525 snapshot: {
526 threadId: "thread",
527 terminalId: "term-1",
528 cwd: "/repo",
529 worktreePath: null,
530 status: "running",
531 pid: 123,
532 history: "* Working |",
533 exitCode: null,
534 exitSignal: null,
535 label: "Terminal",
536 updatedAt: "2026-10-20T00:00:00.000Z",
537 },
538 });
539 let cursor = synchronizeTerminalSession(surface, seed, state, INITIAL_TERMINAL_OUTPUT_CURSOR);
540 harness.flushFrame();
541 harness.pointer("pointerdown", 5, 1);
542 harness.pointer("pointermove", 85, 1);
543 harness.pointer("pointerup", 85, 0);
544 expect(surface.getSelection()).toBe("* Working |");
545
546 // A TUI repaints its spinner line in place, the way Claude Code redraws.
547 const redraw = (data: string) => {
548 const previous = state;
549 state = applyTerminalAttachStreamEvent(state, {
550 type: "output",
551 threadId: "thread",
552 terminalId: "term-1",
553 data,
554 });
555 cursor = synchronizeTerminalSession(surface, previous, state, cursor);
556 };
557 redraw("\r\x1b[2K* Working |");
558 expect(surface.getSelection()).toBe("* Working |");
559
560 redraw("\r\x1b[2K* Working /");
561 expect(surface.getSelection()).toBe("");
562 expect(surface.getSelectionPosition()).toBeNull();
563 });
564
565 it("reports where a selection sits after output scrolls it", async () => {
566 const harness = createHarness();
567 const surface = await harness.create();
568 const rows = Array.from({ length: 10 }, (_, index) => `row ${index}`);
569 surface.write(`\x1b[?1049h\x1b[H${rows.join("\r\n")}`);
570 harness.flushFrame();
571 harness.pointer("pointerdown", 5, 1, {}, 0, 50);
572 harness.pointer("pointermove", 45, 1, {}, 0, 50);
573 harness.pointer("pointerup", 45, 0, {}, 0, 50);
574 const text = surface.getSelection();
575 const before = surface.getSelectionPosition();
576 expect(text).toMatch(/^row \d$/);
577
578 surface.write("\r\nrow 10\r\nrow 11");
579 expect(surface.getSelection()).toBe(text);
580 expect(surface.getSelectionPosition()?.start.y).toBe(before!.start.y - 2);
581 });
582
583 it("keeps a drag anchored to its text when output scrolls it mid-drag", async () => {
584 const harness = createHarness();
585 const surface = await harness.create();
586 const rows = Array.from({ length: 10 }, (_, index) => `row ${index}`);
587 surface.write(`\x1b[?1049h\x1b[H${rows.join("\r\n")}`);
588 harness.flushFrame();
589 harness.pointer("pointerdown", 5, 1, {}, 0, 50);
590 harness.pointer("pointermove", 45, 1, {}, 0, 50);
591 expect(surface.getSelection()).toBe("row 6");
592
593 // The pointer stays over the row that output scrolls "row 8" into.
594 surface.write("\r\nrow 10\r\nrow 11");
595 harness.pointer("pointermove", 53, 1, {}, 0, 50);
596 expect(surface.getSelection()).toBe("row 6\nrow 7\nrow 8");
597 });
598
599 it("does not activate a link replaced before pointer release", async () => {
600 const harness = createHarness();
601 const onLinkActivate = vi.fn();
602 const surface = await harness.create({ onLinkActivate });
603 surface.write("https://first.example");
604 harness.flushFrame();
605
606 harness.pointer("pointerdown", 5, 1);
607 surface.write("\x1b[2J\x1b[Hhttps://second.example");
608 harness.flushFrame();
609 harness.pointer("pointerup", 5, 0);
610
611 expect(onLinkActivate).not.toHaveBeenCalled();
612 });
613
614 it.each([
615 { scenario: "missing", exists: false },
616 { scenario: "file", exists: true },
617 { scenario: "replaced", exists: true },
618 { scenario: "superseded", exists: false },
619 { scenario: "hidden", exists: false },
620 { scenario: "dragged", exists: true },
621 { scenario: "keyboard-selected", exists: false },
622 { scenario: "selection-cleared", exists: true },
623 { scenario: "output-cleaned", exists: true },
624 ])(
625 "validates a quick click without waiting for hover: $scenario",
626 async ({ scenario, exists }) => {
627 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
628 const harness = createHarness();
629 let resolveValidation!: (exists: boolean) => void;
630 const validation = new Promise<boolean>((resolve) => {
631 resolveValidation = resolve;
632 });
633 const validateLink = vi.fn(() => validation);
634 const onLinkActivate = vi.fn();
635 const surface = await harness.create({
636 beforeKey: () => true,
637 canActivateLink: () => false,
638 validateLink,
639 onLinkActivate,
640 });
641 surface.write("src/main.ts");
642 harness.flushFrame();
643 surface.selectAll();
644 expect(surface.getSelection()).toBe("src/main.ts");
645 harness.pointer("pointerdown", 5, 1);
646 expect(validateLink).toHaveBeenCalledWith("src/main.ts");
647 if (scenario === "dragged") harness.pointer("pointermove", 45, 1);
648 harness.pointer("pointerup", 5, 0);
649 expect(onLinkActivate).not.toHaveBeenCalled();
650 if (scenario === "replaced") {
651 surface.write("\r\x1b[2Ksrc/other.ts");
652 harness.flushFrame();
653 }
654 if (scenario === "superseded") harness.pointer("pointerdown", 5, 1);
655 if (scenario === "hidden") {
656 surface.setVisible(false);
657 surface.setVisible(true);
658 }
659 if (scenario === "keyboard-selected")
660 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true });
661 if (scenario === "selection-cleared") surface.clearSelection();
662 if (scenario === "output-cleaned") surface.clearSelection({ source: "output" });
663 resolveValidation(exists);
664 await validation;
665 expect(onLinkActivate).toHaveBeenCalledTimes(
666 scenario === "file" || scenario === "output-cleaned" ? 1 : 0,
667 );
668 if (scenario === "missing" || scenario === "selection-cleared")
669 expect(surface.getSelection()).toBe("");
670 if (
671 scenario === "file" ||
672 scenario === "hidden" ||
673 scenario === "superseded" ||
674 scenario === "keyboard-selected"
675 ) {
676 expect(surface.getSelection()).not.toBe("");
677 }
678 },
679 );
680
681 it("only requests validation for a stable visible link under the pointer", async () => {
682 const harness = createHarness();
683 const onLinkHover = vi.fn();
684 const surface = await harness.create({ onLinkHover, canActivateLink: () => false });
685 surface.write("\x1b[?1049h\x1b[Hsrc/first.ts");
686 harness.flushFrame();
687 vi.advanceTimersByTime(250);
688 expect(onLinkHover).not.toHaveBeenCalled();
689
690 harness.pointer("pointermove", 5, 0);
691 expect(onLinkHover).toHaveBeenLastCalledWith("src/first.ts");
692 onLinkHover.mockClear();
693 for (let index = 0; index < 100; index++) {
694 surface.write(`\r\x1b[2Ksrc/file-${index}.ts`);
695 harness.flushFrame();
696 vi.advanceTimersByTime(10);
697 }
698 vi.advanceTimersByTime(239);
699 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
700 vi.advanceTimersByTime(1);
701 harness.flushFrame();
702 vi.advanceTimersByTime(1_000);
703 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([["src/file-99.ts"]]);
704 onLinkHover.mockClear();
705
706 harness.pointer("pointerleave", 5, 0);
707 surface.write("\r\x1b[2Ksrc/recent.ts");
708 harness.flushFrame();
709 vi.advanceTimersByTime(150);
710 harness.pointer("pointermove", 5, 0);
711 vi.advanceTimersByTime(99);
712 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
713 vi.advanceTimersByTime(1);
714 expect(onLinkHover).toHaveBeenLastCalledWith("src/recent.ts");
715 onLinkHover.mockClear();
716
717 harness.pointer("pointerleave", 5, 0);
718 surface.write("\r\x1b[2Ksrc/still.ts");
719 harness.flushFrame();
720 vi.advanceTimersByTime(250);
721 surface.write("\x1b[2;1Hother output");
722 harness.flushFrame();
723 harness.pointer("pointermove", 5, 0);
724 expect(onLinkHover).toHaveBeenLastCalledWith("src/still.ts");
725 onLinkHover.mockClear();
726
727 surface.write("\x1b[H\x1b[2Ksrc/move.ts");
728 harness.flushFrame();
729 harness.pointer("pointermove", 45, 0);
730 vi.advanceTimersByTime(150);
731 surface.write("\r\x1b[2K src/move.ts");
732 harness.flushFrame();
733 vi.advanceTimersByTime(249);
734 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
735 vi.advanceTimersByTime(1);
736 expect(onLinkHover).toHaveBeenLastCalledWith("src/move.ts");
737 onLinkHover.mockClear();
738
739 for (const [index, cancel] of [
740 () => {
741 surface.write("\r\x1b[2Kplain text");
742 harness.flushFrame();
743 },
744 () => harness.pointer("pointerleave", 5, 0),
745 () => surface.setVisible(false),
746 () => surface.dispose(),
747 ].entries()) {
748 surface.setVisible(true);
749 surface.write(`\x1b[H\x1b[2Ksrc/next-${index}.ts`);
750 harness.flushFrame();
751 harness.pointer("pointermove", 5, 0);
752 cancel();
753 vi.advanceTimersByTime(250);
754 expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
755 }
756 });
757
758 it.each([false, true])(
759 "uses visibility %s if it changes while WASM initializes",
760 async (visible) => {
761 const harness = createHarness();
762 let markCreated!: () => void;
763 const created = new Promise<void>((resolve) => {
764 markCreated = resolve;
765 });
766 let finishLoading!: () => void;
767 const release = new Promise<void>((resolve) => {
768 finishLoading = resolve;
769 });
770 const create = GhosttyTerminalCore.create;
771 vi.spyOn(GhosttyTerminalCore, "create").mockImplementation(async (...args) => {
772 const core = await create(...args);
773 markCreated();
774 await release;
775 return core;
776 });
777 let currentVisible = !visible;
778 const onReply = vi.fn();
779 const pending = harness.create({
780 onReply,
781 get visible() {
782 return currentVisible;
783 },
784 });
785 await created;
786 currentVisible = visible;
787 harness.paint.mockClear();
788 finishLoading();
789 const surface = await pending;
790
791 expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);
792 if (!visible) expect(harness.paint).not.toHaveBeenCalled();
793 surface.write("ready\x1b[5n");
794 expect(onReply).toHaveBeenCalledWith("\x1b[0n");
795 expect(harness.onData).not.toHaveBeenCalled();
796 if (!visible) {
797 expect(harness.frames.size).toBe(0);
798 surface.setVisible(true);
799 } else {
800 harness.flushFrame();
801 }
802 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");
803 },
804 );
805 });
806
807 const cell = (text: string): GhosttyCell => ({
808 text,
809 wide: 0,
810 foreground: { r: 255, g: 255, b: 255 },
811 background: { r: 0, g: 0, b: 0 },
812 bold: false,
813 italic: false,
814 invisible: false,
815 strikethrough: false,
816 overline: false,
817 underline: false,
818 selected: false,
819 });
820
821 describe("terminalLinkAtPositionWithRange", () => {
822 it.each([
823 { text: "https://example.com/日本", cols: 80, end: { x: 23, y: 0 } },
824 { text: "src/日本/main.ts:3:1", cols: 80, end: { x: 19, y: 0 } },
825 { text: "https://example.com/🙂", cols: 80, end: { x: 21, y: 0 } },
826 { text: "https://example.com/日本", cols: 23, end: { x: 1, y: 1 } },
827 ])("keeps every cell of $text clickable at $cols columns", async ({ text, cols, end }) => {
828 const core = await GhosttyTerminalCore.create(
829 cols,
830 3,
831 8,
832 16,
833 {
834 foreground: { r: 255, g: 255, b: 255 },
835 background: { r: 0, g: 0, b: 0 },
836 cursor: { r: 255, g: 255, b: 255 },
837 },
838 () => {},
839 );
840 try {
841 core.write(text + " next");
842 const rows = core.snapshot().rowData;
843 for (let y = 0; y <= end.y; y += 1) {
844 const lastColumn = y === end.y ? end.x : cols - 2;
845 for (let x = 0; x <= lastColumn; x += 1) {
846 expect(terminalLinkAtPositionWithRange(rows, y, x)).toEqual({
847 text,
848 range: { start: { x: 0, y: 0 }, end },
849 });
850 }
851 }
852 expect(terminalLinkAtPositionWithRange(rows, end.y, end.x + 1)).toBeNull();
853 } finally {
854 core.dispose();
855 }
856 });
857
858 it("activates a wrapped quoted Windows path from its spaces and position suffix", () => {
859 const row = (text: string, isWrapContinuation: boolean): GhosttyRow => ({
860 cells: Array.from(text, (character) => cell(character)),
861 text,
862 isWrapContinuation,
863 wrapsToNext: false,
864 });
865 const first = String.raw`"C:\Users\Jane `;
866 const second = String.raw`Doe\index.ts":12:7`;
867 const rows = [row(first, false), row(second, true)];
868 const expected = {
869 text: String.raw`C:\Users\Jane Doe\index.ts:12:7`,
870 range: { start: { x: 1, y: 0 }, end: { x: second.length - 1, y: 1 } },
871 };
872 expect(terminalLinkAtPositionWithRange(rows, 0, first.length - 1)).toEqual(expected);
873 expect(terminalLinkAtPositionWithRange(rows, 1, second.length - 1)).toEqual(expected);
874 expect(terminalLinkAtPositionWithRange(rows, 0, 0)).toBeNull();
875 });
876
877 it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
878 const cells = [
879 cell("🙂"),
880 cell(""),
881 ...Array.from("https://t3.codes", (character) => cell(character)),
882 ];
883 const row: GhosttyRow = {
884 cells,
885 text: cells
886 .map((value) => value.text || " ")
887 .join("")
888 .trimEnd(),
889 isWrapContinuation: false,
890 wrapsToNext: false,
891 };
892
893 expect(terminalLinkAtPositionWithRange([row], 0, 2)?.text).toBe("https://t3.codes");
894 expect(terminalLinkAtPositionWithRange([row], 0, cells.length - 1)?.text).toBe(
895 "https://t3.codes",
896 );
897 expect(terminalLinkAtPositionWithRange([row], 0, 0)).toBeNull();
898 expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
899 start: { x: 2, y: 0 },
900 end: { x: cells.length - 1, y: 0 },
901 });
902 });
903
904 it("uses shared path matching and reconstructs soft-wrapped links", () => {
905 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
906 cells: Array.from(text.padEnd(16), (character) => cell(character)),
907 text: text.trimEnd(),
908 isWrapContinuation,
909 wrapsToNext,
910 });
911 const rows = [
912 row("https://example.", false),
913 row("com/reference", true),
914 row("~/project/file", false),
915 row("C:\\repo\\file.ts", false),
916 row("PS C:\\repo\\dir 1", false, true),
917 row("\\test> ", true),
918 ];
919
920 expect(terminalLinkAtPositionWithRange(rows, 0, 8)?.text).toBe("https://example.com/reference");
921 expect(terminalLinkAtPositionWithRange(rows, 1, 4)?.text).toBe("https://example.com/reference");
922 expect(terminalLinkAtPositionWithRange(rows, 2, 2)?.text).toBe("~/project/file");
923 expect(terminalLinkAtPositionWithRange(rows, 3, 4)?.text).toBe("C:\\repo\\file.ts");
924 expect(terminalLinkAtPositionWithRange(rows, 4, 13)).toEqual({
925 text: "C:\\repo\\dir 1\\test",
926 range: { start: { x: 3, y: 4 }, end: { x: 4, y: 5 } },
927 });
928 expect(terminalLinkAtPositionWithRange(rows, 5, 2)?.text).toBe("C:\\repo\\dir 1\\test");
929 expect(terminalLinkAtPositionWithRange(rows, 5, 5)).toBeNull();
930 expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
931 text: "https://example.com/reference",
932 range: {
933 start: { x: 0, y: 0 },
934 end: { x: 12, y: 1 },
935 },
936 });
937 });
938
939 it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
940 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
941 cells: Array.from(text.padEnd(16), (character) => cell(character)),
942 text: text.trimEnd(),
943 isWrapContinuation,
944 wrapsToNext,
945 });
946 const headCut = [row("ple.com/missing", true), row("head", true)];
947 expect(terminalLinkAtPositionWithRange(headCut, 0, 4)).toBeNull();
948 const tailCut = [row("https://t3.codes", false, true)];
949 expect(terminalLinkAtPositionWithRange(tailCut, 0, 8)).toBeNull();
950 const complete = [row("https://t3.codes", false), row("", false)];
951 expect(terminalLinkAtPositionWithRange(complete, 0, 8)?.text).toBe("https://t3.codes");
952 const wideFull: GhosttyRow = {
953 cells: [
954 { ...cell("🙂"), wide: 1 },
955 { ...cell(""), wide: 2 },
956 ...Array.from("https://t3.code", (character) => cell(character)),
957 ],
958 text: "🙂 https://t3.code",
959 isWrapContinuation: false,
960 wrapsToNext: true,
961 };
962 expect(terminalLinkAtPositionWithRange([wideFull], 0, 8)).toBeNull();
963 const unwrittenTail: GhosttyRow = {
964 cells: [
965 ...Array.from("https://t3.codes", (character) => cell(character)),
966 cell(""),
967 cell(""),
968 ],
969 text: "https://t3.codes",
970 isWrapContinuation: false,
971 wrapsToNext: false,
972 };
973 expect(terminalLinkAtPositionWithRange([unwrittenTail], 0, 8)?.text).toBe("https://t3.codes");
974 });
975 });
976
977 describe("isTerminalCopyShortcut", () => {
978 const event = (overrides: Partial<Parameters<typeof isTerminalCopyShortcut>[0]> = {}) => ({
979 altKey: false,
980 code: "KeyC",
981 ctrlKey: false,
982 key: "c",
983 metaKey: false,
984 shiftKey: false,
985 ...overrides,
986 });
987
988 it("keeps Ctrl+C available for SIGINT on macOS", () => {
989 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
990 expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
991 });
992
993 it("uses the produced character instead of the physical key position", () => {
994 expect(isTerminalCopyShortcut(event({ key: "C", metaKey: true }), "MacIntel")).toBe(true);
995 expect(isTerminalCopyShortcut(event({ key: "j", metaKey: true }), "MacIntel")).toBe(false);
996 });
997 });
998
999 describe("applyTerminalCopyEvent", () => {
1000 // regression: #7678 copying a terminal selection produced a blank clipboard
1001 it("leaves the writeText fallback alive when clipboardData is missing", () => {
1002 // Electron menu Copy often omits clipboardData.
1003 expect(applyTerminalCopyEvent("ls -la", null)).toEqual({
1004 preventDefault: false,
1005 claimWriteFallback: false,
1006 });
1007 expect(applyTerminalCopyEvent("", { setData: vi.fn() })).toEqual({
1008 preventDefault: false,
1009 claimWriteFallback: false,
1010 });
1011 });
1012
1013 it("primes the current selection before a copy event with no clipboardData", () => {
1014 const input = {
1015 value: "stale",
1016 selectionStart: 0,
1017 selectionEnd: 0,
1018 select() {
1019 this.selectionStart = 0;
1020 this.selectionEnd = this.value.length;
1021 },
1022 };
1023 primeTerminalCopyInput(input, "git status");
1024 expect(applyTerminalCopyEvent("git status", null)).toEqual({
1025 preventDefault: false,
1026 claimWriteFallback: false,
1027 });
1028 expect(input.value).toBe("git status");
1029 expect(input.selectionStart).toBe(0);
1030 expect(input.selectionEnd).toBe(10);
1031 });
1032 });
1033
1034 describe("primeTerminalCopyInput", () => {
1035 it("does not wipe an IME candidate that replaced the primed copy", () => {
1036 const input = { value: "", select() {} };
1037 primeTerminalCopyInput(input, "git status");
1038 input.value = "あ";
1039 clearPrimedTerminalCopyInput(input, "git status");
1040 expect(input.value).toBe("あ");
1041 });
1042 });
1043
1044 describe("isTerminalCompositionKey", () => {
1045 const event = (
1046 overrides: Partial<Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">> = {},
1047 ) => ({
1048 isComposing: false,
1049 key: "a",
1050 keyCode: 65,
1051 ...overrides,
1052 });
1053
1054 it("treats in-progress IME keydowns as composition so the copy primer cannot wipe them", () => {
1055 expect(isTerminalCompositionKey(event({ isComposing: true }), false)).toBe(true);
1056 expect(isTerminalCompositionKey(event(), true)).toBe(true);
1057 expect(isTerminalCompositionKey(event({ key: "Process" }), false)).toBe(true);
1058 expect(isTerminalCompositionKey(event({ keyCode: 229 }), false)).toBe(true);
1059 });
1060 });
1061
1062 describe("application mouse reporting", () => {
1063 it("drops repeated motion reports until another mouse action resets the cell", () => {
1064 const data = "\u001b[<35;8;4M";
1065 const report = { data, binary: false };
1066 const first = resolveTerminalMouseData("motion", report, null);
1067 expect(first).toEqual({ send: true, nextMotionData: report });
1068
1069 const duplicate = resolveTerminalMouseData("motion", report, first.nextMotionData);
1070 expect(duplicate).toEqual({ send: false, nextMotionData: report });
1071
1072 const press = resolveTerminalMouseData("press", report, duplicate.nextMotionData);
1073 expect(press).toEqual({ send: true, nextMotionData: null });
1074 expect(resolveTerminalMouseData("motion", report, press.nextMotionData).send).toBe(true);
1075
1076 const legacy = { data: "\x1b[M@\x80$", binary: true };
1077 const utf8 = { ...legacy, binary: false };
1078 const legacyMotion = resolveTerminalMouseData("motion", legacy, null);
1079 const utf8Motion = resolveTerminalMouseData("motion", utf8, legacyMotion.nextMotionData);
1080 expect(utf8Motion.send).toBe(true);
1081 expect(resolveTerminalMouseData("motion", legacy, utf8Motion.nextMotionData).send).toBe(true);
1082 });
1083 });
1084
1085 describe("terminalContentOriginY", () => {
1086 it("keeps the prompt stationary while a drag crosses row boundaries", () => {
1087 for (let height = 88; height < 104; height += 1) {
1088 const rows = Math.max(1, Math.floor((height - 8) / 16));
1089 const origin = terminalContentOriginY(height, 4, rows, 16, true);
1090 expect(origin + rows * 16).toBe(height - 4);
1091 }
1092 });
1093 });
1094
1095 describe("terminalWheelDeltaRows", () => {
1096 it("accumulates fractional pixel deltas across events", () => {
1097 let remainder = 0;
1098 let scrolled = 0;
1099 for (let index = 0; index < 4; index += 1) {
1100 const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
1101 remainder = result.remainder;
1102 scrolled += result.rows;
1103 }
1104 expect(scrolled).toBe(1);
1105 expect(remainder).toBeCloseTo(4 / 16);
1106 });
1107 });
1108
1109 // regression: #19492 drag selection scrolled one row per tick however far past the edge
1110 describe("terminalSelectionAutoscrollRows", () => {
1111 it("scrolls more rows per tick the farther the pointer is past an edge", () => {
1112 const top = 100;
1113 const bottom = 500;
1114 expect(terminalSelectionAutoscrollRows(300, top, bottom)).toBe(0);
1115 expect(terminalSelectionAutoscrollRows(99, top, bottom)).toBe(-1);
1116 expect(terminalSelectionAutoscrollRows(75, top, bottom)).toBe(-8);
1117 expect(terminalSelectionAutoscrollRows(501, top, bottom)).toBe(1);
1118 expect(terminalSelectionAutoscrollRows(525, top, bottom)).toBe(8);
1119 expect(terminalSelectionAutoscrollRows(550, top, bottom)).toBe(15);
1120 expect(terminalSelectionAutoscrollRows(2_000, top, bottom)).toBe(15);
1121 });
1122 });
1123
1124 describe("advanceTerminalSelectionClickSequence", () => {
1125 it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
1126 const first = advanceTerminalSelectionClickSequence(null, {
1127 clientX: 20,
1128 clientY: 30,
1129 timeStamp: 1_000,
1130 });
1131 const second = advanceTerminalSelectionClickSequence(first, {
1132 clientX: 22,
1133 clientY: 29,
1134 timeStamp: 1_200,
1135 });
1136 const third = advanceTerminalSelectionClickSequence(second, {
1137 clientX: 21,
1138 clientY: 31,
1139 timeStamp: 1_400,
1140 });
1141
1142 expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
1143 });
1144 });