Open History to see the last commit
1import { it as effectIt } from "@effect/vitest";
2import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as FileSystem from "effect/FileSystem";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Schema from "effect/Schema";
13import type * as Scope from "effect/Scope";
14import { TestClock } from "effect/testing";
15import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
16
17import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
18import * as ElectronWindow from "../electron/ElectronWindow.ts";
19import * as BrowserSession from "./BrowserSession.ts";
20import * as PreviewManager from "./Manager.ts";
21
22const {
23 createFromPath,
24 fromId,
25 getFocusedWebContents,
26 mkdir,
27 showItemInFolder,
28 webviewSend,
29 writeFile,
30 writeImage,
31} = vi.hoisted(() => ({
32 createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
33 fromId: vi.fn(() => null),
34 getFocusedWebContents: vi.fn(() => null),
35 mkdir: vi.fn((_path: string) => undefined),
36 showItemInFolder: vi.fn(),
37 webviewSend: vi.fn(),
38 writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
39 writeImage: vi.fn(),
40}));
41
42vi.mock("electron", () => ({
43 clipboard: {
44 writeImage,
45 },
46 nativeImage: {
47 createFromPath,
48 },
49 shell: {
50 showItemInFolder,
51 },
52 session: {
53 fromPartition: vi.fn(),
54 },
55 webContents: {
56 fromId,
57 getFocusedWebContents,
58 },
59}));
60
61const browserSessionLayer = Layer.succeed(
62 BrowserSession.BrowserSession,
63 BrowserSession.BrowserSession.of({
64 getPartition: () => Effect.succeed("persist:t3code-preview-test"),
65 isPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
66 getSession: () => Effect.die("unexpected getSession"),
67 clearCookies: () => Effect.void,
68 clearCache: () => Effect.void,
69 }),
70);
71
72const environmentLayer = Layer.succeed(
73 DesktopEnvironment.DesktopEnvironment,
74 DesktopEnvironment.DesktopEnvironment.of({
75 browserArtifactsDir: "/tmp/t3/dev/browser-artifacts",
76 } as DesktopEnvironment.DesktopEnvironment["Service"]),
77);
78
79const fileSystemLayer = FileSystem.layerNoop({
80 makeDirectory: (path) =>
81 Effect.sync(() => {
82 mkdir(path);
83 }),
84 writeFile: (path, data) =>
85 Effect.sync(() => {
86 writeFile(path, data);
87 }),
88});
89
90const layer = PreviewManager.layer.pipe(
91 Layer.provideMerge(browserSessionLayer),
92 Layer.provideMerge(environmentLayer),
93 Layer.provideMerge(fileSystemLayer),
94 Layer.provideMerge(Path.layer),
95 Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
96);
97const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
98
99const withManager = <A>(
100 use: (
101 manager: PreviewManager.PreviewManager["Service"],
102 ) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>,
103) =>
104 Effect.gen(function* () {
105 const manager = yield* PreviewManager.PreviewManager;
106 return yield* use(manager);
107 }).pipe(Effect.provide(layer), Effect.scoped);
108
109describe("PreviewManager", () => {
110 beforeEach(() => {
111 fromId.mockClear();
112 getFocusedWebContents.mockReset();
113 getFocusedWebContents.mockReturnValue(null);
114 mkdir.mockClear();
115 writeFile.mockClear();
116 showItemInFolder.mockClear();
117 writeImage.mockClear();
118 createFromPath.mockClear();
119 webviewSend.mockClear();
120 });
121
122 effectIt.effect("reports an unregistered webview as temporarily unavailable", () =>
123 withManager((manager) =>
124 Effect.gen(function* () {
125 expect(yield* manager.automationStatus("tab_1")).toEqual({
126 available: false,
127 visible: true,
128 tabId: "tab_1",
129 url: null,
130 title: null,
131 loading: false,
132 });
133
134 yield* manager.createTab("tab_1");
135
136 expect(yield* manager.automationStatus("tab_1")).toEqual({
137 available: false,
138 visible: true,
139 tabId: "tab_1",
140 url: null,
141 title: null,
142 loading: false,
143 });
144 expect(fromId).not.toHaveBeenCalled();
145 }),
146 ),
147 );
148
149 effectIt.effect("isolates failed state listeners and continues delivery", () => {
150 const loggedErrors: Array<unknown> = [];
151 const logger = Logger.make(({ message }) => {
152 for (const value of Array.isArray(message) ? message : [message]) {
153 if (typeof value === "object" && value !== null && "cause" in value) {
154 loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
155 }
156 }
157 });
158 const deliveryError = new ElectronWindow.ElectronWindowOperationError({
159 operation: "send-window-message",
160 platform: "darwin",
161 windowId: 42,
162 channel: "preview:state-change",
163 cause: new Error("renderer unavailable"),
164 });
165 const delivered = vi.fn();
166
167 return withManager((manager) =>
168 Effect.gen(function* () {
169 yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
170 yield* manager.subscribeStateChanges((tabId, state) =>
171 Effect.sync(() => {
172 delivered(tabId, state);
173 }),
174 );
175
176 const state = yield* manager.createTab("tab_listener_failure");
177
178 expect(delivered).toHaveBeenCalledOnce();
179 expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
180 expect(loggedErrors).toHaveLength(1);
181 expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
182 expect(loggedErrors[0]).toMatchObject({
183 operation: "send-window-message",
184 windowId: 42,
185 channel: "preview:state-change",
186 });
187 }),
188 ).pipe(
189 Effect.provide(
190 Logger.layer([logger], {
191 mergeWithExisting: false,
192 }),
193 ),
194 );
195 });
196
197 effectIt.effect("does not swallow state listener interruption", () =>
198 withManager((manager) =>
199 Effect.gen(function* () {
200 const exit = yield* Effect.scoped(
201 Effect.gen(function* () {
202 yield* manager.subscribeStateChanges(() => Effect.interrupt);
203 return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
204 }),
205 );
206
207 expect(Exit.isFailure(exit)).toBe(true);
208 if (Exit.isFailure(exit)) {
209 expect(Cause.hasInterrupts(exit.cause)).toBe(true);
210 }
211 }),
212 ),
213 );
214
215 effectIt.effect("queues navigation until the webview registers", () =>
216 withManager((manager) =>
217 Effect.gen(function* () {
218 const loadURL = vi.fn(async () => undefined);
219 const listeners = new Map<string, (...args: never[]) => void>();
220 fromId.mockReturnValue({
221 id: 42,
222 isDestroyed: () => false,
223 getType: () => "webview",
224 getURL: () => "about:blank",
225 getTitle: () => "",
226 isLoading: () => false,
227 getZoomFactor: () => 1,
228 setZoomFactor: vi.fn(),
229 loadURL,
230 on: vi.fn((event: string, listener: (...args: never[]) => void) => {
231 listeners.set(event, listener);
232 }),
233 off: vi.fn(),
234 ipc: { on: vi.fn(), off: vi.fn() },
235 send: webviewSend,
236 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
237 setWindowOpenHandler: vi.fn(),
238 debugger: {
239 isAttached: () => false,
240 attach: vi.fn(),
241 sendCommand: vi.fn(async () => undefined),
242 on: vi.fn(),
243 off: vi.fn(),
244 },
245 } as never);
246
247 yield* manager.navigate("tab_pending", "localhost:3200");
248
249 expect(yield* manager.automationStatus("tab_pending")).toEqual({
250 available: false,
251 visible: true,
252 tabId: "tab_pending",
253 url: "http://localhost:3200/",
254 title: "",
255 loading: true,
256 });
257
258 yield* manager.registerWebview("tab_pending", 42);
259 yield* Effect.yieldNow;
260
261 expect(loadURL).toHaveBeenCalledOnce();
262 expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
263 }),
264 ),
265 );
266
267 effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
268 withManager((manager) =>
269 Effect.gen(function* () {
270 let effectiveZoom = 0.9;
271 let zoomReadable = true;
272 let url = "https://example.com";
273 const listeners = new Map<string, (...args: unknown[]) => void>();
274 const setZoomFactor = vi.fn();
275 fromId.mockReturnValue({
276 id: 42,
277 isDestroyed: () => false,
278 getType: () => "webview",
279 getURL: () => url,
280 getTitle: () => "Example",
281 isLoading: () => false,
282 getZoomFactor: () => {
283 if (!zoomReadable) throw new Error("zoom unavailable");
284 return effectiveZoom;
285 },
286 setZoomFactor,
287 on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
288 listeners.set(event, listener);
289 }),
290 off: vi.fn(),
291 ipc: { on: vi.fn(), off: vi.fn() },
292 send: webviewSend,
293 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
294 setWindowOpenHandler: vi.fn(),
295 debugger: {
296 isAttached: () => false,
297 attach: vi.fn(),
298 sendCommand: vi.fn(async () => undefined),
299 on: vi.fn(),
300 off: vi.fn(),
301 },
302 } as never);
303 const states: PreviewManager.PreviewTabState[] = [];
304
305 yield* manager.subscribeStateChanges((_tabId, state) =>
306 Effect.sync(() => {
307 states.push(state);
308 }),
309 );
310 yield* manager.createTab("tab_zoom");
311 yield* manager.registerWebview("tab_zoom", 42);
312
313 expect(states.at(-1)?.zoomFactor).toBe(0.9);
314 expect(setZoomFactor).not.toHaveBeenCalled();
315
316 effectiveZoom = 1.25;
317 listeners.get("did-navigate")?.();
318 yield* Effect.yieldNow;
319
320 expect(states.at(-1)?.zoomFactor).toBe(1.25);
321 expect(setZoomFactor).not.toHaveBeenCalled();
322
323 zoomReadable = false;
324 url = "https://example.com/after-zoom-read-failed";
325 listeners.get("did-navigate")?.();
326 yield* Effect.yieldNow;
327
328 expect(states.at(-1)?.navStatus).toEqual({
329 kind: "Success",
330 url,
331 title: "Example",
332 });
333 expect(states.at(-1)?.zoomFactor).toBe(1.25);
334
335 const replacementSetZoomFactor = vi.fn();
336 fromId.mockReturnValue({
337 id: 43,
338 isDestroyed: () => false,
339 getType: () => "webview",
340 getURL: () => url,
341 getTitle: () => "Example",
342 isLoading: () => false,
343 getZoomFactor: () => 1,
344 setZoomFactor: replacementSetZoomFactor,
345 on: vi.fn(),
346 off: vi.fn(),
347 ipc: { on: vi.fn(), off: vi.fn() },
348 send: webviewSend,
349 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
350 setWindowOpenHandler: vi.fn(),
351 debugger: {
352 isAttached: () => false,
353 attach: vi.fn(),
354 sendCommand: vi.fn(async () => undefined),
355 on: vi.fn(),
356 off: vi.fn(),
357 },
358 } as never);
359
360 yield* manager.registerWebview("tab_zoom", 43);
361
362 expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
363 expect(states.at(-1)?.zoomFactor).toBe(1.25);
364 }),
365 ),
366 );
367
368 effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
369 withManager((manager) =>
370 Effect.gen(function* () {
371 const url = "http://localhost:5733/";
372 let loading = false;
373 const listeners = new Map<string, (...args: unknown[]) => void>();
374 fromId.mockReturnValue({
375 id: 42,
376 isDestroyed: () => false,
377 getType: () => "webview",
378 getURL: () => url,
379 getTitle: () => "localhost:5733",
380 isLoading: () => loading,
381 getZoomFactor: () => 1,
382 setZoomFactor: vi.fn(),
383 on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
384 listeners.set(event, listener);
385 }),
386 off: vi.fn(),
387 ipc: { on: vi.fn(), off: vi.fn() },
388 send: webviewSend,
389 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
390 setWindowOpenHandler: vi.fn(),
391 debugger: {
392 isAttached: () => false,
393 attach: vi.fn(),
394 sendCommand: vi.fn(async () => undefined),
395 on: vi.fn(),
396 off: vi.fn(),
397 },
398 } as never);
399 const statuses: PreviewManager.PreviewNavStatus[] = [];
400
401 yield* manager.subscribeStateChanges((_tabId, state) =>
402 Effect.sync(() => {
403 statuses.push(state.navStatus);
404 }),
405 );
406 yield* manager.createTab("tab_failed");
407 yield* manager.registerWebview("tab_failed", 42);
408
409 listeners.get("did-fail-load")?.(
410 {},
411 -105,
412 "ERR_NAME_NOT_RESOLVED",
413 "https://missing-frame.example/",
414 false,
415 );
416 yield* Effect.yieldNow;
417 expect(statuses.at(-1)?.kind).toBe("Success");
418
419 loading = true;
420 listeners.get("did-start-loading")?.();
421 yield* Effect.yieldNow;
422 expect(statuses.at(-1)?.kind).toBe("Loading");
423
424 loading = false;
425 listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
426 listeners.get("did-stop-loading")?.();
427 listeners.get("page-title-updated")?.();
428 yield* Effect.yieldNow;
429 expect(statuses.at(-1)).toEqual({
430 kind: "LoadFailed",
431 url,
432 title: "localhost:5733",
433 code: -102,
434 description: "ERR_CONNECTION_REFUSED",
435 });
436
437 loading = true;
438 listeners.get("did-start-loading")?.();
439 yield* Effect.yieldNow;
440 expect(statuses.at(-1)?.kind).toBe("Loading");
441
442 loading = false;
443 listeners.get("did-stop-loading")?.();
444 yield* Effect.yieldNow;
445 expect(statuses.at(-1)?.kind).toBe("Success");
446
447 listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
448 yield* Effect.yieldNow;
449 expect(statuses.at(-1)?.kind).toBe("LoadFailed");
450
451 listeners.get("did-navigate")?.();
452 yield* Effect.yieldNow;
453 expect(statuses.at(-1)?.kind).toBe("Success");
454 }),
455 ),
456 );
457
458 effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
459 withManager((manager) =>
460 Effect.gen(function* () {
461 const png = Buffer.from("preview-png");
462 const capturePage = vi.fn(async () => ({ toPNG: () => png }));
463 const listeners = new Map<string, (...args: never[]) => void>();
464 fromId.mockReturnValue({
465 id: 42,
466 isDestroyed: () => false,
467 getType: () => "webview",
468 getURL: () => "https://example.com:8443/path?query=value",
469 getTitle: () => "Example",
470 isLoading: () => false,
471 getZoomFactor: () => 1,
472 setZoomFactor: vi.fn(),
473 on: vi.fn((event: string, listener: (...args: never[]) => void) => {
474 listeners.set(event, listener);
475 }),
476 off: vi.fn(),
477 ipc: { on: vi.fn(), off: vi.fn() },
478 send: webviewSend,
479 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
480 setWindowOpenHandler: vi.fn(),
481 debugger: {
482 isAttached: () => false,
483 attach: vi.fn(),
484 sendCommand: vi.fn(async () => undefined),
485 on: vi.fn(),
486 off: vi.fn(),
487 },
488 capturePage,
489 } as never);
490
491 yield* manager.createTab("tab_1");
492 yield* manager.registerWebview("tab_1", 42);
493
494 expect(webviewSend).toHaveBeenCalledWith(
495 "preview:annotation-theme",
496 expect.objectContaining({
497 colorScheme: "light",
498 primary: "oklch(0.488 0.217 264)",
499 }),
500 );
501
502 const artifact = yield* manager.captureScreenshot("tab_1");
503
504 expect(capturePage).toHaveBeenCalledOnce();
505 expect(mkdir).toHaveBeenCalledWith("/tmp/t3/dev/browser-artifacts");
506 expect(writeFile).toHaveBeenCalledWith(artifact.path, png);
507 expect(artifact).toMatchObject({
508 tabId: "tab_1",
509 mimeType: "image/png",
510 sizeBytes: png.byteLength,
511 });
512 expect(artifact.path).toMatch(
513 /\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
514 );
515
516 const captureCause = new Error("capture failed");
517 capturePage.mockRejectedValueOnce(captureCause);
518 const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
519 expect(Exit.isFailure(exit)).toBe(true);
520 if (Exit.isSuccess(exit)) return;
521 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
522 expect(error).toMatchObject({
523 _tag: "PreviewOperationError",
524 operation: "captureScreenshot.capturePage",
525 tabId: "tab_1",
526 webContentsId: 42,
527 cause: captureCause,
528 });
529 }),
530 ),
531 );
532
533 effectIt.effect("keeps element picking active during subframe navigation", () =>
534 withManager((manager) =>
535 Effect.gen(function* () {
536 const listeners = new Map<string, (...args: unknown[]) => void>();
537 fromId.mockReturnValue({
538 id: 42,
539 isDestroyed: () => false,
540 getType: () => "webview",
541 getURL: () => "https://example.com",
542 getTitle: () => "Example",
543 isLoading: () => false,
544 isFocused: () => true,
545 getZoomFactor: () => 1,
546 setZoomFactor: vi.fn(),
547 on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
548 listeners.set(event, listener);
549 }),
550 once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
551 listeners.set(event, listener);
552 }),
553 off: vi.fn(),
554 ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() },
555 send: webviewSend,
556 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
557 setWindowOpenHandler: vi.fn(),
558 debugger: {
559 isAttached: () => false,
560 attach: vi.fn(),
561 sendCommand: vi.fn(async () => undefined),
562 on: vi.fn(),
563 off: vi.fn(),
564 },
565 } as never);
566
567 yield* manager.createTab("tab_1");
568 yield* manager.registerWebview("tab_1", 42);
569 const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
570 yield* Effect.yieldNow;
571
572 listeners.get("did-start-navigation")?.({}, "about:blank", false, false);
573 yield* Effect.yieldNow;
574 expect(pick.pollUnsafe()).toBeUndefined();
575
576 listeners.get("did-start-navigation")?.({}, "https://example.com/next", false, true);
577 expect(yield* Fiber.join(pick)).toBeNull();
578 }),
579 ),
580 );
581
582 effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
583 withManager((manager) =>
584 Effect.gen(function* () {
585 yield* manager.revealArtifact("/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png");
586
587 expect(showItemInFolder).toHaveBeenCalledWith(
588 "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png",
589 );
590 const exit = yield* Effect.exit(manager.revealArtifact("/tmp/t3/dev/settings.json"));
591 expect(Exit.isFailure(exit)).toBe(true);
592 if (Exit.isSuccess(exit)) return;
593 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
594 expect(error).toMatchObject({
595 _tag: "PreviewArtifactPathOutsideDirectoryError",
596 artifactPath: "/tmp/t3/dev/settings.json",
597 artifactDirectory: "/tmp/t3/dev/browser-artifacts",
598 });
599 expect("cause" in error).toBe(false);
600 }),
601 ),
602 );
603
604 effectIt.effect("copies screenshot artifacts to the system clipboard", () =>
605 withManager((manager) =>
606 Effect.gen(function* () {
607 const artifactPath = "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png";
608
609 yield* manager.copyArtifactToClipboard(artifactPath);
610
611 expect(createFromPath).toHaveBeenCalledWith(artifactPath);
612 expect(writeImage).toHaveBeenCalledOnce();
613 const exit = yield* Effect.exit(
614 manager.copyArtifactToClipboard("/tmp/t3/dev/settings.json"),
615 );
616 expect(Exit.isFailure(exit)).toBe(true);
617 if (Exit.isSuccess(exit)) return;
618 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
619 expect(error).toMatchObject({
620 _tag: "PreviewArtifactPathOutsideDirectoryError",
621 artifactPath: "/tmp/t3/dev/settings.json",
622 artifactDirectory: "/tmp/t3/dev/browser-artifacts",
623 });
624 expect("cause" in error).toBe(false);
625
626 createFromPath.mockReturnValueOnce({ isEmpty: () => true });
627 const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
628 expect(Exit.isFailure(invalidImageExit)).toBe(true);
629 if (Exit.isSuccess(invalidImageExit)) return;
630 expect(Option.getOrThrow(Cause.findErrorOption(invalidImageExit.cause))).toMatchObject({
631 _tag: "PreviewArtifactImageLoadError",
632 artifactPath,
633 });
634 }),
635 ),
636 );
637
638 effectIt.effect("emits the resolved pointer target before dispatching an automation click", () =>
639 withManager((manager) =>
640 Effect.gen(function* () {
641 let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
642 const activity: string[] = [];
643 const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
644 if (method === "Runtime.evaluate") {
645 return {
646 result: {
647 value: { width: 800, height: 600 },
648 },
649 };
650 }
651 if (method === "Input.dispatchMouseEvent" && params?.type === "mousePressed") {
652 activity.push("mousePressed");
653 humanInput?.({}, { kind: "pointer", x: params.x, y: params.y, button: 0 });
654 }
655 return undefined;
656 });
657 fromId.mockReturnValue({
658 id: 42,
659 isDestroyed: () => false,
660 getType: () => "webview",
661 getURL: () => "https://example.com",
662 getTitle: () => "Example",
663 isLoading: () => false,
664 isDevToolsOpened: () => false,
665 getZoomFactor: () => 1,
666 setZoomFactor: vi.fn(),
667 on: vi.fn(),
668 off: vi.fn(),
669 ipc: {
670 on: vi.fn((channel: string, listener: typeof humanInput) => {
671 if (channel === "preview:human-input") humanInput = listener;
672 }),
673 off: vi.fn(),
674 },
675 send: webviewSend,
676 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
677 setWindowOpenHandler: vi.fn(),
678 debugger: {
679 isAttached: () => false,
680 attach: vi.fn(),
681 sendCommand,
682 on: vi.fn(),
683 off: vi.fn(),
684 },
685 } as never);
686
687 yield* manager.subscribePointerEvents((event) =>
688 Effect.sync(() => {
689 activity.push(event.phase);
690 }),
691 );
692 yield* manager.createTab("tab_1");
693 yield* manager.registerWebview("tab_1", 42);
694 const click = yield* manager
695 .automationClick("tab_1", { x: 120, y: 80 })
696 .pipe(Effect.forkChild({ startImmediately: true }));
697 yield* TestClock.adjust(200);
698 yield* Fiber.join(click);
699
700 expect(activity).toEqual(["move", "click", "mousePressed"]);
701 expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
702 type: "mousePressed",
703 x: 120,
704 y: 80,
705 button: "left",
706 clickCount: 1,
707 });
708 expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
709 type: "mouseReleased",
710 x: 120,
711 y: 80,
712 button: "left",
713 clickCount: 1,
714 });
715 }),
716 ),
717 );
718
719 effectIt.effect("types in background webviews and enables native key input", () =>
720 withManager((manager) =>
721 Effect.gen(function* () {
722 let failKeyDown = false;
723 let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
724 const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
725 if (
726 failKeyDown &&
727 method === "Input.dispatchKeyEvent" &&
728 (params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
729 ) {
730 throw new Error("key dispatch failed");
731 }
732 if (
733 method === "Input.dispatchKeyEvent" &&
734 (params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
735 ) {
736 humanInput?.(
737 {},
738 {
739 kind: "key",
740 key: params["key"],
741 code: params["code"] ?? "Digit1",
742 },
743 );
744 }
745 return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
746 });
747 const restoreFocus = vi.fn();
748 const focus = vi.fn();
749 getFocusedWebContents.mockReturnValue({
750 id: 7,
751 isDestroyed: () => false,
752 focus: restoreFocus,
753 } as never);
754 fromId.mockReturnValue({
755 id: 42,
756 isDestroyed: () => false,
757 getType: () => "webview",
758 getURL: () => "https://example.com",
759 getTitle: () => "Example",
760 isLoading: () => false,
761 isDevToolsOpened: () => false,
762 focus,
763 getZoomFactor: () => 1,
764 setZoomFactor: vi.fn(),
765 on: vi.fn(),
766 off: vi.fn(),
767 ipc: {
768 on: vi.fn((channel: string, listener: typeof humanInput) => {
769 if (channel === "preview:human-input") humanInput = listener;
770 }),
771 off: vi.fn(),
772 },
773 send: webviewSend,
774 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
775 setWindowOpenHandler: vi.fn(),
776 debugger: {
777 isAttached: () => false,
778 attach: vi.fn(),
779 sendCommand,
780 on: vi.fn(),
781 off: vi.fn(),
782 },
783 } as never);
784
785 yield* manager.createTab("tab_input");
786 yield* manager.registerWebview("tab_input", 42);
787 yield* manager.automationType("tab_input", { text: "hello", clear: true });
788 yield* manager.automationType("tab_input", { text: "", clear: true });
789 yield* manager.automationPress("tab_input", { key: "x" });
790
791 const calls = sendCommand.mock.calls;
792 const methods = calls.map(([method]) => method);
793 const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
794 const focusOnIndex = calls.findIndex(
795 ([method, params]) =>
796 method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
797 );
798 const keyDownIndex = calls.findIndex(
799 ([method, params]) =>
800 method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
801 );
802 const keyUpIndex = calls.findIndex(
803 ([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
804 );
805 const focusOffIndex = calls.findIndex(
806 ([method, params]) =>
807 method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
808 );
809 const typeEvaluation = sendCommand.mock.calls.find(
810 ([method, params]) =>
811 method === "Runtime.evaluate" &&
812 typeof params === "object" &&
813 params !== null &&
814 "expression" in params &&
815 typeof params.expression === "string" &&
816 params.expression.includes('document.execCommand("insertText"'),
817 );
818 expect(typeEvaluation).toBeDefined();
819 const clearOnlyEvaluation = sendCommand.mock.calls.find(
820 ([method, params]) =>
821 method === "Runtime.evaluate" &&
822 typeof params === "object" &&
823 params !== null &&
824 "expression" in params &&
825 typeof params.expression === "string" &&
826 params.expression.includes('const text = ""') &&
827 params.expression.includes("Object.getOwnPropertyDescriptor"),
828 );
829 expect(clearOnlyEvaluation).toBeDefined();
830 expect(methods).not.toContain("Input.insertText");
831 expect(enableIndex).toBeGreaterThanOrEqual(0);
832 expect(focus).toHaveBeenCalledOnce();
833 expect(restoreFocus).toHaveBeenCalledOnce();
834 expect(methods).toContain("Page.bringToFront");
835 expect(enableIndex).toBeLessThan(focusOnIndex);
836 expect(focusOnIndex).toBeLessThan(keyDownIndex);
837 expect(keyDownIndex).toBeLessThan(keyUpIndex);
838 expect(keyUpIndex).toBeLessThan(focusOffIndex);
839 expect(
840 calls.filter(
841 ([method, params]) =>
842 method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
843 ),
844 ).toHaveLength(1);
845 expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
846
847 sendCommand.mockClear();
848 failKeyDown = true;
849 const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
850
851 expect(Exit.isFailure(failedPress)).toBe(true);
852 expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
853 type: "keyUp",
854 key: "y",
855 code: "KeyY",
856 modifiers: 0,
857 windowsVirtualKeyCode: 89,
858 location: 0,
859 isKeypad: false,
860 });
861 expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
862 enabled: false,
863 });
864 expect(restoreFocus).toHaveBeenCalledTimes(2);
865 expect(
866 sendCommand.mock.calls.filter(
867 ([method, params]) =>
868 method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
869 ),
870 ).toHaveLength(1);
871
872 sendCommand.mockClear();
873 failKeyDown = false;
874 yield* manager.automationPress("tab_input", { key: "!" });
875 expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
876 type: "keyDown",
877 key: "!",
878 code: "Digit1",
879 modifiers: 0,
880 windowsVirtualKeyCode: 49,
881 location: 0,
882 isKeypad: false,
883 text: "!",
884 unmodifiedText: "!",
885 });
886 expect(restoreFocus).toHaveBeenCalledTimes(3);
887 }),
888 ),
889 );
890
891 effectIt.effect("still interrupts agent control for a different human pointer event", () =>
892 withManager((manager) =>
893 Effect.gen(function* () {
894 let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
895 const sendCommand = vi.fn(async (method: string) => {
896 if (method === "Runtime.evaluate") {
897 return {
898 result: {
899 value: { width: 800, height: 600 },
900 },
901 };
902 }
903 if (method === "Input.dispatchMouseEvent") {
904 humanInput?.({}, { kind: "pointer", x: 400, y: 300, button: 0 });
905 }
906 return undefined;
907 });
908 fromId.mockReturnValue({
909 id: 42,
910 isDestroyed: () => false,
911 getType: () => "webview",
912 getURL: () => "https://example.com",
913 getTitle: () => "Example",
914 isLoading: () => false,
915 isDevToolsOpened: () => false,
916 getZoomFactor: () => 1,
917 setZoomFactor: vi.fn(),
918 on: vi.fn(),
919 off: vi.fn(),
920 ipc: {
921 on: vi.fn((channel: string, listener: typeof humanInput) => {
922 if (channel === "preview:human-input") humanInput = listener;
923 }),
924 off: vi.fn(),
925 },
926 send: webviewSend,
927 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
928 setWindowOpenHandler: vi.fn(),
929 debugger: {
930 isAttached: () => false,
931 attach: vi.fn(),
932 sendCommand,
933 on: vi.fn(),
934 off: vi.fn(),
935 },
936 } as never);
937
938 yield* manager.createTab("tab_1");
939 yield* manager.registerWebview("tab_1", 42);
940
941 const click = yield* manager
942 .automationClick("tab_1", { x: 120, y: 80 })
943 .pipe(Effect.forkChild({ startImmediately: true }));
944 yield* TestClock.adjust(200);
945 const exit = yield* Fiber.await(click);
946 expect(Exit.isFailure(exit)).toBe(true);
947 if (Exit.isSuccess(exit)) return;
948 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
949 expect(error).toMatchObject({
950 _tag: "PreviewAutomationControlInterruptedError",
951 operation: "click",
952 tabId: "tab_1",
953 webContentsId: 42,
954 });
955 expect(error).toBeInstanceOf(Error);
956 if (error instanceof Error) {
957 expect(error.name).toBe("PreviewAutomationControlInterruptedError");
958 }
959 expect("cause" in error).toBe(false);
960 }),
961 ),
962 );
963
964 effectIt.effect("derives evaluation detail kind and length from the same non-empty source", () =>
965 withManager((manager) =>
966 Effect.gen(function* () {
967 const text = "ReferenceError: fallbackDetail is not defined";
968 const exceptionDetails = {
969 text,
970 exception: { description: "" },
971 };
972 const sendCommand = vi.fn(async (method: string) =>
973 method === "Runtime.evaluate" ? { exceptionDetails } : undefined,
974 );
975 fromId.mockReturnValue({
976 id: 42,
977 isDestroyed: () => false,
978 getType: () => "webview",
979 getURL: () => "https://example.com",
980 getTitle: () => "Example",
981 isLoading: () => false,
982 isDevToolsOpened: () => false,
983 getZoomFactor: () => 1,
984 setZoomFactor: vi.fn(),
985 on: vi.fn(),
986 off: vi.fn(),
987 ipc: { on: vi.fn(), off: vi.fn() },
988 send: webviewSend,
989 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
990 setWindowOpenHandler: vi.fn(),
991 debugger: {
992 isAttached: () => false,
993 attach: vi.fn(),
994 sendCommand,
995 on: vi.fn(),
996 off: vi.fn(),
997 },
998 } as never);
999
1000 yield* manager.createTab("tab_1");
1001 yield* manager.registerWebview("tab_1", 42);
1002 const exit = yield* Effect.exit(
1003 manager.automationEvaluate("tab_1", { expression: "fallbackDetail" }),
1004 );
1005
1006 expect(Exit.isFailure(exit)).toBe(true);
1007 if (Exit.isSuccess(exit)) return;
1008 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
1009 expect(error).toMatchObject({
1010 _tag: "PreviewAutomationEvaluationError",
1011 detailKind: "exception-text",
1012 detailLength: text.length,
1013 cause: exceptionDetails,
1014 });
1015 }),
1016 ),
1017 );
1018});
1019
1020describe("PreviewOperationError", () => {
1021 it("keeps timeline detail separate from its structured message", () => {
1022 const cause = new Error("CDP command failed with an invalid node id");
1023 const error = new PreviewManager.PreviewOperationError({
1024 operation: "click.DOM.resolveNode",
1025 tabId: "tab_1",
1026 webContentsId: 42,
1027 cause,
1028 });
1029
1030 expect(error.message).not.toContain(cause.message);
1031 expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message);
1032 });
1033});
1034
1035describe("Preview automation diagnostics", () => {
1036 it("keeps browser exception detail out of structural diagnostics", () => {
1037 const secret = "unrelated-browser-payload-secret";
1038 const detail = "ReferenceError: missingValue is not defined";
1039 const cause = {
1040 text: "Uncaught Error",
1041 exception: { description: detail },
1042 unsafePayload: secret,
1043 };
1044 const error = new PreviewManager.PreviewAutomationEvaluationError({
1045 tabId: "tab_1",
1046 detailKind: "exception-description",
1047 detailLength: detail.length,
1048 cause,
1049 });
1050
1051 const encoded = encodePreviewManagerError(error);
1052 const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
1053 readonly cause?: unknown;
1054 };
1055
1056 expect(error.cause).toBe(cause);
1057 expect(encodedCause).toStrictEqual(cause);
1058 expect(error.message).toBe("Preview JavaScript evaluation failed in tab tab_1");
1059 expect(error.message).not.toContain(secret);
1060 expect(JSON.stringify(encodedDiagnostics)).not.toContain(secret);
1061 expect("detail" in error).toBe(false);
1062 expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).toBe(detail);
1063 expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).not.toContain(
1064 secret,
1065 );
1066 });
1067
1068 it("retains bounded selector diagnostics without exposing selector or reason text", () => {
1069 const selector = "role=button[name='selector-secret']";
1070 const reason = "Unexpected token near reason-secret";
1071 const cause = { invalidSelector: true as const, message: reason };
1072 const error = new PreviewManager.PreviewAutomationInvalidSelectorError({
1073 operation: "click",
1074 tabId: "tab_1",
1075 selectorKind: "locator",
1076 selectorLength: selector.length,
1077 reasonLength: reason.length,
1078 cause,
1079 });
1080
1081 const encoded = encodePreviewManagerError(error);
1082 const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
1083 readonly cause?: unknown;
1084 };
1085
1086 expect(error.cause).toBe(cause);
1087 expect(encodedCause).toStrictEqual(cause);
1088 expect(error).toMatchObject({
1089 selectorKind: "locator",
1090 selectorLength: selector.length,
1091 reasonLength: reason.length,
1092 });
1093 expect(error.detail).toEqual({
1094 selectorKind: "locator",
1095 selectorLength: selector.length,
1096 });
1097 expect(error.message).not.toContain("secret");
1098 expect(JSON.stringify(encodedDiagnostics)).not.toContain("secret");
1099 expect("selector" in error).toBe(false);
1100 expect("reason" in error).toBe(false);
1101 expect(PreviewManager.PreviewAutomationInvalidSelectorError.toTimelineMessage(error)).toBe(
1102 reason,
1103 );
1104 });
1105
1106 it("does not retain a missing target locator", () => {
1107 const selector = "[data-token='target-secret']";
1108 const error = new PreviewManager.PreviewAutomationTargetNotFoundError({
1109 operation: "scroll",
1110 tabId: "tab_1",
1111 selectorKind: "selector",
1112 selectorLength: selector.length,
1113 });
1114
1115 expect(error.message).not.toContain(selector);
1116 expect(JSON.stringify(error)).not.toContain(selector);
1117 expect("locator" in error).toBe(false);
1118 });
1119});