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

ServerBrowser.test.ts

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