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

ServerBrowser.test.ts

1,280 lines48.7 KB

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