Open History to see the last commit
1import { it as effectIt } from "@effect/vitest";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as FileSystem from "effect/FileSystem";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
8import * as Logger from "effect/Logger";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import type * as Scope from "effect/Scope";
13import { TestClock } from "effect/testing";
14import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
15
16import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
17import * as ElectronWindow from "../electron/ElectronWindow.ts";
18import * as BrowserSession from "./BrowserSession.ts";
19import * as PreviewManager from "./Manager.ts";
20
21const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
22 vi.hoisted(() => ({
23 createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
24 fromId: vi.fn(() => null),
25 mkdir: vi.fn((_path: string) => undefined),
26 showItemInFolder: vi.fn(),
27 webviewSend: vi.fn(),
28 writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
29 writeImage: vi.fn(),
30 }));
31
32vi.mock("electron", () => ({
33 clipboard: {
34 writeImage,
35 },
36 nativeImage: {
37 createFromPath,
38 },
39 shell: {
40 showItemInFolder,
41 },
42 session: {
43 fromPartition: vi.fn(),
44 },
45 webContents: {
46 fromId,
47 },
48}));
49
50const browserSessionLayer = Layer.succeed(
51 BrowserSession.BrowserSession,
52 BrowserSession.BrowserSession.of({
53 getPartition: () => Effect.succeed("persist:t3code-preview-test"),
54 isPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
55 getSession: () => Effect.die("unexpected getSession"),
56 clearCookies: () => Effect.void,
57 clearCache: () => Effect.void,
58 }),
59);
60
61const environmentLayer = Layer.succeed(
62 DesktopEnvironment.DesktopEnvironment,
63 DesktopEnvironment.DesktopEnvironment.of({
64 browserArtifactsDir: "/tmp/t3/dev/browser-artifacts",
65 } as DesktopEnvironment.DesktopEnvironment["Service"]),
66);
67
68const fileSystemLayer = FileSystem.layerNoop({
69 makeDirectory: (path) =>
70 Effect.sync(() => {
71 mkdir(path);
72 }),
73 writeFile: (path, data) =>
74 Effect.sync(() => {
75 writeFile(path, data);
76 }),
77});
78
79const layer = PreviewManager.layer.pipe(
80 Layer.provideMerge(browserSessionLayer),
81 Layer.provideMerge(environmentLayer),
82 Layer.provideMerge(fileSystemLayer),
83 Layer.provideMerge(Path.layer),
84);
85const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
86
87const withManager = <A>(
88 use: (
89 manager: PreviewManager.PreviewManager["Service"],
90 ) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>,
91) =>
92 Effect.gen(function* () {
93 const manager = yield* PreviewManager.PreviewManager;
94 return yield* use(manager);
95 }).pipe(Effect.provide(layer), Effect.scoped);
96
97describe("PreviewManager", () => {
98 beforeEach(() => {
99 fromId.mockClear();
100 mkdir.mockClear();
101 writeFile.mockClear();
102 showItemInFolder.mockClear();
103 writeImage.mockClear();
104 createFromPath.mockClear();
105 webviewSend.mockClear();
106 });
107
108 effectIt.effect("reports an unregistered webview as temporarily unavailable", () =>
109 withManager((manager) =>
110 Effect.gen(function* () {
111 expect(yield* manager.automationStatus("tab_1")).toEqual({
112 available: false,
113 visible: true,
114 tabId: "tab_1",
115 url: null,
116 title: null,
117 loading: false,
118 });
119
120 yield* manager.createTab("tab_1");
121
122 expect(yield* manager.automationStatus("tab_1")).toEqual({
123 available: false,
124 visible: true,
125 tabId: "tab_1",
126 url: null,
127 title: null,
128 loading: false,
129 });
130 expect(fromId).not.toHaveBeenCalled();
131 }),
132 ),
133 );
134
135 effectIt.effect("isolates failed state listeners and continues delivery", () => {
136 const loggedErrors: Array<unknown> = [];
137 const logger = Logger.make(({ message }) => {
138 for (const value of Array.isArray(message) ? message : [message]) {
139 if (typeof value === "object" && value !== null && "cause" in value) {
140 loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
141 }
142 }
143 });
144 const deliveryError = new ElectronWindow.ElectronWindowOperationError({
145 operation: "send-window-message",
146 platform: "darwin",
147 windowId: 42,
148 channel: "preview:state-change",
149 cause: new Error("renderer unavailable"),
150 });
151 const delivered = vi.fn();
152
153 return withManager((manager) =>
154 Effect.gen(function* () {
155 yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
156 yield* manager.subscribeStateChanges((tabId, state) =>
157 Effect.sync(() => {
158 delivered(tabId, state);
159 }),
160 );
161
162 const state = yield* manager.createTab("tab_listener_failure");
163
164 expect(delivered).toHaveBeenCalledOnce();
165 expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
166 expect(loggedErrors).toHaveLength(1);
167 expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
168 expect(loggedErrors[0]).toMatchObject({
169 operation: "send-window-message",
170 windowId: 42,
171 channel: "preview:state-change",
172 });
173 }),
174 ).pipe(
175 Effect.provide(
176 Logger.layer([logger], {
177 mergeWithExisting: false,
178 }),
179 ),
180 );
181 });
182
183 effectIt.effect("does not swallow state listener interruption", () =>
184 withManager((manager) =>
185 Effect.gen(function* () {
186 const exit = yield* Effect.scoped(
187 Effect.gen(function* () {
188 yield* manager.subscribeStateChanges(() => Effect.interrupt);
189 return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
190 }),
191 );
192
193 expect(Exit.isFailure(exit)).toBe(true);
194 if (Exit.isFailure(exit)) {
195 expect(Cause.hasInterrupts(exit.cause)).toBe(true);
196 }
197 }),
198 ),
199 );
200
201 effectIt.effect("queues navigation until the webview registers", () =>
202 withManager((manager) =>
203 Effect.gen(function* () {
204 const loadURL = vi.fn(async () => undefined);
205 const listeners = new Map<string, (...args: never[]) => void>();
206 fromId.mockReturnValue({
207 id: 42,
208 isDestroyed: () => false,
209 getType: () => "webview",
210 getURL: () => "about:blank",
211 getTitle: () => "",
212 isLoading: () => false,
213 getZoomFactor: () => 1,
214 setZoomFactor: vi.fn(),
215 loadURL,
216 on: vi.fn((event: string, listener: (...args: never[]) => void) => {
217 listeners.set(event, listener);
218 }),
219 off: vi.fn(),
220 ipc: { on: vi.fn(), off: vi.fn() },
221 send: webviewSend,
222 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
223 setWindowOpenHandler: vi.fn(),
224 debugger: {
225 isAttached: () => false,
226 attach: vi.fn(),
227 sendCommand: vi.fn(async () => undefined),
228 on: vi.fn(),
229 off: vi.fn(),
230 },
231 } as never);
232
233 yield* manager.navigate("tab_pending", "localhost:3200");
234
235 expect(yield* manager.automationStatus("tab_pending")).toEqual({
236 available: false,
237 visible: true,
238 tabId: "tab_pending",
239 url: "http://localhost:3200/",
240 title: "",
241 loading: true,
242 });
243
244 yield* manager.registerWebview("tab_pending", 42);
245 yield* Effect.yieldNow;
246
247 expect(loadURL).toHaveBeenCalledOnce();
248 expect(loadURL).toHaveBeenCalledWith("http://localhost:3200/");
249 }),
250 ),
251 );
252
253 effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
254 withManager((manager) =>
255 Effect.gen(function* () {
256 const png = Buffer.from("preview-png");
257 const capturePage = vi.fn(async () => ({ toPNG: () => png }));
258 const listeners = new Map<string, (...args: never[]) => void>();
259 fromId.mockReturnValue({
260 id: 42,
261 isDestroyed: () => false,
262 getType: () => "webview",
263 getURL: () => "https://example.com:8443/path?query=value",
264 getTitle: () => "Example",
265 isLoading: () => false,
266 getZoomFactor: () => 1,
267 setZoomFactor: vi.fn(),
268 on: vi.fn((event: string, listener: (...args: never[]) => void) => {
269 listeners.set(event, listener);
270 }),
271 off: vi.fn(),
272 ipc: { on: vi.fn(), off: vi.fn() },
273 send: webviewSend,
274 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
275 setWindowOpenHandler: vi.fn(),
276 debugger: {
277 isAttached: () => false,
278 attach: vi.fn(),
279 sendCommand: vi.fn(async () => undefined),
280 on: vi.fn(),
281 off: vi.fn(),
282 },
283 capturePage,
284 } as never);
285
286 yield* manager.createTab("tab_1");
287 yield* manager.registerWebview("tab_1", 42);
288
289 expect(webviewSend).toHaveBeenCalledWith(
290 "preview:annotation-theme",
291 expect.objectContaining({
292 colorScheme: "light",
293 primary: "oklch(0.488 0.217 264)",
294 }),
295 );
296
297 const artifact = yield* manager.captureScreenshot("tab_1");
298
299 expect(capturePage).toHaveBeenCalledOnce();
300 expect(mkdir).toHaveBeenCalledWith("/tmp/t3/dev/browser-artifacts");
301 expect(writeFile).toHaveBeenCalledWith(artifact.path, png);
302 expect(artifact).toMatchObject({
303 tabId: "tab_1",
304 mimeType: "image/png",
305 sizeBytes: png.byteLength,
306 });
307 expect(artifact.path).toMatch(
308 /\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
309 );
310
311 const captureCause = new Error("capture failed");
312 capturePage.mockRejectedValueOnce(captureCause);
313 const exit = yield* Effect.exit(manager.captureScreenshot("tab_1"));
314 expect(Exit.isFailure(exit)).toBe(true);
315 if (Exit.isSuccess(exit)) return;
316 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
317 expect(error).toMatchObject({
318 _tag: "PreviewOperationError",
319 operation: "captureScreenshot.capturePage",
320 tabId: "tab_1",
321 webContentsId: 42,
322 cause: captureCause,
323 });
324 }),
325 ),
326 );
327
328 effectIt.effect("keeps element picking active during subframe navigation", () =>
329 withManager((manager) =>
330 Effect.gen(function* () {
331 const listeners = new Map<string, (...args: unknown[]) => void>();
332 fromId.mockReturnValue({
333 id: 42,
334 isDestroyed: () => false,
335 getType: () => "webview",
336 getURL: () => "https://example.com",
337 getTitle: () => "Example",
338 isLoading: () => false,
339 isFocused: () => true,
340 getZoomFactor: () => 1,
341 setZoomFactor: vi.fn(),
342 on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
343 listeners.set(event, listener);
344 }),
345 once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
346 listeners.set(event, listener);
347 }),
348 off: vi.fn(),
349 ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() },
350 send: webviewSend,
351 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
352 setWindowOpenHandler: vi.fn(),
353 debugger: {
354 isAttached: () => false,
355 attach: vi.fn(),
356 sendCommand: vi.fn(async () => undefined),
357 on: vi.fn(),
358 off: vi.fn(),
359 },
360 } as never);
361
362 yield* manager.createTab("tab_1");
363 yield* manager.registerWebview("tab_1", 42);
364 const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild);
365 yield* Effect.yieldNow;
366
367 listeners.get("did-start-navigation")?.({}, "about:blank", false, false);
368 yield* Effect.yieldNow;
369 expect(pick.pollUnsafe()).toBeUndefined();
370
371 listeners.get("did-start-navigation")?.({}, "https://example.com/next", false, true);
372 expect(yield* Fiber.join(pick)).toBeNull();
373 }),
374 ),
375 );
376
377 effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
378 withManager((manager) =>
379 Effect.gen(function* () {
380 yield* manager.revealArtifact("/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png");
381
382 expect(showItemInFolder).toHaveBeenCalledWith(
383 "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png",
384 );
385 const exit = yield* Effect.exit(manager.revealArtifact("/tmp/t3/dev/settings.json"));
386 expect(Exit.isFailure(exit)).toBe(true);
387 if (Exit.isSuccess(exit)) return;
388 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
389 expect(error).toMatchObject({
390 _tag: "PreviewArtifactPathOutsideDirectoryError",
391 artifactPath: "/tmp/t3/dev/settings.json",
392 artifactDirectory: "/tmp/t3/dev/browser-artifacts",
393 });
394 expect("cause" in error).toBe(false);
395 }),
396 ),
397 );
398
399 effectIt.effect("copies screenshot artifacts to the system clipboard", () =>
400 withManager((manager) =>
401 Effect.gen(function* () {
402 const artifactPath = "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png";
403
404 yield* manager.copyArtifactToClipboard(artifactPath);
405
406 expect(createFromPath).toHaveBeenCalledWith(artifactPath);
407 expect(writeImage).toHaveBeenCalledOnce();
408 const exit = yield* Effect.exit(
409 manager.copyArtifactToClipboard("/tmp/t3/dev/settings.json"),
410 );
411 expect(Exit.isFailure(exit)).toBe(true);
412 if (Exit.isSuccess(exit)) return;
413 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
414 expect(error).toMatchObject({
415 _tag: "PreviewArtifactPathOutsideDirectoryError",
416 artifactPath: "/tmp/t3/dev/settings.json",
417 artifactDirectory: "/tmp/t3/dev/browser-artifacts",
418 });
419 expect("cause" in error).toBe(false);
420
421 createFromPath.mockReturnValueOnce({ isEmpty: () => true });
422 const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath));
423 expect(Exit.isFailure(invalidImageExit)).toBe(true);
424 if (Exit.isSuccess(invalidImageExit)) return;
425 expect(Option.getOrThrow(Cause.findErrorOption(invalidImageExit.cause))).toMatchObject({
426 _tag: "PreviewArtifactImageLoadError",
427 artifactPath,
428 });
429 }),
430 ),
431 );
432
433 effectIt.effect("emits the resolved pointer target before dispatching an automation click", () =>
434 withManager((manager) =>
435 Effect.gen(function* () {
436 let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
437 const activity: string[] = [];
438 const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
439 if (method === "Runtime.evaluate") {
440 return {
441 result: {
442 value: { width: 800, height: 600 },
443 },
444 };
445 }
446 if (method === "Input.dispatchMouseEvent" && params?.type === "mousePressed") {
447 activity.push("mousePressed");
448 humanInput?.({}, { kind: "pointer", x: params.x, y: params.y, button: 0 });
449 }
450 return undefined;
451 });
452 fromId.mockReturnValue({
453 id: 42,
454 isDestroyed: () => false,
455 getType: () => "webview",
456 getURL: () => "https://example.com",
457 getTitle: () => "Example",
458 isLoading: () => false,
459 isDevToolsOpened: () => false,
460 getZoomFactor: () => 1,
461 setZoomFactor: vi.fn(),
462 on: vi.fn(),
463 off: vi.fn(),
464 ipc: {
465 on: vi.fn((channel: string, listener: typeof humanInput) => {
466 if (channel === "preview:human-input") humanInput = listener;
467 }),
468 off: vi.fn(),
469 },
470 send: webviewSend,
471 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
472 setWindowOpenHandler: vi.fn(),
473 debugger: {
474 isAttached: () => false,
475 attach: vi.fn(),
476 sendCommand,
477 on: vi.fn(),
478 off: vi.fn(),
479 },
480 } as never);
481
482 yield* manager.subscribePointerEvents((event) =>
483 Effect.sync(() => {
484 activity.push(event.phase);
485 }),
486 );
487 yield* manager.createTab("tab_1");
488 yield* manager.registerWebview("tab_1", 42);
489 const click = yield* manager
490 .automationClick("tab_1", { x: 120, y: 80 })
491 .pipe(Effect.forkChild({ startImmediately: true }));
492 yield* TestClock.adjust(200);
493 yield* Fiber.join(click);
494
495 expect(activity).toEqual(["move", "click", "mousePressed"]);
496 expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
497 type: "mousePressed",
498 x: 120,
499 y: 80,
500 button: "left",
501 clickCount: 1,
502 });
503 expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
504 type: "mouseReleased",
505 x: 120,
506 y: 80,
507 button: "left",
508 clickCount: 1,
509 });
510 }),
511 ),
512 );
513
514 effectIt.effect("still interrupts agent control for a different human pointer event", () =>
515 withManager((manager) =>
516 Effect.gen(function* () {
517 let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
518 const sendCommand = vi.fn(async (method: string) => {
519 if (method === "Runtime.evaluate") {
520 return {
521 result: {
522 value: { width: 800, height: 600 },
523 },
524 };
525 }
526 if (method === "Input.dispatchMouseEvent") {
527 humanInput?.({}, { kind: "pointer", x: 400, y: 300, button: 0 });
528 }
529 return undefined;
530 });
531 fromId.mockReturnValue({
532 id: 42,
533 isDestroyed: () => false,
534 getType: () => "webview",
535 getURL: () => "https://example.com",
536 getTitle: () => "Example",
537 isLoading: () => false,
538 isDevToolsOpened: () => false,
539 getZoomFactor: () => 1,
540 setZoomFactor: vi.fn(),
541 on: vi.fn(),
542 off: vi.fn(),
543 ipc: {
544 on: vi.fn((channel: string, listener: typeof humanInput) => {
545 if (channel === "preview:human-input") humanInput = listener;
546 }),
547 off: vi.fn(),
548 },
549 send: webviewSend,
550 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
551 setWindowOpenHandler: vi.fn(),
552 debugger: {
553 isAttached: () => false,
554 attach: vi.fn(),
555 sendCommand,
556 on: vi.fn(),
557 off: vi.fn(),
558 },
559 } as never);
560
561 yield* manager.createTab("tab_1");
562 yield* manager.registerWebview("tab_1", 42);
563
564 const click = yield* manager
565 .automationClick("tab_1", { x: 120, y: 80 })
566 .pipe(Effect.forkChild({ startImmediately: true }));
567 yield* TestClock.adjust(200);
568 const exit = yield* Fiber.await(click);
569 expect(Exit.isFailure(exit)).toBe(true);
570 if (Exit.isSuccess(exit)) return;
571 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
572 expect(error).toMatchObject({
573 _tag: "PreviewAutomationControlInterruptedError",
574 operation: "click",
575 tabId: "tab_1",
576 webContentsId: 42,
577 });
578 expect(error).toBeInstanceOf(Error);
579 if (error instanceof Error) {
580 expect(error.name).toBe("PreviewAutomationControlInterruptedError");
581 }
582 expect("cause" in error).toBe(false);
583 }),
584 ),
585 );
586
587 effectIt.effect("derives evaluation detail kind and length from the same non-empty source", () =>
588 withManager((manager) =>
589 Effect.gen(function* () {
590 const text = "ReferenceError: fallbackDetail is not defined";
591 const exceptionDetails = {
592 text,
593 exception: { description: "" },
594 };
595 const sendCommand = vi.fn(async (method: string) =>
596 method === "Runtime.evaluate" ? { exceptionDetails } : undefined,
597 );
598 fromId.mockReturnValue({
599 id: 42,
600 isDestroyed: () => false,
601 getType: () => "webview",
602 getURL: () => "https://example.com",
603 getTitle: () => "Example",
604 isLoading: () => false,
605 isDevToolsOpened: () => false,
606 getZoomFactor: () => 1,
607 setZoomFactor: vi.fn(),
608 on: vi.fn(),
609 off: vi.fn(),
610 ipc: { on: vi.fn(), off: vi.fn() },
611 send: webviewSend,
612 navigationHistory: { canGoBack: () => false, canGoForward: () => false },
613 setWindowOpenHandler: vi.fn(),
614 debugger: {
615 isAttached: () => false,
616 attach: vi.fn(),
617 sendCommand,
618 on: vi.fn(),
619 off: vi.fn(),
620 },
621 } as never);
622
623 yield* manager.createTab("tab_1");
624 yield* manager.registerWebview("tab_1", 42);
625 const exit = yield* Effect.exit(
626 manager.automationEvaluate("tab_1", { expression: "fallbackDetail" }),
627 );
628
629 expect(Exit.isFailure(exit)).toBe(true);
630 if (Exit.isSuccess(exit)) return;
631 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
632 expect(error).toMatchObject({
633 _tag: "PreviewAutomationEvaluationError",
634 detailKind: "exception-text",
635 detailLength: text.length,
636 cause: exceptionDetails,
637 });
638 }),
639 ),
640 );
641});
642
643describe("PreviewOperationError", () => {
644 it("keeps timeline detail separate from its structured message", () => {
645 const cause = new Error("CDP command failed with an invalid node id");
646 const error = new PreviewManager.PreviewOperationError({
647 operation: "click.DOM.resolveNode",
648 tabId: "tab_1",
649 webContentsId: 42,
650 cause,
651 });
652
653 expect(error.message).not.toContain(cause.message);
654 expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message);
655 });
656});
657
658describe("Preview automation diagnostics", () => {
659 it("keeps browser exception detail out of structural diagnostics", () => {
660 const secret = "unrelated-browser-payload-secret";
661 const detail = "ReferenceError: missingValue is not defined";
662 const cause = {
663 text: "Uncaught Error",
664 exception: { description: detail },
665 unsafePayload: secret,
666 };
667 const error = new PreviewManager.PreviewAutomationEvaluationError({
668 tabId: "tab_1",
669 detailKind: "exception-description",
670 detailLength: detail.length,
671 cause,
672 });
673
674 const encoded = encodePreviewManagerError(error);
675 const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
676 readonly cause?: unknown;
677 };
678
679 expect(error.cause).toBe(cause);
680 expect(encodedCause).toStrictEqual(cause);
681 expect(error.message).toBe("Preview JavaScript evaluation failed in tab tab_1");
682 expect(error.message).not.toContain(secret);
683 expect(JSON.stringify(encodedDiagnostics)).not.toContain(secret);
684 expect("detail" in error).toBe(false);
685 expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).toBe(detail);
686 expect(PreviewManager.PreviewAutomationEvaluationError.toTimelineMessage(error)).not.toContain(
687 secret,
688 );
689 });
690
691 it("retains bounded selector diagnostics without exposing selector or reason text", () => {
692 const selector = "role=button[name='selector-secret']";
693 const reason = "Unexpected token near reason-secret";
694 const cause = { invalidSelector: true as const, message: reason };
695 const error = new PreviewManager.PreviewAutomationInvalidSelectorError({
696 operation: "click",
697 tabId: "tab_1",
698 selectorKind: "locator",
699 selectorLength: selector.length,
700 reasonLength: reason.length,
701 cause,
702 });
703
704 const encoded = encodePreviewManagerError(error);
705 const { cause: encodedCause, ...encodedDiagnostics } = encoded as typeof encoded & {
706 readonly cause?: unknown;
707 };
708
709 expect(error.cause).toBe(cause);
710 expect(encodedCause).toStrictEqual(cause);
711 expect(error).toMatchObject({
712 selectorKind: "locator",
713 selectorLength: selector.length,
714 reasonLength: reason.length,
715 });
716 expect(error.detail).toEqual({
717 selectorKind: "locator",
718 selectorLength: selector.length,
719 });
720 expect(error.message).not.toContain("secret");
721 expect(JSON.stringify(encodedDiagnostics)).not.toContain("secret");
722 expect("selector" in error).toBe(false);
723 expect("reason" in error).toBe(false);
724 expect(PreviewManager.PreviewAutomationInvalidSelectorError.toTimelineMessage(error)).toBe(
725 reason,
726 );
727 });
728
729 it("does not retain a missing target locator", () => {
730 const selector = "[data-token='target-secret']";
731 const error = new PreviewManager.PreviewAutomationTargetNotFoundError({
732 operation: "scroll",
733 tabId: "tab_1",
734 selectorKind: "selector",
735 selectorLength: selector.length,
736 });
737
738 expect(error.message).not.toContain(selector);
739 expect(JSON.stringify(error)).not.toContain(selector);
740 expect("locator" in error).toBe(false);
741 });
742});