Open History to see the last commit
1import * as NodeEvents from "node:events";
2import * as NodeVM from "node:vm";
3// @effect-diagnostics-next-line nodeBuiltinImport:off - Playwright download mocks perform real file operations outside the Effect runtime.
4import * as NodeFSP from "node:fs/promises";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import { it } from "@effect/vitest";
9import {
10 type BrowserRecordingFrameRate,
11 EnvironmentId,
12 PreviewTabId,
13 ProviderInstanceId,
14 ThreadId,
15 type PreviewAutomationSnapshot,
16 type PreviewAutomationStatus,
17} from "@t3tools/contracts";
18import * as Effect from "effect/Effect";
19import * as Fiber from "effect/Fiber";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Path from "effect/Path";
24import * as PubSub from "effect/PubSub";
25import * as Queue from "effect/Queue";
26import * as Stream from "effect/Stream";
27import type { BrowserContext, Page } from "playwright-core";
28import { beforeEach, expect, vi } from "vite-plus/test";
29
30import * as ServerConfig from "../config.ts";
31import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
32import * as Broker from "../mcp/PreviewAutomationBroker.ts";
33import * as DesktopChannel from "./DesktopBrowserChannel.ts";
34import * as Manager from "./Manager.ts";
35import * as ServerBrowser from "./ServerBrowser.ts";
36import * as PreviewBrowser from "./PreviewBrowser.ts";
37
38vi.mock("./ServerBrowserContexts.ts", () => ({
39 presentAsChrome: async () => {},
40 ServerBrowserContexts: class {
41 private readonly onClose: ((context: BrowserContext) => void) | undefined;
42 constructor(options: { onContextClose?: (context: BrowserContext) => void }) {
43 this.onClose = options.onContextClose;
44 }
45 async contextFor(profileId: string, isolationKey?: string) {
46 contextRequests.push({ profileId, isolated: isolationKey !== undefined });
47 if (contextFailure) throw contextFailure;
48 await contextGate?.promise;
49 const context = makeContext(this.onClose);
50 contexts.push(context);
51 return context as unknown as BrowserContext;
52 }
53 async scratchPage() {
54 return makeEncoderPage() as unknown as Page;
55 }
56 async connectDesktopPage(endpoint: string) {
57 const context = makeContext();
58 desktopConnections.push({ endpoint, context });
59 return { browser: { close: async () => {} }, page: context.page as unknown as Page };
60 }
61 async close() {
62 for (const context of contexts) await context.close();
63 }
64 },
65}));
66
67function makeFrame() {
68 const frame = {
69 copy: "",
70 detached: false,
71 isDetached: () => frame.detached,
72 recording: Promise.withResolvers<void>(),
73 };
74 return frame;
75}
76
77const PNG_HEADER = (() => {
78 const header = Buffer.alloc(24);
79 header.write("IHDR", 12);
80 header.writeUInt32BE(1280, 16);
81 header.writeUInt32BE(800, 20);
82 return header.toString("base64");
83})();
84
85function makeSession(frame?: ReturnType<typeof makeFrame>) {
86 const events = new NodeEvents.EventEmitter();
87 return {
88 on: vi.fn((name: string, listener: () => void) => events.on(name, listener)),
89 emit: (name: string) => events.emit(name),
90 detach: vi.fn(async () => {}),
91 send: vi.fn(async (method: string, input?: unknown): Promise<Record<string, unknown>> => {
92 if (method === "Page.getNavigationHistory") return { currentIndex: 0, entries: [{}] };
93 if (method === "Page.getLayoutMetrics") return { cssVisualViewport: { pageX: 0, pageY: 0 } };
94 if (method === "Page.captureScreenshot") {
95 // A snapshot sizes its screenshot from the PNG header; viewers get JPEG frames as-is.
96 return { data: (input as { format: string }).format === "png" ? PNG_HEADER : "ZnJhbWU=" };
97 }
98 if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
99 // Snapshots read password fields from their own isolated world in each frame.
100 if (method === "Page.createIsolatedWorld") {
101 return {
102 executionContextId: (input as { worldName?: string }).worldName === "t3-preview" ? 1 : 7,
103 };
104 }
105 if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 1) {
106 return { result: { value: [] } };
107 }
108 if (method === "Page.addScriptToEvaluateOnNewDocument") frame?.recording.resolve();
109 if (method === "Input.dispatchKeyEvent" && (input as { commands?: unknown }).commands) {
110 if (focusedFrame) focusedFrame.copy = keyCopy || focusedFrame.copy;
111 else pageCopy = keyCopy || pageCopy;
112 }
113 if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) {
114 const value = frame ? frame.copy : pageCopy;
115 if (frame) frame.copy = "";
116 else pageCopy = "";
117 return { result: { value } };
118 }
119 return { result: { value: "evaluated" } };
120 }),
121 };
122}
123
124function makeContext(onClose?: (context: BrowserContext) => void) {
125 const events = new NodeEvents.EventEmitter();
126 const nativeFileChooser = vi.fn();
127 const setChooserFiles = vi.fn(async (_files: unknown) => {});
128 const sessions: ReturnType<typeof makeSession>[] = [];
129 let url = "about:blank";
130 let viewport = { width: 1280, height: 800 };
131 let closed = false;
132 let contextClosed = false;
133 const page = {
134 on: (name: string, callback: (...args: unknown[]) => void) => events.on(name, callback),
135 once: (name: string, callback: (...args: unknown[]) => void) => events.once(name, callback),
136 off: (name: string, callback: (...args: unknown[]) => void) => events.off(name, callback),
137 emit: (name: string, ...args: unknown[]) => events.emit(name, ...args),
138 nativeFileChooser,
139 setChooserFiles,
140 openFileChooser: () => {
141 if (
142 !events.emit("filechooser", {
143 isMultiple: () => false,
144 element: () => ({ getAttribute: async () => ".csv" }),
145 setFiles: setChooserFiles,
146 })
147 ) {
148 nativeFileChooser();
149 }
150 },
151 emitAsync: (name: string, ...args: unknown[]) =>
152 Promise.all(events.listeners(name).map((listener) => listener(...args))),
153 setDefaultTimeout: vi.fn(),
154 setDefaultNavigationTimeout: vi.fn(),
155 context: () => context,
156 mainFrame: () => page,
157 frames: () => [page],
158 url: () => url,
159 title: vi.fn(async () => "test page"),
160 viewportSize: () => viewport,
161 setViewportSize: vi.fn(async (size: typeof viewport) => {
162 viewport = size;
163 }),
164 goto: vi.fn(async (next: string) => {
165 url = next;
166 events.emit("load");
167 const pending = initialNavigation;
168 initialNavigation = null;
169 await pending?.();
170 }),
171 goBack: vi.fn(async () => {}),
172 goForward: vi.fn(async () => {}),
173 reload: vi.fn(async () => {}),
174 emulateMedia: vi.fn(async () => {}),
175 waitForLoadState: vi.fn(async () => {}),
176 evaluate: vi.fn(async () => ({
177 url,
178 title: "test page",
179 loading: false,
180 visibleText: "delete",
181 interactiveElements: [],
182 })),
183 ariaSnapshot: vi.fn(async () => '- button "delete" [ref=e1]'),
184 locator: vi.fn(() => {
185 throw new Error("Unexpected locator action");
186 }),
187 isClosed: () => closed,
188 close: vi.fn(async () => {
189 if (!closed) {
190 closed = true;
191 events.emit("close");
192 }
193 }),
194 };
195 const context = {
196 page,
197 sessions,
198 newPage: async () => page as unknown as Page,
199 grantPermissions: vi.fn(async () => {}),
200 newCDPSession: async (target: unknown) => {
201 const session = makeSession(
202 target === page ? undefined : (target as ReturnType<typeof makeFrame>),
203 );
204 sessions.push(session);
205 return session;
206 },
207 close: vi.fn(async () => {
208 if (contextClosed) return;
209 contextClosed = true;
210 await page.close();
211 onClose?.(context as unknown as BrowserContext);
212 }),
213 };
214 return context;
215}
216
217// Runs the real encoder script against fake canvas and MediaRecorder globals.
218function makeEncoderPage() {
219 const canvas = {
220 width: 0,
221 height: 0,
222 getContext: () => ({ drawImage() {}, fillRect() {} }),
223 captureStream: (frameRate?: number) => ({ frameRate, getTracks: () => [] }),
224 };
225 class FakeMediaRecorder {
226 static isTypeSupported = (type: string) => type === "video/webm";
227 onstart: (() => void) | null = null;
228 constructor(stream: { frameRate?: number }, options: { videoBitsPerSecond: number }) {
229 encoderStreams.push({
230 frameRate: stream.frameRate,
231 bitsPerSecond: options.videoBitsPerSecond,
232 });
233 }
234 start() {
235 this.onstart?.();
236 }
237 }
238 const sandbox: Record<string, unknown> = {
239 document: { createElement: () => canvas },
240 Path2D: function Path2D() {},
241 MediaRecorder: FakeMediaRecorder,
242 createImageBitmap: async () => ({ width: 1280, height: 800, close() {} }),
243 atob,
244 Blob,
245 performance,
246 };
247 sandbox.window = sandbox;
248 const context = NodeVM.createContext(sandbox);
249 return {
250 ...makeContext().page,
251 evaluate: vi.fn(async (script: string | ((arg: unknown) => unknown), arg?: unknown) =>
252 typeof script === "string"
253 ? NodeVM.runInContext(script, context)
254 : NodeVM.runInContext(`(${script.toString()})`, context)(arg),
255 ),
256 };
257}
258
259const contexts: ReturnType<typeof makeContext>[] = [];
260const encoderStreams: Array<{ frameRate: number | undefined; bitsPerSecond: number }> = [];
261const contextRequests: Array<{ profileId: string; isolated: boolean }> = [];
262let contextGate: PromiseWithResolvers<void> | null = null;
263let pageCopy = "";
264let keyCopy = "";
265let focusedFrame: ReturnType<typeof makeFrame> | null = null;
266let contextFailure: Error | null = null;
267let initialNavigation: (() => Promise<void>) | null = null;
268let desktopRendersNext = false;
269const desktopDetaches = new NodeEvents.EventEmitter();
270const desktopTabs = new Set<string>();
271const desktopRenders = (tabId: string) => {
272 if (desktopRendersNext) {
273 desktopRendersNext = false;
274 desktopTabs.add(tabId);
275 }
276 return desktopTabs.has(tabId);
277};
278const releasedDesktopTabs: Array<string> = [];
279const desktopConnections: Array<{ endpoint: string; context: ReturnType<typeof makeContext> }> = [];
280const testThread = {
281 threadId: ThreadId.make("browser-test-thread"),
282 providerSessionId: "agent-a",
283 providerInstanceId: ProviderInstanceId.make("codex"),
284};
285const scope = {
286 environmentId: EnvironmentId.make("browser-test-environment"),
287 thread: testThread,
288 client: undefined,
289 requestNamespace: "browser-test",
290 capabilities: new Set(["preview"] as const),
291 issuedAt: 1,
292};
293const asSession = (providerSessionId: string) => ({
294 ...scope,
295 thread: { ...testThread, providerSessionId },
296});
297const dependencies = Layer.mergeAll(
298 Broker.layer,
299 Manager.layer,
300 Layer.succeed(ServerEnvironment.ServerEnvironment, {
301 getEnvironmentId: Effect.succeed(scope.environmentId),
302 getDescriptor: Effect.die("unused descriptor"),
303 }),
304 Layer.succeed(PreviewBrowser.PreviewBrowser, {
305 executable: Effect.die("mock Chromium does not need an executable"),
306 installed: Effect.die("mock Chromium does not need an executable"),
307 }),
308 Layer.succeed(DesktopChannel.DesktopBrowserChannel, {
309 available: true,
310 awaitAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)),
311 detached: Stream.callback<{ threadId: string; tabId: string }>((queue) =>
312 Effect.acquireRelease(
313 Effect.sync(() => {
314 const onDetach = (key: { threadId: string; tabId: string }) =>
315 Queue.offerUnsafe(queue, key);
316 desktopDetaches.on("detach", onDetach);
317 return onDetach;
318 }),
319 (onDetach) => Effect.sync(() => desktopDetaches.off("detach", onDetach)),
320 ),
321 ),
322 attached: Stream.callback<{ threadId: string; tabId: string }>((queue) =>
323 Effect.acquireRelease(
324 Effect.sync(() => {
325 const onAttach = (key: { threadId: string; tabId: string }) =>
326 Queue.offerUnsafe(queue, key);
327 desktopDetaches.on("attach", onAttach);
328 return onAttach;
329 }),
330 (onAttach) => Effect.sync(() => desktopDetaches.off("attach", onAttach)),
331 ),
332 ),
333 isAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)),
334 endpoint: (key) =>
335 Effect.acquireRelease(Effect.succeed(`ws://desktop/${key.tabId}`), () =>
336 Effect.sync(() => releasedDesktopTabs.push(key.tabId)),
337 ),
338 pointer: () => Effect.void,
339 }),
340).pipe(
341 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-server-browser-" })),
342 Layer.provideMerge(NodeServices.layer),
343);
344const layer = ServerBrowser.layer.pipe(Layer.provideMerge(dependencies));
345const ready = Effect.gen(function* () {
346 const browser = yield* ServerBrowser.ServerBrowser;
347 const broker = yield* Broker.PreviewAutomationBroker;
348 yield* Effect.yieldNow;
349 const opened = yield* broker.invoke<PreviewAutomationStatus>({
350 scope,
351 operation: "open",
352 input: { reuseExistingTab: false, show: false },
353 });
354 const tabId = PreviewTabId.make(opened.tabId!);
355 return { browser, broker, tabId };
356});
357const viewerInput = (tabId: string, canOperate: boolean) => ({
358 threadId: scope.thread.threadId,
359 tabId,
360 canOperate,
361 maxWidth: 1280,
362 maxHeight: 800,
363 quality: 70,
364});
365
366beforeEach(() => {
367 contexts.length = 0;
368 encoderStreams.length = 0;
369 contextRequests.length = 0;
370 contextGate = null;
371 contextFailure = null;
372 initialNavigation = null;
373 pageCopy = "";
374 keyCopy = "";
375 focusedFrame = null;
376 desktopTabs.clear();
377 desktopRendersNext = false;
378 releasedDesktopTabs.length = 0;
379 desktopConnections.length = 0;
380});
381
382it.live.each(["desktop" as const, undefined])(
383 "explicit desktop targets ($0 runtime) fail without creating a server tab",
384 (runtime) =>
385 Effect.scoped(
386 Effect.gen(function* () {
387 const { broker, tabId } = yield* ready;
388 const manager = yield* Manager.PreviewManager;
389 const desktop = yield* manager.open({
390 threadId: scope.thread.threadId,
391 url: "https://example.com/original",
392 ...(runtime === undefined ? {} : { runtime }),
393 });
394 const before = yield* manager.list({ threadId: scope.thread.threadId });
395 const error = yield* broker
396 .invoke<PreviewAutomationStatus>({
397 scope,
398 tabId: PreviewTabId.make(desktop.tabId),
399 operation: "open",
400 input: { url: "https://example.com/replacement", open: true },
401 })
402 .pipe(Effect.flip);
403 expect(error).toMatchObject({ _tag: "PreviewAutomationExecutionError" });
404 expect(error.message).toContain("desktop runtime");
405 expect(error.message).toContain("cannot control");
406 expect(yield* manager.list({ threadId: scope.thread.threadId })).toEqual(before);
407 expect(contexts).toHaveLength(1);
408 // A rejected explicit target must not replace this session's working tab.
409 const reused = yield* broker.invoke<PreviewAutomationStatus>({
410 scope,
411 operation: "open",
412 input: { open: false },
413 });
414 expect(reused.tabId).toBe(tabId);
415 }),
416 ).pipe(Effect.provide(layer)),
417);
418
419it.live.each([
420 { method: "goto" as const, message: { type: "navigate", url: "http://10.255.255.1/" } },
421 { method: "goBack" as const, message: { type: "history", delta: -1 } },
422 { method: "goForward" as const, message: { type: "history", delta: 1 } },
423 { method: "reload" as const, message: { type: "reload" } },
424])("a pending viewer $method allows a corrected URL and text input", ({ method, message }) =>
425 Effect.scoped(
426 Effect.gen(function* () {
427 const { browser, tabId } = yield* ready;
428 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
429 yield* viewer.input({ type: "takeControl" });
430 const started = Promise.withResolvers<void>();
431 const committed = Promise.withResolvers<void>();
432 const page = contexts[0]!.page;
433 page[method].mockImplementationOnce(() => {
434 started.resolve();
435 return committed.promise;
436 });
437 const navigation = yield* viewer.input(message).pipe(Effect.forkScoped);
438 yield* Effect.promise(() => started.promise);
439 const cdp = contexts[0]!.sessions.at(-1)!;
440 const send = cdp.send.getMockImplementation()!;
441 const typed = Promise.withResolvers<void>();
442 cdp.send.mockImplementation(async (operation, input) => {
443 if (operation === "Input.insertText") typed.resolve();
444 return send(operation, input);
445 });
446 const correction = yield* Effect.gen(function* () {
447 yield* viewer.input({ type: "navigate", url: "http://localhost:5173/fixed" });
448 yield* viewer.input({ type: "text", text: "hello" });
449 }).pipe(Effect.forkScoped);
450 yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));
451 // The text reaches the page while the first navigation is still uncommitted.
452 yield* Effect.promise(() => typed.promise);
453 expect(page.goto).toHaveBeenLastCalledWith(
454 "http://localhost:5173/fixed",
455 expect.objectContaining({ waitUntil: "commit" }),
456 );
457 expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", {
458 text: "hello",
459 });
460 committed.resolve();
461 yield* Fiber.join(navigation);
462 yield* Fiber.join(correction);
463 }),
464 ).pipe(Effect.provide(layer)),
465);
466
467// The fake encoder decodes every frame at 1280x800, so 30 fps hits the bitrate floor.
468it.live.each([
469 { reports: [], frameRate: 30, bitsPerSecond: 2.5e6 },
470 { reports: [30], frameRate: 30, bitsPerSecond: 2.5e6 },
471 { reports: [60], frameRate: 60, bitsPerSecond: 1280 * 800 * 60 * 0.05 },
472 { reports: [60, undefined], frameRate: 60, bitsPerSecond: 1280 * 800 * 60 * 0.05 },
473 { reports: [60, 30], frameRate: 30, bitsPerSecond: 2.5e6 },
474] satisfies ReadonlyArray<{
475 reports: ReadonlyArray<BrowserRecordingFrameRate | undefined>;
476 frameRate: number;
477 bitsPerSecond: number;
478}>)(
479 "agent recordings encode at the last reported frame rate ($reports)",
480 ({ reports, frameRate, bitsPerSecond }) =>
481 Effect.scoped(
482 Effect.gen(function* () {
483 const { browser, broker, tabId } = yield* ready;
484 for (const recordingFrameRate of reports) {
485 yield* browser.reportProfiles({
486 profiles: [],
487 defaultProfileId: "default",
488 ...(recordingFrameRate === undefined ? {} : { recordingFrameRate }),
489 });
490 }
491 yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} });
492 expect(encoderStreams).toEqual([{ frameRate, bitsPerSecond }]);
493 }),
494 ).pipe(Effect.provide(layer)),
495);
496
497it.live("enforces provider ownership and explicit targets when a session has multiple tabs", () =>
498 Effect.scoped(
499 Effect.gen(function* () {
500 const { broker, tabId } = yield* ready;
501 const foreign = yield* broker
502 .invoke<void>({
503 scope: asSession("agent-b"),
504 tabId,
505 operation: "navigate",
506 input: { url: "http://localhost:5173/foreign" },
507 })
508 .pipe(Effect.flip);
509 expect(foreign).toMatchObject({
510 _tag: "PreviewAutomationControlInterruptedError",
511 reason: "agentMismatch",
512 });
513 expect(contexts[0]!.page.goto).not.toHaveBeenCalledWith(
514 "http://localhost:5173/foreign",
515 expect.anything(),
516 );
517 yield* broker.invoke<PreviewAutomationSnapshot>({
518 scope: asSession("agent-b"),
519 tabId,
520 operation: "snapshot",
521 input: {},
522 });
523 const foreignEvaluate = yield* broker
524 .invoke<void>({
525 scope: asSession("agent-b"),
526 tabId,
527 operation: "evaluate",
528 input: { expression: "read()" },
529 })
530 .pipe(Effect.flip);
531 expect(foreignEvaluate).toMatchObject({
532 _tag: "PreviewAutomationControlInterruptedError",
533 reason: "agentMismatch",
534 });
535 yield* broker.invoke({
536 scope,
537 operation: "open",
538 input: { reuseExistingTab: false, show: false },
539 });
540 const ambiguous = yield* broker
541 .invoke<void>({ scope, operation: "evaluate", input: { expression: "ambiguous()" } })
542 .pipe(Effect.flip);
543 expect(ambiguous).toMatchObject({
544 _tag: "PreviewAutomationControlInterruptedError",
545 reason: "tabRequired",
546 });
547 const ambiguousStop = yield* broker
548 .invoke<void>({ scope, operation: "recordingStop", input: {} })
549 .pipe(Effect.flip);
550 expect(ambiguousStop).toMatchObject({
551 _tag: "PreviewAutomationControlInterruptedError",
552 reason: "tabRequired",
553 });
554 const explicitStop = yield* broker
555 .invoke<void>({ scope, tabId, operation: "recordingStop", input: {} })
556 .pipe(Effect.flip);
557 expect(explicitStop).toMatchObject({
558 _tag: "PreviewAutomationExecutionError",
559 cause: { _tag: "PreviewAutomationRecordingNotActiveError" },
560 });
561 const result = yield* broker.invoke({
562 scope,
563 tabId,
564 operation: "evaluate",
565 input: { expression: "owned()" },
566 });
567 expect(result).toBe("evaluated");
568 expect(contexts).toHaveLength(2);
569 }),
570 ).pipe(Effect.provide(layer)),
571);
572
573it.live("streams to a read-only viewer without allowing takeover, input, or viewport changes", () =>
574 Effect.scoped(
575 Effect.gen(function* () {
576 const { browser, tabId } = yield* ready;
577 const viewer = yield* browser.attachViewer(viewerInput(tabId, false));
578 const page = contexts[0]!.page;
579 page.setViewportSize.mockClear();
580 const session = contexts[0]!.sessions.at(-1)!;
581 session.send.mockClear();
582 for (const message of [
583 { type: "takeControl" },
584 { type: "key", action: "down", key: "a", text: "a" },
585 { type: "resize", width: 390, height: 844 },
586 { type: "viewport", setting: { _tag: "freeform", width: 390, height: 844 } },
587 ])
588 yield* viewer.input(message);
589 expect(page.setViewportSize).not.toHaveBeenCalled();
590 expect(session.send.mock.calls.some(([method]) => method.startsWith("Input."))).toBe(false);
591 const outputs = yield* Queue.takeAll(viewer.output);
592 expect(outputs).toContainEqual(
593 expect.objectContaining({ _tag: "frame", data: Buffer.from("frame") }),
594 );
595 expect(outputs).toContainEqual(expect.objectContaining({ _tag: "viewport" }));
596 expect(outputs).toContainEqual(
597 expect.objectContaining({ _tag: "control", canOperate: false, controller: "agent" }),
598 );
599 const operator = yield* browser.attachViewer(viewerInput(tabId, true));
600 yield* operator.input({ type: "takeControl" });
601 yield* operator.input({ type: "text", text: "typed" });
602 yield* operator.input({ type: "resize", width: 390, height: 844 });
603 expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", {
604 text: "typed",
605 });
606 expect(page.setViewportSize).toHaveBeenCalledWith({ width: 390, height: 844 });
607 yield* operator.input({ type: "releaseControl" });
608 }),
609 ).pipe(Effect.provide(layer)),
610);
611
612it.live(
613 "takeover waits for the running agent and revokes snapshot refs before returning control",
614 () =>
615 Effect.scoped(
616 Effect.gen(function* () {
617 const { browser, broker, tabId } = yield* ready;
618 const snapshot = yield* broker.invoke<PreviewAutomationSnapshot>({
619 scope,
620 tabId,
621 operation: "snapshot",
622 input: {},
623 });
624 const ref = /\[ref=([^\]]+)\]/.exec(String(snapshot.accessibilityTree))![1]!;
625 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
626 const started = Promise.withResolvers<void>();
627 const finish = Promise.withResolvers<Record<string, unknown>>();
628 const session = contexts[0]!.sessions[0]!;
629 session.send.mockImplementationOnce(async () => {
630 started.resolve();
631 return finish.promise;
632 });
633 const running = yield* broker
634 .invoke({ scope, tabId, operation: "evaluate", input: { expression: "pending()" } })
635 .pipe(Effect.forkScoped);
636 yield* Effect.addFinalizer(() =>
637 Effect.sync(() => finish.resolve({ result: { value: "finished" } })),
638 );
639 yield* Effect.promise(() => started.promise);
640 const takeover = yield* viewer.input({ type: "takeControl" }).pipe(Effect.forkScoped);
641 let control = yield* Queue.take(viewer.output);
642 while (control._tag !== "control" || control.controller !== "you") {
643 control = yield* Queue.take(viewer.output);
644 }
645 const rejected = yield* broker
646 .invoke<void>({ scope, tabId, operation: "evaluate", input: { expression: "racing()" } })
647 .pipe(Effect.flip);
648 expect(rejected).toMatchObject({
649 _tag: "PreviewAutomationControlInterruptedError",
650 reason: "humanControl",
651 });
652 finish.resolve({ result: { value: "finished" } });
653 expect(yield* Fiber.join(running)).toBe("finished");
654 yield* Fiber.join(takeover);
655 yield* viewer.input({ type: "releaseControl" });
656 const stale = yield* broker
657 .invoke<void>({ scope, tabId, operation: "click", input: { locator: `aria-ref=${ref}` } })
658 .pipe(Effect.flip);
659 expect(stale._tag).toBe("PreviewAutomationInvalidSelectorError");
660 expect(contexts[0]!.page.locator).not.toHaveBeenCalled();
661 expect(
662 yield* broker.invoke({
663 scope,
664 tabId,
665 operation: "evaluate",
666 input: { expression: "resumed()" },
667 }),
668 ).toBe("evaluated");
669 }),
670 ).pipe(Effect.provide(layer)),
671);
672
673it.live("reports a pending dialog without evaluating the page and resolves it explicitly", () =>
674 Effect.scoped(
675 Effect.gen(function* () {
676 const { broker, tabId } = yield* ready;
677 const page = contexts[0]!.page;
678 yield* broker.invoke({
679 scope,
680 tabId,
681 operation: "navigate",
682 input: { url: "http://localhost:5173" },
683 });
684 const started = Promise.withResolvers<void>();
685 const resolvedEvaluation = Promise.withResolvers<Record<string, unknown>>();
686 const session = contexts[0]!.sessions[0]!;
687 const send = session.send.getMockImplementation()!;
688 session.send.mockImplementation(async (method, input) => {
689 if (method !== "Runtime.evaluate") return send(method, input);
690 started.resolve();
691 return resolvedEvaluation.promise;
692 });
693 const blockedAction = yield* broker
694 .invoke({
695 scope,
696 tabId,
697 operation: "evaluate",
698 input: { expression: 'confirm("Delete row?")' },
699 })
700 .pipe(Effect.forkScoped);
701 yield* Effect.addFinalizer(() =>
702 Effect.sync(() => resolvedEvaluation.resolve({ result: { value: true } })),
703 );
704 yield* Effect.promise(() => started.promise);
705 const dialog = {
706 type: () => "confirm",
707 message: () => "Delete row?",
708 defaultValue: () => "",
709 accept: vi.fn(async () => {
710 resolvedEvaluation.resolve({ result: { value: true } });
711 }),
712 dismiss: vi.fn(async () => {}),
713 };
714 page.emit("dialog", dialog);
715 page.title.mockClear();
716 const status = yield* broker.invoke<PreviewAutomationStatus>({
717 scope,
718 tabId,
719 operation: "status",
720 input: {},
721 });
722 expect(status.dialog).toMatchObject({ type: "confirm", message: "Delete row?" });
723 expect(page.title).not.toHaveBeenCalled();
724 expect(dialog.dismiss).not.toHaveBeenCalled();
725 const reuse = yield* broker
726 .invoke<void>({
727 scope,
728 tabId,
729 operation: "open",
730 input: { url: "http://localhost:5173/other" },
731 })
732 .pipe(Effect.flip);
733 expect(reuse).toMatchObject({
734 _tag: "PreviewAutomationControlInterruptedError",
735 reason: "dialogPending",
736 });
737 expect(page.goto).toHaveBeenCalledTimes(1);
738 yield* broker.invoke({ scope, tabId, operation: "dialog", input: { accept: true } });
739 expect(yield* Fiber.join(blockedAction)).toBe(true);
740 expect(dialog.accept).toHaveBeenCalledTimes(1);
741 const resolved = yield* broker.invoke<PreviewAutomationStatus>({
742 scope,
743 tabId,
744 operation: "status",
745 input: {},
746 });
747 expect(resolved.dialog).toBeNull();
748 }),
749 ).pipe(Effect.provide(layer)),
750);
751
752it.live("a tab opened to a file the browser cannot show reports the file to download", () =>
753 Effect.scoped(
754 Effect.gen(function* () {
755 const browser = yield* ServerBrowser.ServerBrowser;
756 const manager = yield* Manager.PreviewManager;
757 const events = yield* manager.subscribeEvents;
758 yield* Effect.yieldNow;
759 const opened = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" });
760 const viewer = yield* browser.attachViewer(viewerInput(opened.tabId, true));
761 const page = contexts[0]!.page;
762 const pdf = "https://example.com/paper.pdf";
763 const request = { url: () => pdf, method: () => "GET", isNavigationRequest: () => true };
764 // What Chromium reports when a navigation turns into a download.
765 page.emit("requestfailed", {
766 ...request,
767 frame: () => page,
768 failure: () => ({ errorText: "net::ERR_ABORTED" }),
769 });
770 const saved = yield* Queue.unbounded<string>();
771 const written = Promise.withResolvers<void>();
772 page.emit("download", {
773 failure: async () => null,
774 delete: async () => {
775 // A new navigation during cleanup must not erase the settled download status.
776 page.emit("request", {
777 url: () => "https://example.com/next",
778 method: () => "GET",
779 isNavigationRequest: () => true,
780 frame: () => page,
781 });
782 },
783 saveAs: (path: string) => {
784 Queue.offerUnsafe(saved, path);
785 return written.promise;
786 },
787 suggestedFilename: () => "paper.pdf",
788 url: () => pdf,
789 });
790 const fs = yield* FileSystem.FileSystem;
791 yield* fs.writeFileString(yield* Queue.take(saved), "%PDF");
792 written.resolve();
793 const received = [];
794 let status;
795 do {
796 status = yield* PubSub.take(events);
797 received.push(status);
798 } while (
799 status.type !== "navigated" ||
800 status.snapshot.navStatus._tag !== "Loading" ||
801 status.snapshot.navStatus.url !== "https://example.com/next"
802 );
803 expect(received).toContainEqual(
804 expect.objectContaining({
805 type: "failed",
806 url: pdf,
807 download: { id: expect.any(String), fileName: "paper.pdf" },
808 }),
809 );
810 expect((yield* Queue.clear(viewer.output)).some((item) => item._tag === "download")).toBe(
811 false,
812 );
813 }),
814 ).pipe(Effect.provide(layer)),
815);
816
817it.live(
818 "a late failure from a request that predates tracking leaves a newer navigation loading",
819 () =>
820 Effect.scoped(
821 Effect.gen(function* () {
822 const { broker, tabId } = yield* ready;
823 const page = contexts[0]!.page;
824 const navigation = (url: string) => ({
825 url: () => url,
826 method: () => "GET",
827 isNavigationRequest: () => true,
828 frame: () => page,
829 failure: () => ({ errorText: "net::ERR_CONNECTION_REFUSED" }),
830 });
831 page.emit("request", navigation("https://example.com/next"));
832 // A popup's first request can start before the tab listens for requests.
833 page.emit("requestfailed", navigation("https://example.com/first"));
834 const status = yield* broker.invoke<PreviewAutomationStatus>({
835 scope,
836 tabId,
837 operation: "status",
838 input: {},
839 });
840 expect(status.loading).toBe(true);
841 }),
842 ).pipe(Effect.provide(layer)),
843);
844
845it.live("only the controlling viewer's copy and cut keys reach its clipboard", () =>
846 Effect.scoped(
847 Effect.gen(function* () {
848 const { browser, tabId } = yield* ready;
849 const watcher = yield* browser.attachViewer(viewerInput(tabId, false));
850 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
851 yield* viewer.input({ type: "takeControl" });
852 const clipboard = (queue: typeof viewer.output) =>
853 Queue.clear(queue).pipe(
854 Effect.map((items) => items.filter((item) => item._tag === "clipboard")),
855 );
856 pageCopy = "unprompted";
857 yield* viewer.input({ type: "mouse", action: "move", x: 10, y: 10 });
858 yield* viewer.input({ type: "wheel", x: 10, y: 10, deltaY: 40 });
859 yield* viewer.input({ type: "key", action: "down", key: "v", code: "KeyV", modifiers: 4 });
860 yield* viewer.input({ type: "unknown" });
861 expect(yield* clipboard(viewer.output)).toEqual([]);
862 keyCopy = "copied";
863 yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
864 const cdp = contexts[0]!.sessions.at(-1)!;
865 expect(cdp.send).toHaveBeenCalledWith(
866 "Input.dispatchKeyEvent",
867 expect.objectContaining({ key: "c", commands: ["copy"] }),
868 );
869 expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "copied" }]);
870 keyCopy = "cut";
871 yield* viewer.input({ type: "key", action: "down", key: "x", code: "KeyX", modifiers: 2 });
872 expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "cut" }]);
873 pageCopy = "left over";
874 keyCopy = "";
875 yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
876 expect(yield* clipboard(viewer.output)).toEqual([]);
877 expect(yield* clipboard(watcher.output)).toEqual([]);
878 }),
879 ).pipe(Effect.provide(layer)),
880);
881
882it.live.each([false, true])(
883 "a page download is saved, offered to the controller, and listed for the agent (delete fails: %s)",
884 (deleteFails) =>
885 Effect.scoped(
886 Effect.gen(function* () {
887 const { browser, broker, tabId } = yield* ready;
888 const page = contexts[0]!.page;
889 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
890 yield* viewer.input({ type: "takeControl" });
891 yield* Queue.clear(viewer.output);
892 const fs = yield* FileSystem.FileSystem;
893 const original = `${yield* fs.makeTempDirectoryScoped()}/chromium-download`;
894 yield* fs.writeFileString(original, "a,b");
895 const released = Promise.withResolvers<void>();
896 page.emit("download", {
897 failure: async () => null,
898 delete: async () => {
899 try {
900 if (deleteFails) throw new Error("context closed");
901 await NodeFSP.rm(original);
902 } finally {
903 released.resolve();
904 }
905 },
906 saveAs: (path: string) => NodeFSP.copyFile(original, path),
907 suggestedFilename: () => "report.csv",
908 url: () => 'data:text/csv;charset="a,b",a b\'c',
909 });
910 let offered = yield* Queue.take(viewer.output);
911 while (offered._tag !== "download") offered = yield* Queue.take(viewer.output);
912 expect(offered).toMatchObject({ _tag: "download", fileName: "report.csv", sizeBytes: 3 });
913 yield* Effect.promise(() => released.promise);
914 expect(yield* fs.exists(original)).toBe(deleteFails);
915 const file = yield* browser.openDownload({
916 threadId: scope.thread.threadId,
917 tabId,
918 downloadId: offered.id,
919 });
920 expect(Option.isSome(file) && file.value.fileName).toBe("report.csv");
921 expect(yield* fs.readFileString(Option.getOrThrow(file).path)).toBe("a,b");
922 if ((yield* HostProcess.Platform) !== "win32") {
923 expect((yield* fs.stat(Option.getOrThrow(file).path)).mode & 0o777).toBe(0o600);
924 }
925 const status = yield* broker.invoke<PreviewAutomationStatus>({
926 scope,
927 tabId,
928 operation: "status",
929 input: {},
930 });
931 expect(status.downloads).toEqual([
932 expect.objectContaining({
933 fileName: "report.csv",
934 sizeBytes: 3,
935 url: "data:text/csv,…",
936 }),
937 ]);
938 expect(
939 Option.isNone(
940 yield* browser.openDownload({
941 threadId: scope.thread.threadId,
942 tabId,
943 downloadId: "guess",
944 }),
945 ),
946 ).toBe(true);
947 if ((yield* HostProcess.Platform) !== "win32") {
948 const folder = (yield* Path.Path).dirname(Option.getOrThrow(file).path);
949 yield* fs.chmod(folder, 0o755);
950 page.emit("download", {
951 failure: async () => null,
952 delete: async () => {},
953 saveAs: (path: string) => NodeFSP.writeFile(path, "c"),
954 suggestedFilename: () => "again.csv",
955 url: () => "https://example.test/again.csv",
956 });
957 let again = yield* Queue.take(viewer.output);
958 while (again._tag !== "download") again = yield* Queue.take(viewer.output);
959 expect((yield* fs.stat(folder)).mode & 0o777).toBe(0o700);
960 }
961 }),
962 ).pipe(Effect.provide(layer)),
963);
964
965it.live.each(["save failed", "oversized"])(
966 "a rejected download releases the original and keeps no saved copy (%s)",
967 (outcome) =>
968 Effect.scoped(
969 Effect.gen(function* () {
970 const { broker, tabId } = yield* ready;
971 const fs = yield* FileSystem.FileSystem;
972 const original = `${yield* fs.makeTempDirectoryScoped()}/chromium-download`;
973 yield* fs.writeFileString(original, "a,b");
974 let savedPath: string | undefined;
975 const released = Promise.withResolvers<void>();
976 contexts[0]!.page.emit("download", {
977 failure: async () => null,
978 delete: async () => {
979 await NodeFSP.rm(original);
980 released.resolve();
981 },
982 saveAs: async (path: string) => {
983 savedPath = path;
984 await NodeFSP.copyFile(original, path);
985 if (outcome === "save failed") throw new Error("save interrupted");
986 // A sparse file exercises the size limit without writing a GiB of data.
987 await NodeFSP.truncate(path, 1024 ** 3 + 1);
988 },
989 suggestedFilename: () => "report.csv",
990 url: () => "blob:http://localhost:5173/1",
991 });
992 yield* Effect.promise(() => released.promise);
993 expect(yield* fs.exists(original)).toBe(false);
994 if (savedPath !== undefined) expect(yield* fs.exists(savedPath)).toBe(false);
995 const status = yield* broker.invoke<PreviewAutomationStatus>({
996 scope,
997 tabId,
998 operation: "status",
999 input: {},
1000 });
1001 expect(status.downloads).toEqual([]);
1002 }),
1003 ).pipe(Effect.provide(layer)),
1004);
1005
1006it.live("a page's file picker goes to the controller and takes its uploaded files", () =>
1007 Effect.scoped(
1008 Effect.gen(function* () {
1009 const { browser, tabId } = yield* ready;
1010 const page = contexts[0]!.page;
1011 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
1012 yield* viewer.input({ type: "takeControl" });
1013 const setFiles = vi.fn(async (_files: unknown) => {});
1014 page.emit("filechooser", {
1015 isMultiple: () => false,
1016 element: () => ({ getAttribute: async () => ".csv" }),
1017 setFiles,
1018 });
1019 let offered = yield* Queue.take(viewer.output);
1020 while (offered._tag !== "fileChooser") offered = yield* Queue.take(viewer.output);
1021 expect(offered).toMatchObject({ multiple: false, accept: ".csv" });
1022 const file = (name: string) => ({ name, mimeType: "text/csv", buffer: Buffer.from(name) });
1023 const answer = (chooserId: string) =>
1024 browser.answerFileChooser({
1025 threadId: scope.thread.threadId,
1026 tabId,
1027 chooserId,
1028 files: [file("a.csv"), file("b.csv")],
1029 });
1030 expect(yield* answer("other")).toBe(false);
1031 expect(yield* answer(offered.id)).toBe(true);
1032 expect(setFiles).toHaveBeenCalledExactlyOnceWith([file("a.csv")]);
1033 let closed = yield* Queue.take(viewer.output);
1034 while (closed._tag !== "fileChooserClosed") closed = yield* Queue.take(viewer.output);
1035 expect(closed.id).toBe(offered.id);
1036 expect(yield* answer(offered.id)).toBe(false);
1037 }),
1038 ).pipe(Effect.provide(layer)),
1039);
1040
1041it.live("only the current controller can answer a file picker", () =>
1042 Effect.scoped(
1043 Effect.gen(function* () {
1044 const { browser, tabId } = yield* ready;
1045 const first = yield* browser.attachViewer(viewerInput(tabId, true));
1046 yield* first.input({ type: "takeControl" });
1047 const setFiles = vi.fn(async (_files: unknown) => {});
1048 contexts[0]!.page.emit("filechooser", {
1049 isMultiple: () => false,
1050 element: () => ({ getAttribute: async () => "" }),
1051 setFiles,
1052 });
1053 let offered = yield* Queue.take(first.output);
1054 while (offered._tag !== "fileChooser") offered = yield* Queue.take(first.output);
1055 const second = yield* browser.attachViewer(viewerInput(tabId, true));
1056 yield* first.input({ type: "releaseControl" });
1057 yield* second.input({ type: "takeControl" });
1058 const answered = yield* browser.answerFileChooser({
1059 threadId: scope.thread.threadId,
1060 tabId,
1061 chooserId: offered.id,
1062 files: [{ name: "a.txt", mimeType: "text/plain", buffer: Buffer.from("a") }],
1063 });
1064 expect(answered).toBe(false);
1065 expect(setFiles).not.toHaveBeenCalled();
1066 }),
1067 ).pipe(Effect.provide(layer)),
1068);
1069
1070it.live("agents read a human's tab with no arguments and act on it only while nobody drives", () =>
1071 Effect.scoped(
1072 Effect.gen(function* () {
1073 const browser = yield* ServerBrowser.ServerBrowser;
1074 const broker = yield* Broker.PreviewAutomationBroker;
1075 const manager = yield* Manager.PreviewManager;
1076 yield* Effect.yieldNow;
1077 const opened = yield* manager.open({
1078 threadId: scope.thread.threadId,
1079 url: "http://localhost:5173/mine",
1080 runtime: "server",
1081 });
1082 const tabId = PreviewTabId.make(opened.tabId);
1083 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
1084 const status = yield* broker.invoke<PreviewAutomationStatus>({
1085 scope,
1086 operation: "status",
1087 input: {},
1088 });
1089 expect(status).toMatchObject({
1090 tabId,
1091 control: { owner: "human", ownedByCaller: false },
1092 });
1093 expect(status.tabs).toEqual([
1094 expect.objectContaining({ tabId, owner: "human", ownedByCaller: false, visible: true }),
1095 ]);
1096 const evaluated = yield* broker
1097 .invoke<void>({ scope, operation: "evaluate", input: { expression: "read()" } })
1098 .pipe(Effect.flip);
1099 expect(evaluated).toMatchObject({
1100 _tag: "PreviewAutomationControlInterruptedError",
1101 reason: "humanControl",
1102 });
1103 yield* broker.invoke<PreviewAutomationSnapshot>({
1104 scope,
1105 tabId,
1106 operation: "snapshot",
1107 input: {},
1108 });
1109 const refused = yield* broker
1110 .invoke<void>({
1111 scope,
1112 tabId,
1113 operation: "navigate",
1114 input: { url: "http://localhost:5173/agent" },
1115 })
1116 .pipe(Effect.flip);
1117 expect(refused).toMatchObject({
1118 _tag: "PreviewAutomationControlInterruptedError",
1119 reason: "humanControl",
1120 });
1121 yield* viewer.input({ type: "releaseControl" });
1122 const released = yield* broker.invoke<PreviewAutomationStatus>({
1123 scope,
1124 tabId,
1125 operation: "status",
1126 input: {},
1127 });
1128 expect(released.control).toMatchObject({ owner: "unclaimed", ownedByCaller: false });
1129 yield* broker.invoke({
1130 scope,
1131 tabId,
1132 operation: "navigate",
1133 input: { url: "http://localhost:5173/agent" },
1134 });
1135 expect(contexts[0]!.page.goto).toHaveBeenCalledWith(
1136 "http://localhost:5173/agent",
1137 expect.anything(),
1138 );
1139 yield* viewer.input({ type: "takeControl" });
1140 const retaken = yield* broker
1141 .invoke<void>({ scope, tabId, operation: "press", input: { key: "Enter" } })
1142 .pipe(Effect.flip);
1143 expect(retaken).toMatchObject({ reason: "humanControl" });
1144 }),
1145 ).pipe(Effect.provide(layer)),
1146);
1147
1148it.live("a session's own tab stays its default while other sessions' tabs are listed", () =>
1149 Effect.scoped(
1150 Effect.gen(function* () {
1151 const { broker, tabId } = yield* ready;
1152 const other = yield* broker.invoke<PreviewAutomationStatus>({
1153 scope: asSession("agent-b"),
1154 operation: "open",
1155 input: { reuseExistingTab: false, show: false },
1156 });
1157 const status = yield* broker.invoke<PreviewAutomationStatus>({
1158 scope,
1159 operation: "status",
1160 input: {},
1161 });
1162 expect(status.tabId).toBe(tabId);
1163 expect(status.tabs).toEqual(
1164 expect.arrayContaining([
1165 expect.objectContaining({ tabId, owner: "agent", ownedByCaller: true }),
1166 expect.objectContaining({ tabId: other.tabId, owner: "agent", ownedByCaller: false }),
1167 ]),
1168 );
1169 }),
1170 ).pipe(Effect.provide(layer)),
1171);
1172
1173it.live(
1174 "preview_open picks a reported profile by id or name and defaults to the reported one",
1175 () =>
1176 Effect.scoped(
1177 Effect.gen(function* () {
1178 const browser = yield* ServerBrowser.ServerBrowser;
1179 const broker = yield* Broker.PreviewAutomationBroker;
1180 const manager = yield* Manager.PreviewManager;
1181 yield* Effect.yieldNow;
1182 yield* browser.reportProfiles({
1183 profiles: [{ id: "profile-work", name: "Work", kind: "persistent" }],
1184 defaultProfileId: "profile-work",
1185 });
1186 const openWith = (profileId?: string) =>
1187 broker.invoke<PreviewAutomationStatus>({
1188 scope,
1189 operation: "open",
1190 input: {
1191 reuseExistingTab: false,
1192 show: false,
1193 ...(profileId === undefined ? {} : { profileId }),
1194 },
1195 });
1196 const byDefault = yield* openWith();
1197 const byName = yield* openWith("WORK");
1198 const byId = yield* openWith("incognito");
1199 const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
1200 const profileOf = (tabId: string | null) =>
1201 sessions.find((session) => session.tabId === tabId)?.profileId;
1202 expect(profileOf(byDefault.tabId)).toBe("profile-work");
1203 expect(profileOf(byName.tabId)).toBe("profile-work");
1204 expect(profileOf(byId.tabId)).toBe("incognito");
1205 expect(contextRequests).toEqual([
1206 { profileId: "profile-work", isolated: false },
1207 { profileId: "profile-work", isolated: false },
1208 { profileId: "incognito", isolated: true },
1209 ]);
1210 expect(byDefault).toMatchObject({
1211 defaultProfileId: "profile-work",
1212 profiles: [
1213 { id: "default", name: "Default" },
1214 { id: "incognito", name: "Incognito", incognito: true },
1215 { id: "profile-work", name: "Work" },
1216 ],
1217 });
1218 const unknown = yield* openWith("Personal").pipe(Effect.flip);
1219 expect(unknown).toMatchObject({
1220 _tag: "PreviewAutomationExecutionError",
1221 reason:
1222 'No browser profile is named "Personal". Use one of: Default (id default), Incognito (id incognito), Work (id profile-work).',
1223 });
1224 }),
1225 ).pipe(Effect.provide(layer)),
1226);