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

snapShot.test.ts

760 lines22.7 KB

1import { it as effectIt } from "@effect/vitest";
2import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
3import * as Effect from "effect/Effect";
4import { describe, expect, it, vi } from "vite-plus/test";
5​
6import {
7 accessibleWindowElementTree,
8 accessibleWindowText,
9 capturedImageBounds,
10 compactAccessibilityTree,
11 findAccessibleWindow,
12 findCaptureSource,
13 hideAndWaitForBlur,
14 isWaylandSession,
15 snapShotShortcutRegistrationFailureMessage,
16 snapShotShortcutSystemConflict,
17 toElectronAccelerator,
18} from "./snapShot.ts";
19import { DesktopSnapShotError } from "./DesktopSnapShot.ts";
20​
21describe("window capture errors", () => {
22 it.each([
23 ["unsupported", "SnapShots are not supported here."],
24 ["disabled", "Enable SnapShots in Settings first."],
25 ["no-window-selected", "No window was selected."],
26 ["window-unavailable", "The active window is not available for capture."],
27 ["capture", "Could not capture the active window."],
28 ] as const)("keeps %s failures user-facing", (operation, message) => {
29 expect(new DesktopSnapShotError({ operation }).message).toBe(message);
30 });
31});
32​
33describe("accessibleWindowText", () => {
34 it("keeps unique names and values in tree order", () => {
35 expect(
36 accessibleWindowText(
37 {
38 name: "Settings",
39 children: [
40 {
41 name: "General",
42 children: [],
43 },
44 {
45 name: "Name",
46 value: "Bilal",
47 children: [],
48 },
49 ],
50 },
51 100,
52 ),
53 ).toBe("Settings\nGeneral\nName\nBilal");
54 });
55​
56 it("caps large text without splitting a surrogate pair", () => {
57 expect(
58 accessibleWindowText(
59 {
60 value: "abc😀def",
61 children: [],
62 },
63 5,
64 ),
65 ).toBe("abc😀");
66 });
67​
68 it("stops traversing very large trees", () => {
69 expect(
70 accessibleWindowText(
71 {
72 children: [
73 ...Array.from({ length: 10_000 }, () => ({ children: [] })),
74 { value: "past node limit", children: [] },
75 ],
76 },
77 100,
78 ),
79 ).not.toContain("past node limit");
80 });
81});
82​
83describe("accessibleWindowElementTree", () => {
84 it("maps element bounds into captured-image pixels and keeps semantic state", async () => {
85 const tree = await accessibleWindowElementTree(
86 {
87 role: "window",
88 name: "Editor",
89 bounds: { x: 100, y: 200, width: 800, height: 600 },
90 active: true,
91 children: async () => [
92 {
93 role: "button",
94 name: "Save",
95 description: "Save the document",
96 bounds: { x: 300, y: 350, width: 100, height: 50 },
97 focused: true,
98 actions: ["press", "press"],
99 children: async () => [],
100 },
101 ],
102 },
103 { x: 100, y: 200, width: 800, height: 600 },
104 { width: 1_600, height: 1_200 },
105 );
106​
107 expect(tree).toEqual({
108 truncated: false,
109 root: {
110 role: "window",
111 name: "Editor",
112 bounds: { x: 0, y: 0, width: 1_600, height: 1_200 },
113 state: { active: true },
114 children: [
115 {
116 role: "button",
117 name: "Save",
118 description: "Save the document",
119 bounds: { x: 400, y: 300, width: 200, height: 100 },
120 state: { focused: true },
121 actions: ["press"],
122 children: [],
123 },
124 ],
125 },
126 });
127 });
128​
129 it("uses null child bounds when a Wayland provider reports only the root origin", async () => {
130 const tree = await accessibleWindowElementTree(
131 {
132 role: "window",
133 bounds: { x: 0, y: 0, width: 800, height: 600 },
134 children: async () => [
135 {
136 role: "button",
137 name: "Save",
138 bounds: { x: 0, y: 0, width: 100, height: 50 },
139 children: async () => [],
140 },
141 ],
142 },
143 { x: 0, y: 0, width: 800, height: 600 },
144 { width: 1_600, height: 1_200 },
145 { locationsReliable: true, verifyDescendantLocations: true },
146 );
147​
148 expect(tree?.root.bounds).toEqual({ x: 0, y: 0, width: 1_600, height: 1_200 });
149 expect(tree?.root.children[0]?.bounds).toBeNull();
150 });
151​
152 it("keeps Wayland child bounds after observing real position variation", async () => {
153 const tree = await accessibleWindowElementTree(
154 {
155 role: "window",
156 bounds: { x: 0, y: 0, width: 800, height: 600 },
157 children: async () => [
158 {
159 role: "button",
160 name: "Save",
161 bounds: { x: 20, y: 30, width: 100, height: 50 },
162 children: async () => [],
163 },
164 ],
165 },
166 { x: 0, y: 0, width: 800, height: 600 },
167 { width: 1_600, height: 1_200 },
168 { locationsReliable: true, verifyDescendantLocations: true },
169 );
170​
171 expect(tree?.root.children[0]?.bounds).toEqual({ x: 40, y: 60, width: 200, height: 100 });
172 });
173​
174 it("does not mistake a title-bar offset for varying descendant positions", async () => {
175 const tree = await accessibleWindowElementTree(
176 {
177 role: "window",
178 bounds: { x: 100, y: 229, width: 800, height: 571 },
179 children: async () => [
180 {
181 role: "button",
182 name: "Save",
183 bounds: { x: 100, y: 229, width: 100, height: 50 },
184 children: async () => [],
185 },
186 ],
187 },
188 { x: 100, y: 200, width: 800, height: 600 },
189 { width: 1_600, height: 1_200 },
190 { locationsReliable: true, verifyDescendantLocations: true },
191 );
192 expect(tree?.root.children[0]?.bounds).toBeNull();
193 });
194​
195 it("collapses anonymous wrapper chains and removes duplicate text fields", async () => {
196 const tree = await accessibleWindowElementTree(
197 {
198 role: "window",
199 name: "Editor",
200 bounds: { x: 0, y: 0, width: 800, height: 600 },
201 children: async () => [
202 {
203 role: "group",
204 bounds: { x: 0, y: 0, width: 800, height: 600 },
205 children: async () => [
206 {
207 role: "group",
208 bounds: { x: 0, y: 0, width: 800, height: 600 },
209 children: async () => [
210 {
211 role: "button",
212 name: "Save",
213 value: "Save",
214 description: "Save",
215 bounds: { x: 20, y: 30, width: 80, height: 24 },
216 actions: ["press"],
217 children: async () => [],
218 },
219 {
220 role: "group",
221 bounds: null,
222 children: async () => [],
223 },
224 ],
225 },
226 ],
227 },
228 ],
229 },
230 { x: 0, y: 0, width: 800, height: 600 },
231 { width: 800, height: 600 },
232 );
233​
234 expect(tree?.root.children).toEqual([
235 {
236 role: "button",
237 name: "Save",
238 bounds: { x: 20, y: 30, width: 80, height: 24 },
239 actions: ["press"],
240 children: [],
241 },
242 ]);
243 });
244​
245 it("marks trees truncated before their serialized payload grows without bound", async () => {
246 const tree = await accessibleWindowElementTree(
247 {
248 role: "window",
249 bounds: { x: 0, y: 0, width: 800, height: 600 },
250 children: async () =>
251 Array.from({ length: 10 }, (_, index) => ({
252 role: "text",
253 value: `${index}${"x".repeat(8_000)}`,
254 bounds: null,
255 children: async () => [],
256 })),
257 },
258 { x: 0, y: 0, width: 800, height: 600 },
259 { width: 800, height: 600 },
260 );
261​
262 expect(tree?.truncated).toBe(true);
263 expect(tree?.root.children.length).toBeLessThan(10);
264 expect(JSON.stringify(tree).length).toBeLessThanOrEqual(32_000);
265 });
266});
267​
268describe("compactAccessibilityTree", () => {
269 it("keeps anonymous groups that organize multiple semantic children", () => {
270 const compacted = compactAccessibilityTree({
271 role: "window",
272 bounds: { x: 0, y: 0, width: 800, height: 600 },
273 children: [
274 {
275 role: "group",
276 bounds: { x: 0, y: 0, width: 800, height: 100 },
277 children: [
278 { role: "button", name: "Back", bounds: null, children: [] },
279 { role: "button", name: "Forward", bounds: null, children: [] },
280 ],
281 },
282 ],
283 });
284​
285 expect(compacted.root.children[0]?.role).toBe("group");
286 expect(compacted.root.children[0]?.children).toHaveLength(2);
287 });
288});
289​
290describe("capturedImageBounds", () => {
291 it("clips locations to the attached image", () => {
292 expect(
293 capturedImageBounds(
294 { x: 50, y: 150, width: 200, height: 200 },
295 { x: 100, y: 200, width: 800, height: 600 },
296 { width: 1_600, height: 1_200 },
297 ),
298 ).toEqual({ x: 0, y: 0, width: 300, height: 300 });
299 });
300​
301 it("returns null when an accessibility provider omits a location", () => {
302 expect(
303 capturedImageBounds(
304 null,
305 { x: 0, y: 0, width: 800, height: 600 },
306 { width: 800, height: 600 },
307 ),
308 ).toBeNull();
309 });
310});
311​
312describe("findAccessibleWindow", () => {
313 const captured = {
314 title: "Editor",
315 bounds: { x: 100, y: 200, width: 800, height: 600 },
316 };
317​
318 it("matches one window by its captured bounds", () => {
319 const windows = [
320 { name: "Private", bounds: { x: 0, y: 0, width: 400, height: 300 } },
321 { name: "Editor", bounds: { x: 101, y: 199, width: 800, height: 601 } },
322 ];
323​
324 expect(findAccessibleWindow(windows, captured)).toBe(windows[1]);
325 });
326​
327 it("uses the matched source title when macOS omits the active title", () => {
328 const windows = [{ name: "Editor", bounds: captured.bounds }];
329 expect(
330 findAccessibleWindow(windows, {
331 ...captured,
332 title: "",
333 sourceTitle: "Editor",
334 }),
335 ).toBe(windows[0]);
336 });
337​
338 it("uses the captured source title when the active title changed", () => {
339 const windows = [{ name: "Editor — saved", bounds: captured.bounds }];
340​
341 expect(
342 findAccessibleWindow(windows, {
343 ...captured,
344 title: "Editor — saving",
345 sourceTitle: "Editor — saved",
346 }),
347 ).toBe(windows[0]);
348 });
349​
350 it("uses the active match to disambiguate equal windows", () => {
351 const windows = [
352 { name: "Editor", bounds: captured.bounds, active: false },
353 { name: "Editor", bounds: captured.bounds, active: true },
354 ];
355​
356 expect(findAccessibleWindow(windows, captured)).toBe(windows[1]);
357 });
358​
359 it("does not match equal bounds with a different title", () => {
360 expect(
361 findAccessibleWindow(
362 [{ name: "Private", bounds: { x: 100, y: 200, width: 800, height: 600 } }],
363 captured,
364 ),
365 ).toBeUndefined();
366 });
367​
368 it("does not use a title match when the bounds differ", () => {
369 expect(
370 findAccessibleWindow(
371 [{ name: "Editor", bounds: { x: 0, y: 0, width: 800, height: 600 } }],
372 captured,
373 ),
374 ).toBeUndefined();
375 });
376​
377 it("matches a Wayland window whose accessibility provider omits its screen position", () => {
378 const captured = {
379 title: "hello world (Draft) - Text Editor",
380 bounds: { x: 479, y: 342, width: 700, height: 520 },
381 };
382 const windows = [{ name: captured.title, bounds: { x: 0, y: 0, width: 700, height: 520 } }];
383​
384 expect(findAccessibleWindow(windows, captured, "wayland")).toBe(windows[0]);
385 expect(findAccessibleWindow(windows, captured)).toBeUndefined();
386 });
387​
388 it("matches a decorated Wayland window by its verified client size", () => {
389 const clientBounds = { x: 100, y: 229, width: 800, height: 571 };
390 const windows = [{ name: captured.title, bounds: { ...clientBounds, x: 0, y: 0 } }];
391 expect(findAccessibleWindow(windows, { ...captured, clientBounds }, "wayland")).toBe(
392 windows[0],
393 );
394 expect(findAccessibleWindow(windows, { ...captured, clientBounds })).toBeUndefined();
395 expect(findAccessibleWindow(windows, captured, "wayland")).toBeUndefined();
396 });
397​
398 it("does not guess between client-size and frame-size matches", () => {
399 const clientBounds = { x: 100, y: 229, width: 800, height: 571 };
400 const windows = [
401 { name: captured.title, bounds: clientBounds },
402 { name: captured.title, bounds: captured.bounds },
403 ];
404 expect(findAccessibleWindow(windows, { ...captured, clientBounds }, "wayland")).toBeUndefined();
405 expect(
406 findAccessibleWindow(
407 [
408 { name: "Private", bounds: clientBounds },
409 { name: captured.title, bounds: { ...clientBounds, height: 550 } },
410 ],
411 { ...captured, clientBounds },
412 "wayland",
413 ),
414 ).toBeUndefined();
415 });
416​
417 it("distinguishes same-title Wayland windows by size", () => {
418 const windows = [
419 { name: "Editor", bounds: { x: 0, y: 0, width: 400, height: 300 } },
420 { name: "Editor", bounds: { x: 0, y: 0, width: 801, height: 599 } },
421 ];
422​
423 expect(findAccessibleWindow(windows, captured, "wayland")).toBe(windows[1]);
424 });
425​
426 it.each([
427 { name: "Private", bounds: { x: 0, y: 0, width: 800, height: 600 } },
428 { name: "Editor", bounds: { x: 0, y: 0, width: 400, height: 600 } },
429 { name: "Editor", bounds: { x: 0, y: 0, width: 800, height: 300 } },
430 { name: "Editor", bounds: null },
431 ])("rejects an unverified Wayland window: %j", (window) => {
432 expect(findAccessibleWindow([window], captured, "wayland")).toBeUndefined();
433 });
434​
435 it("rejects ambiguous Wayland windows even when one reports the captured screen position", () => {
436 const windows = [
437 { name: "Editor", bounds: captured.bounds },
438 { name: "Editor", bounds: { x: 0, y: 0, width: 800, height: 600 } },
439 ];
440​
441 expect(findAccessibleWindow(windows, captured, "wayland")).toBeUndefined();
442 });
443​
444 it("does not match an untitled Wayland window by size alone", () => {
445 const windows = [{ name: "", bounds: captured.bounds }];
446​
447 expect(findAccessibleWindow(windows, { ...captured, title: "" }, "wayland")).toBeUndefined();
448 });
449​
450 it.each(["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"])(
451 "ignores a leading Wayland title spinner frame %s",
452 (frame) => {
453 const windows = [{ name: `${frame} t3code`, bounds: captured.bounds }];
454​
455 expect(findAccessibleWindow(windows, { ...captured, title: "⠋ t3code" }, "wayland")).toBe(
456 windows[0],
457 );
458 },
459 );
460​
461 it.each([
462 ["⠋ t3code", "t3code"],
463 ["t3code", "⠙ t3code"],
464 ])("matches a Wayland spinner starting or stopping: %s → %s", (title, name) => {
465 const windows = [{ name, bounds: captured.bounds }];
466​
467 expect(findAccessibleWindow(windows, { ...captured, title }, "wayland")).toBe(windows[0]);
468 });
469​
470 it.each([
471 ["⠋ t3code", "⠙ private"],
472 ["t3code ⠋", "t3code ⠙"],
473 ["⠋t3code", "⠙t3code"],
474 ["⠁ t3code", "⠙ t3code"],
475 ["⠋", "⠋"],
476 ])("does not guess a Wayland title match: %s → %s", (title, name) => {
477 expect(
478 findAccessibleWindow([{ name, bounds: captured.bounds }], { ...captured, title }, "wayland"),
479 ).toBeUndefined();
480 });
481​
482 it("rejects matching spinners when the window sizes differ", () => {
483 expect(
484 findAccessibleWindow(
485 [{ name: "⠙ t3code", bounds: { ...captured.bounds, width: 400 } }],
486 { ...captured, title: "⠋ t3code" },
487 "wayland",
488 ),
489 ).toBeUndefined();
490 });
491​
492 it("rejects ambiguous normalized titles even if one matches the captured spinner exactly", () => {
493 const windows = [
494 { name: "⠋ t3code", bounds: captured.bounds },
495 { name: "⠙ t3code", bounds: captured.bounds },
496 ];
497​
498 expect(
499 findAccessibleWindow(windows, { ...captured, title: "⠋ t3code" }, "wayland"),
500 ).toBeUndefined();
501 });
502​
503 it("keeps exact title matching outside Wayland", () => {
504 expect(
505 findAccessibleWindow([{ name: "⠙ t3code", bounds: captured.bounds }], {
506 ...captured,
507 title: "⠋ t3code",
508 }),
509 ).toBeUndefined();
510 });
511});
512​
513describe("hideAndWaitForBlur", () => {
514 it("waits for a delayed blur after hiding the window", async () => {
515 let blur: (() => void) | undefined;
516 let settled = false;
517 const hidden = hideAndWaitForBlur({
518 hide: () => undefined,
519 once: (_event, listener) => {
520 blur = listener;
521 },
522 removeListener: () => undefined,
523 }).then(() => {
524 settled = true;
525 });
526​
527 await Promise.resolve();
528 expect(settled).toBe(false);
529 blur?.();
530 await hidden;
531 expect(settled).toBe(true);
532 });
533​
534 it("rejects when the hidden window never blurs", async () => {
535 vi.useFakeTimers();
536 try {
537 let rejected = false;
538 const hidden = hideAndWaitForBlur({
539 hide: () => undefined,
540 once: () => undefined,
541 removeListener: () => undefined,
542 }).catch(() => {
543 rejected = true;
544 });
545​
546 await vi.advanceTimersByTimeAsync(1_000);
547 expect(rejected).toBe(true);
548 await hidden;
549 } finally {
550 vi.useRealTimers();
551 }
552 });
553});
554​
555describe("toElectronAccelerator", () => {
556 it("converts the default portable shortcut", () => {
557 expect(
558 toElectronAccelerator({
559 key: "2",
560 metaKey: false,
561 ctrlKey: false,
562 shiftKey: true,
563 altKey: false,
564 modKey: true,
565 }),
566 ).toBe("CommandOrControl+Shift+2");
567 });
568​
569 it("maps the portable meta key to Super", () => {
570 expect(
571 toElectronAccelerator({
572 key: "k",
573 metaKey: true,
574 ctrlKey: false,
575 shiftKey: false,
576 altKey: false,
577 modKey: false,
578 }),
579 ).toBe("Super+K");
580 });
581​
582 it("normalizes Electron key names", () => {
583 expect(
584 toElectronAccelerator({
585 key: "ArrowUp",
586 metaKey: false,
587 ctrlKey: true,
588 shiftKey: false,
589 altKey: true,
590 modKey: false,
591 }),
592 ).toBe("Control+Alt+Up");
593 });
594});
595​
596describe("findCaptureSource", () => {
597 const sources = [
598 { id: "window:42:0", name: "Terminal" },
599 { id: "window:84:0", name: "Editor" },
600 ];
601​
602 it("matches the native window id before its title", () => {
603 expect(
604 findCaptureSource(sources, {
605 id: 84,
606 title: "Changed title",
607 }),
608 ).toEqual(sources[1]);
609 });
610​
611 it("falls back to a unique title match", () => {
612 expect(
613 findCaptureSource(sources, {
614 id: 100,
615 title: "Terminal",
616 }),
617 ).toEqual(sources[0]);
618 });
619​
620 it("does not guess when a title is ambiguous", () => {
621 expect(
622 findCaptureSource(
623 [
624 { id: "window:42:0", name: "Editor" },
625 { id: "window:84:0", name: "Editor" },
626 ],
627 {
628 id: 100,
629 title: "Editor",
630 },
631 ),
632 ).toBeUndefined();
633 });
634});
635​
636describe("isWaylandSession", () => {
637 it.each([
638 ["linux", { XDG_SESSION_TYPE: "wayland" }, true],
639 ["linux", { WAYLAND_DISPLAY: "wayland-0" }, true],
640 ["linux", { XDG_SESSION_TYPE: "x11" }, false],
641 ["darwin", { XDG_SESSION_TYPE: "wayland", WAYLAND_DISPLAY: "wayland-0" }, false],
642 ] as const)("detects %s session %o as portal=%s", (platform, environment, expected) => {
643 expect(isWaylandSession(platform, environment)).toBe(expected);
644 });
645​
646 effectIt.effect(
647 "falls back to a live runtime directory socket when session variables are stripped",
648 () =>
649 Effect.gen(function* () {
650 if ((yield* HostProcessPlatform) !== "linux") return;
651 yield* Effect.promise(async () => {
652 const { mkdtemp, rm, writeFile } = await import("node:fs/promises");
653 const { createServer } = await import("node:net");
654 const { tmpdir } = await import("node:os");
655 const { join } = await import("node:path");
656 const runtimeDirectory = await mkdtemp(join(tmpdir(), "t3-wayland-"));
657 const socketPath = join(runtimeDirectory, "wayland-0");
658 const server = createServer();
659 try {
660 expect(isWaylandSession("linux", { XDG_RUNTIME_DIR: runtimeDirectory })).toBe(false);
661 await writeFile(socketPath, "");
662 expect(isWaylandSession("linux", { XDG_RUNTIME_DIR: runtimeDirectory })).toBe(false);
663 await rm(socketPath);
664 await new Promise<void>((resolve, reject) => {
665 server.once("error", reject);
666 server.listen(socketPath, resolve);
667 });
668 expect(isWaylandSession("linux", { XDG_RUNTIME_DIR: runtimeDirectory })).toBe(true);
669 expect(
670 isWaylandSession("linux", {
671 XDG_RUNTIME_DIR: runtimeDirectory,
672 XDG_SESSION_TYPE: "x11",
673 }),
674 ).toBe(false);
675 expect(isWaylandSession("linux", { XDG_RUNTIME_DIR: "/nonexistent-t3-test" })).toBe(
676 false,
677 );
678 } finally {
679 if (server.listening) {
680 await new Promise<void>((resolve, reject) => {
681 server.close((error) => (error ? reject(error) : resolve()));
682 });
683 }
684 await rm(runtimeDirectory, { recursive: true, force: true });
685 }
686 });
687 }),
688 );
689});
690​
691describe("snapShotShortcutRegistrationFailureMessage", () => {
692 it("distinguishes a modifier listener failure from a reserved key chord", () => {
693 expect(
694 snapShotShortcutRegistrationFailureMessage({ kind: "both-shift-keys" }, "darwin"),
695 ).toMatch(/Shift \+ Shift is not available/);
696 expect(
697 snapShotShortcutRegistrationFailureMessage(
698 { kind: "modifier-pair", modifier: "meta" },
699 "darwin",
700 ),
701 ).toMatch(/Command \+ Command is not available/);
702 expect(
703 snapShotShortcutRegistrationFailureMessage(
704 { kind: "modifier-pair", modifier: "meta" },
705 "linux",
706 ),
707 ).toMatch(/Super \+ Super is not available/);
708 expect(
709 snapShotShortcutRegistrationFailureMessage(
710 {
711 key: "2",
712 metaKey: false,
713 ctrlKey: false,
714 shiftKey: true,
715 altKey: false,
716 modKey: true,
717 },
718 "darwin",
719 ),
720 ).toMatch(/already used/);
721 });
722});
723​
724describe("snapShotShortcutSystemConflict", () => {
725 it("blocks shortcuts that would break typing or common app actions", () => {
726 expect(
727 snapShotShortcutSystemConflict({
728 key: "s",
729 metaKey: false,
730 ctrlKey: false,
731 shiftKey: true,
732 altKey: false,
733 modKey: false,
734 }),
735 ).toMatch(/typing/);
736 expect(
737 snapShotShortcutSystemConflict({
738 key: "c",
739 metaKey: false,
740 ctrlKey: false,
741 shiftKey: false,
742 altKey: false,
743 modKey: true,
744 }),
745 ).toMatch(/Copy/);
746 });
747​
748 it("allows a specific multi-modifier shortcut", () => {
749 expect(
750 snapShotShortcutSystemConflict({
751 key: "2",
752 metaKey: false,
753 ctrlKey: false,
754 shiftKey: true,
755 altKey: false,
756 modKey: true,
757 }),
758 ).toBeNull();
759 });
760});