Open History to see the last commit
1import * as NodeEvents from "node:events";
2import * as NodeVM from "node:vm";
3// @effect-diagnostics-next-line nodeBuiltinImport:off - Playwright download mocks perform real file operations outside the Effect runtime.
4import * as NodeFSP from "node:fs/promises";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import { it } from "@effect/vitest";
9import {
10 type BrowserRecordingFrameRate,
11 EnvironmentId,
12 PreviewTabId,
13 ProviderInstanceId,
14 ThreadId,
15 type PreviewAutomationSnapshot,
16 type PreviewAutomationStatus,
17} from "@t3tools/contracts";
18import * as Effect from "effect/Effect";
19import * as Fiber from "effect/Fiber";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Path from "effect/Path";
24import * as PubSub from "effect/PubSub";
25import * as Queue from "effect/Queue";
26import * as Stream from "effect/Stream";
27import type { BrowserContext, Page } from "playwright-core";
28import { beforeEach, expect, vi } from "vite-plus/test";
29
30import * as ServerConfig from "../config.ts";
31import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
32import * as Broker from "../mcp/PreviewAutomationBroker.ts";
33import * as DesktopChannel from "./DesktopBrowserChannel.ts";
34import * as Manager from "./Manager.ts";
35import * as 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;
76}
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 };
124}
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;
217}
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 };
259}
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.effect("a tab the desktop does not draw is marked headless, so the desktop streams it", () =>
477 Effect.scoped(
478 Effect.gen(function* () {
479 const { broker, tabId } = yield* ready;
480 const manager = yield* Manager.PreviewManager;
481 desktopRendersNext = true;
482 const desktopTab = yield* broker.invoke<PreviewAutomationStatus>({
483 scope,
484 operation: "open",
485 input: { reuseExistingTab: false, show: false },
486 });
487 const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
488 const headlessOf = (id: string | null) =>
489 sessions.find((session) => session.tabId === id)?.headless;
490
491 expect(headlessOf(tabId)).toBe(true);
492 expect(headlessOf(desktopTab.tabId)).toBeUndefined();
493 }),
494 ).pipe(Effect.provide(layer)),
495);
496
497it.live.each([
498 { method: "goto" as const, message: { type: "navigate", url: "http://10.255.255.1/" } },
499 { method: "goBack" as const, message: { type: "history", delta: -1 } },
500 { method: "goForward" as const, message: { type: "history", delta: 1 } },
501 { method: "reload" as const, message: { type: "reload" } },
502])("a pending viewer $method allows a corrected URL and text input", ({ method, message }) =>
503 Effect.scoped(
504 Effect.gen(function* () {
505 const { browser, tabId } = yield* ready;
506 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
507 yield* viewer.input({ type: "takeControl" });
508 const started = Promise.withResolvers<void>();
509 const committed = Promise.withResolvers<void>();
510 const page = contexts[0]!.page;
511 page[method].mockImplementationOnce(() => {
512 started.resolve();
513 return committed.promise;
514 });
515 const navigation = yield* viewer.input(message).pipe(Effect.forkScoped);
516 yield* Effect.promise(() => started.promise);
517 const cdp = contexts[0]!.sessions.at(-1)!;
518 const send = cdp.send.getMockImplementation()!;
519 const typed = Promise.withResolvers<void>();
520 cdp.send.mockImplementation(async (operation, input) => {
521 if (operation === "Input.insertText") typed.resolve();
522 return send(operation, input);
523 });
524 const correction = yield* Effect.gen(function* () {
525 yield* viewer.input({ type: "navigate", url: "http://localhost:5173/fixed" });
526 yield* viewer.input({ type: "text", text: "hello" });
527 }).pipe(Effect.forkScoped);
528 yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));
529 // The text reaches the page while the first navigation is still uncommitted.
530 yield* Effect.promise(() => typed.promise);
531 expect(page.goto).toHaveBeenLastCalledWith(
532 "http://localhost:5173/fixed",
533 expect.objectContaining({ waitUntil: "commit" }),
534 );
535 expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", {
536 text: "hello",
537 });
538 committed.resolve();
539 yield* Fiber.join(navigation);
540 yield* Fiber.join(correction);
541 }),
542 ).pipe(Effect.provide(layer)),
543);
544
545// The fake encoder decodes every frame at 1280x800, so 30 fps hits the bitrate floor.
546it.live.each([
547 { reports: [], frameRate: 30, bitsPerSecond: 2.5e6 },
548 { reports: [30], frameRate: 30, bitsPerSecond: 2.5e6 },
549 { reports: [60], frameRate: 60, bitsPerSecond: 1280 * 800 * 60 * 0.05 },
550 { reports: [60, undefined], frameRate: 60, bitsPerSecond: 1280 * 800 * 60 * 0.05 },
551 { reports: [60, 30], frameRate: 30, bitsPerSecond: 2.5e6 },
552] satisfies ReadonlyArray<{
553 reports: ReadonlyArray<BrowserRecordingFrameRate | undefined>;
554 frameRate: number;
555 bitsPerSecond: number;
556}>)(
557 "agent recordings encode at the last reported frame rate ($reports)",
558 ({ reports, frameRate, bitsPerSecond }) =>
559 Effect.scoped(
560 Effect.gen(function* () {
561 const { browser, broker, tabId } = yield* ready;
562 for (const recordingFrameRate of reports) {
563 yield* browser.reportProfiles({
564 profiles: [],
565 defaultProfileId: "default",
566 ...(recordingFrameRate === undefined ? {} : { recordingFrameRate }),
567 });
568 }
569 yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} });
570 expect(encoderStreams).toEqual([{ frameRate, bitsPerSecond }]);
571 }),
572 ).pipe(Effect.provide(layer)),
573);
574
575it.live("enforces provider ownership and explicit targets when a session has multiple tabs", () =>
576 Effect.scoped(
577 Effect.gen(function* () {
578 const { broker, tabId } = yield* ready;
579 const foreign = yield* broker
580 .invoke<void>({
581 scope: asSession("agent-b"),
582 tabId,
583 operation: "navigate",
584 input: { url: "http://localhost:5173/foreign" },
585 })
586 .pipe(Effect.flip);
587 expect(foreign).toMatchObject({
588 _tag: "PreviewAutomationControlInterruptedError",
589 reason: "agentMismatch",
590 });
591 expect(contexts[0]!.page.goto).not.toHaveBeenCalledWith(
592 "http://localhost:5173/foreign",
593 expect.anything(),
594 );
595 yield* broker.invoke<PreviewAutomationSnapshot>({
596 scope: asSession("agent-b"),
597 tabId,
598 operation: "snapshot",
599 input: {},
600 });
601 const foreignEvaluate = yield* broker
602 .invoke<void>({
603 scope: asSession("agent-b"),
604 tabId,
605 operation: "evaluate",
606 input: { expression: "read()" },
607 })
608 .pipe(Effect.flip);
609 expect(foreignEvaluate).toMatchObject({
610 _tag: "PreviewAutomationControlInterruptedError",
611 reason: "agentMismatch",
612 });
613 yield* broker.invoke({
614 scope,
615 operation: "open",
616 input: { reuseExistingTab: false, show: false },
617 });
618 const ambiguous = yield* broker
619 .invoke<void>({ scope, operation: "evaluate", input: { expression: "ambiguous()" } })
620 .pipe(Effect.flip);
621 expect(ambiguous).toMatchObject({
622 _tag: "PreviewAutomationControlInterruptedError",
623 reason: "tabRequired",
624 });
625 const ambiguousStop = yield* broker
626 .invoke<void>({ scope, operation: "recordingStop", input: {} })
627 .pipe(Effect.flip);
628 expect(ambiguousStop).toMatchObject({
629 _tag: "PreviewAutomationControlInterruptedError",
630 reason: "tabRequired",
631 });
632 const explicitStop = yield* broker
633 .invoke<void>({ scope, tabId, operation: "recordingStop", input: {} })
634 .pipe(Effect.flip);
635 expect(explicitStop).toMatchObject({
636 _tag: "PreviewAutomationExecutionError",
637 cause: { _tag: "PreviewAutomationRecordingNotActiveError" },
638 });
639 const result = yield* broker.invoke({
640 scope,
641 tabId,
642 operation: "evaluate",
643 input: { expression: "owned()" },
644 });
645 expect(result).toBe("evaluated");
646 expect(contexts).toHaveLength(2);
647 }),
648 ).pipe(Effect.provide(layer)),
649);
650
651it.live("streams to a read-only viewer without allowing takeover, input, or viewport changes", () =>
652 Effect.scoped(
653 Effect.gen(function* () {
654 const { browser, tabId } = yield* ready;
655 const viewer = yield* browser.attachViewer(viewerInput(tabId, false));
656 const page = contexts[0]!.page;
657 page.setViewportSize.mockClear();
658 const session = contexts[0]!.sessions.at(-1)!;
659 session.send.mockClear();
660 for (const message of [
661 { type: "takeControl" },
662 { type: "key", action: "down", key: "a", text: "a" },
663 { type: "resize", width: 390, height: 844 },
664 { type: "viewport", setting: { _tag: "freeform", width: 390, height: 844 } },
665 ])
666 yield* viewer.input(message);
667 expect(page.setViewportSize).not.toHaveBeenCalled();
668 expect(session.send.mock.calls.some(([method]) => method.startsWith("Input."))).toBe(false);
669 const outputs = yield* Queue.takeAll(viewer.output);
670 expect(outputs).toContainEqual(
671 expect.objectContaining({ _tag: "frame", data: Buffer.from("frame") }),
672 );
673 expect(outputs).toContainEqual(expect.objectContaining({ _tag: "viewport" }));
674 expect(outputs).toContainEqual(
675 expect.objectContaining({ _tag: "control", canOperate: false, controller: "agent" }),
676 );
677 const operator = yield* browser.attachViewer(viewerInput(tabId, true));
678 yield* operator.input({ type: "takeControl" });
679 yield* operator.input({ type: "text", text: "typed" });
680 yield* operator.input({ type: "resize", width: 390, height: 844 });
681 expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", {
682 text: "typed",
683 });
684 expect(page.setViewportSize).toHaveBeenCalledWith({ width: 390, height: 844 });
685 yield* operator.input({ type: "releaseControl" });
686 }),
687 ).pipe(Effect.provide(layer)),
688);
689
690it.live(
691 "takeover waits for the running agent and revokes snapshot refs before returning control",
692 () =>
693 Effect.scoped(
694 Effect.gen(function* () {
695 const { browser, broker, tabId } = yield* ready;
696 const snapshot = yield* broker.invoke<PreviewAutomationSnapshot>({
697 scope,
698 tabId,
699 operation: "snapshot",
700 input: {},
701 });
702 const ref = /\[ref=([^\]]+)\]/.exec(String(snapshot.accessibilityTree))![1]!;
703 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
704 const started = Promise.withResolvers<void>();
705 const finish = Promise.withResolvers<Record<string, unknown>>();
706 const session = contexts[0]!.sessions[0]!;
707 session.send.mockImplementationOnce(async () => {
708 started.resolve();
709 return finish.promise;
710 });
711 const running = yield* broker
712 .invoke({ scope, tabId, operation: "evaluate", input: { expression: "pending()" } })
713 .pipe(Effect.forkScoped);
714 yield* Effect.addFinalizer(() =>
715 Effect.sync(() => finish.resolve({ result: { value: "finished" } })),
716 );
717 yield* Effect.promise(() => started.promise);
718 const takeover = yield* viewer.input({ type: "takeControl" }).pipe(Effect.forkScoped);
719 let control = yield* Queue.take(viewer.output);
720 while (control._tag !== "control" || control.controller !== "you") {
721 control = yield* Queue.take(viewer.output);
722 }
723 const rejected = yield* broker
724 .invoke<void>({ scope, tabId, operation: "evaluate", input: { expression: "racing()" } })
725 .pipe(Effect.flip);
726 expect(rejected).toMatchObject({
727 _tag: "PreviewAutomationControlInterruptedError",
728 reason: "humanControl",
729 });
730 finish.resolve({ result: { value: "finished" } });
731 expect(yield* Fiber.join(running)).toBe("finished");
732 yield* Fiber.join(takeover);
733 yield* viewer.input({ type: "releaseControl" });
734 const stale = yield* broker
735 .invoke<void>({ scope, tabId, operation: "click", input: { locator: `aria-ref=${ref}` } })
736 .pipe(Effect.flip);
737 expect(stale._tag).toBe("PreviewAutomationInvalidSelectorError");
738 expect(contexts[0]!.page.locator).not.toHaveBeenCalled();
739 expect(
740 yield* broker.invoke({
741 scope,
742 tabId,
743 operation: "evaluate",
744 input: { expression: "resumed()" },
745 }),
746 ).toBe("evaluated");
747 }),
748 ).pipe(Effect.provide(layer)),
749);
750
751it.live("reports a pending dialog without evaluating the page and resolves it explicitly", () =>
752 Effect.scoped(
753 Effect.gen(function* () {
754 const { broker, tabId } = yield* ready;
755 const page = contexts[0]!.page;
756 yield* broker.invoke({
757 scope,
758 tabId,
759 operation: "navigate",
760 input: { url: "http://localhost:5173" },
761 });
762 const started = Promise.withResolvers<void>();
763 const resolvedEvaluation = Promise.withResolvers<Record<string, unknown>>();
764 const session = contexts[0]!.sessions[0]!;
765 const send = session.send.getMockImplementation()!;
766 session.send.mockImplementation(async (method, input) => {
767 if (method !== "Runtime.evaluate") return send(method, input);
768 started.resolve();
769 return resolvedEvaluation.promise;
770 });
771 const blockedAction = yield* broker
772 .invoke({
773 scope,
774 tabId,
775 operation: "evaluate",
776 input: { expression: 'confirm("Delete row?")' },
777 })
778 .pipe(Effect.forkScoped);
779 yield* Effect.addFinalizer(() =>
780 Effect.sync(() => resolvedEvaluation.resolve({ result: { value: true } })),
781 );
782 yield* Effect.promise(() => started.promise);
783 const dialog = {
784 type: () => "confirm",
785 message: () => "Delete row?",
786 defaultValue: () => "",
787 accept: vi.fn(async () => {
788 resolvedEvaluation.resolve({ result: { value: true } });
789 }),
790 dismiss: vi.fn(async () => {}),
791 };
792 page.emit("dialog", dialog);
793 page.title.mockClear();
794 const status = yield* broker.invoke<PreviewAutomationStatus>({
795 scope,
796 tabId,
797 operation: "status",
798 input: {},
799 });
800 expect(status.dialog).toMatchObject({ type: "confirm", message: "Delete row?" });
801 expect(page.title).not.toHaveBeenCalled();
802 expect(dialog.dismiss).not.toHaveBeenCalled();
803 const reuse = yield* broker
804 .invoke<void>({
805 scope,
806 tabId,
807 operation: "open",
808 input: { url: "http://localhost:5173/other" },
809 })
810 .pipe(Effect.flip);
811 expect(reuse).toMatchObject({
812 _tag: "PreviewAutomationControlInterruptedError",
813 reason: "dialogPending",
814 });
815 expect(page.goto).toHaveBeenCalledTimes(1);
816 yield* broker.invoke({ scope, tabId, operation: "dialog", input: { accept: true } });
817 expect(yield* Fiber.join(blockedAction)).toBe(true);
818 expect(dialog.accept).toHaveBeenCalledTimes(1);
819 const resolved = yield* broker.invoke<PreviewAutomationStatus>({
820 scope,
821 tabId,
822 operation: "status",
823 input: {},
824 });
825 expect(resolved.dialog).toBeNull();
826 }),
827 ).pipe(Effect.provide(layer)),
828);
829
830it.live("a tab opened to a file the browser cannot show reports the file to download", () =>
831 Effect.scoped(
832 Effect.gen(function* () {
833 const browser = yield* ServerBrowser.ServerBrowser;
834 const manager = yield* Manager.PreviewManager;
835 const events = yield* manager.subscribeEvents;
836 yield* Effect.yieldNow;
837 const opened = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" });
838 const viewer = yield* browser.attachViewer(viewerInput(opened.tabId, true));
839 const page = contexts[0]!.page;
840 const pdf = "https://example.com/paper.pdf";
841 const request = { url: () => pdf, method: () => "GET", isNavigationRequest: () => true };
842 page.emit("requestfailed", {
843 ...request,
844 frame: () => page,
845 failure: () => ({ errorText: "net::ERR_ABORTED" }),
846 });
847 const saved = yield* Queue.unbounded<string>();
848 const written = Promise.withResolvers<void>();
849 page.emit("download", {
850 failure: async () => null,
851 delete: async () => {
852 // A new navigation during cleanup must not erase the settled download status.
853 page.emit("request", {
854 url: () => "https://example.com/next",
855 method: () => "GET",
856 isNavigationRequest: () => true,
857 frame: () => page,
858 });
859 },
860 saveAs: (path: string) => {
861 Queue.offerUnsafe(saved, path);
862 return written.promise;
863 },
864 suggestedFilename: () => "paper.pdf",
865 url: () => pdf,
866 });
867 const fs = yield* FileSystem.FileSystem;
868 yield* fs.writeFileString(yield* Queue.take(saved), "%PDF");
869 written.resolve();
870 const received = [];
871 let status;
872 do {
873 status = yield* PubSub.take(events);
874 received.push(status);
875 } while (
876 status.type !== "navigated" ||
877 status.snapshot.navStatus._tag !== "Loading" ||
878 status.snapshot.navStatus.url !== "https://example.com/next"
879 );
880 expect(received).toContainEqual(
881 expect.objectContaining({
882 type: "failed",
883 url: pdf,
884 download: { id: expect.any(String), fileName: "paper.pdf" },
885 }),
886 );
887 expect((yield* Queue.clear(viewer.output)).some((item) => item._tag === "download")).toBe(
888 false,
889 );
890 }),
891 ).pipe(Effect.provide(layer)),
892);
893
894it.live(
895 "a late failure from a request that predates tracking leaves a newer navigation loading",
896 () =>
897 Effect.scoped(
898 Effect.gen(function* () {
899 const { broker, tabId } = yield* ready;
900 const page = contexts[0]!.page;
901 const navigation = (url: string) => ({
902 url: () => url,
903 method: () => "GET",
904 isNavigationRequest: () => true,
905 frame: () => page,
906 failure: () => ({ errorText: "net::ERR_CONNECTION_REFUSED" }),
907 });
908 page.emit("request", navigation("https://example.com/next"));
909 // A popup's first request can start before the tab listens for requests.
910 page.emit("requestfailed", navigation("https://example.com/first"));
911 const status = yield* broker.invoke<PreviewAutomationStatus>({
912 scope,
913 tabId,
914 operation: "status",
915 input: {},
916 });
917 expect(status.loading).toBe(true);
918 }),
919 ).pipe(Effect.provide(layer)),
920);
921
922it.live("only the controlling viewer's copy and cut keys reach its clipboard", () =>
923 Effect.scoped(
924 Effect.gen(function* () {
925 const { browser, tabId } = yield* ready;
926 const watcher = yield* browser.attachViewer(viewerInput(tabId, false));
927 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
928 yield* viewer.input({ type: "takeControl" });
929 const clipboard = (queue: typeof viewer.output) =>
930 Queue.clear(queue).pipe(
931 Effect.map((items) => items.filter((item) => item._tag === "clipboard")),
932 );
933 pageCopy = "unprompted";
934 yield* viewer.input({ type: "mouse", action: "move", x: 10, y: 10 });
935 yield* viewer.input({ type: "wheel", x: 10, y: 10, deltaY: 40 });
936 yield* viewer.input({ type: "key", action: "down", key: "v", code: "KeyV", modifiers: 4 });
937 yield* viewer.input({ type: "unknown" });
938 expect(yield* clipboard(viewer.output)).toEqual([]);
939 keyCopy = "copied";
940 yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
941 const cdp = contexts[0]!.sessions.at(-1)!;
942 expect(cdp.send).toHaveBeenCalledWith(
943 "Input.dispatchKeyEvent",
944 expect.objectContaining({ key: "c", commands: ["copy"] }),
945 );
946 expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "copied" }]);
947 keyCopy = "cut";
948 yield* viewer.input({ type: "key", action: "down", key: "x", code: "KeyX", modifiers: 2 });
949 expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "cut" }]);
950 pageCopy = "left over";
951 keyCopy = "";
952 yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
953 expect(yield* clipboard(viewer.output)).toEqual([]);
954 expect(yield* clipboard(watcher.output)).toEqual([]);
955 }),
956 ).pipe(Effect.provide(layer)),
957);
958
959it.live.each([false, true])(
960 "a page download is saved, offered to the controller, and listed for the agent (delete fails: %s)",
961 (deleteFails) =>
962 Effect.scoped(
963 Effect.gen(function* () {
964 const { browser, broker, tabId } = yield* ready;
965 const page = contexts[0]!.page;
966 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
967 yield* viewer.input({ type: "takeControl" });
968 yield* Queue.clear(viewer.output);
969 const fs = yield* FileSystem.FileSystem;
970 const original = `${yield* fs.makeTempDirectoryScoped()}/chromium-download`;
971 yield* fs.writeFileString(original, "a,b");
972 const released = Promise.withResolvers<void>();
973 page.emit("download", {
974 failure: async () => null,
975 delete: async () => {
976 try {
977 if (deleteFails) throw new Error("context closed");
978 await NodeFSP.rm(original);
979 } finally {
980 released.resolve();
981 }
982 },
983 saveAs: (path: string) => NodeFSP.copyFile(original, path),
984 suggestedFilename: () => "report.csv",
985 url: () => 'data:text/csv;charset="a,b",a b\'c',
986 });
987 let offered = yield* Queue.take(viewer.output);
988 while (offered._tag !== "download") offered = yield* Queue.take(viewer.output);
989 expect(offered).toMatchObject({ _tag: "download", fileName: "report.csv", sizeBytes: 3 });
990 yield* Effect.promise(() => released.promise);
991 expect(yield* fs.exists(original)).toBe(deleteFails);
992 const file = yield* browser.openDownload({
993 threadId: scope.thread.threadId,
994 tabId,
995 downloadId: offered.id,
996 });
997 expect(Option.isSome(file) && file.value.fileName).toBe("report.csv");
998 expect(yield* fs.readFileString(Option.getOrThrow(file).path)).toBe("a,b");
999 if ((yield* HostProcess.Platform) !== "win32") {
1000 expect((yield* fs.stat(Option.getOrThrow(file).path)).mode & 0o777).toBe(0o600);
1001 }
1002 const status = yield* broker.invoke<PreviewAutomationStatus>({
1003 scope,
1004 tabId,
1005 operation: "status",
1006 input: {},
1007 });
1008 expect(status.downloads).toEqual([
1009 expect.objectContaining({
1010 fileName: "report.csv",
1011 sizeBytes: 3,
1012 url: "data:text/csv,…",
1013 }),
1014 ]);
1015 expect(
1016 Option.isNone(
1017 yield* browser.openDownload({
1018 threadId: scope.thread.threadId,
1019 tabId,
1020 downloadId: "guess",
1021 }),
1022 ),
1023 ).toBe(true);
1024 if ((yield* HostProcess.Platform) !== "win32") {
1025 const folder = (yield* Path.Path).dirname(Option.getOrThrow(file).path);
1026 yield* fs.chmod(folder, 0o755);
1027 page.emit("download", {
1028 failure: async () => null,
1029 delete: async () => {},
1030 saveAs: (path: string) => NodeFSP.writeFile(path, "c"),
1031 suggestedFilename: () => "again.csv",
1032 url: () => "https://example.test/again.csv",
1033 });
1034 let again = yield* Queue.take(viewer.output);
1035 while (again._tag !== "download") again = yield* Queue.take(viewer.output);
1036 expect((yield* fs.stat(folder)).mode & 0o777).toBe(0o700);
1037 }
1038 }),
1039 ).pipe(Effect.provide(layer)),
1040);
1041
1042it.live.each(["save failed", "oversized"])(
1043 "a rejected download releases the original and keeps no saved copy (%s)",
1044 (outcome) =>
1045 Effect.scoped(
1046 Effect.gen(function* () {
1047 const { broker, tabId } = yield* ready;
1048 const fs = yield* FileSystem.FileSystem;
1049 const original = `${yield* fs.makeTempDirectoryScoped()}/chromium-download`;
1050 yield* fs.writeFileString(original, "a,b");
1051 let savedPath: string | undefined;
1052 const released = Promise.withResolvers<void>();
1053 contexts[0]!.page.emit("download", {
1054 failure: async () => null,
1055 delete: async () => {
1056 await NodeFSP.rm(original);
1057 released.resolve();
1058 },
1059 saveAs: async (path: string) => {
1060 savedPath = path;
1061 await NodeFSP.copyFile(original, path);
1062 if (outcome === "save failed") throw new Error("save interrupted");
1063 // A sparse file exercises the size limit without writing a GiB of data.
1064 await NodeFSP.truncate(path, 1024 ** 3 + 1);
1065 },
1066 suggestedFilename: () => "report.csv",
1067 url: () => "blob:http://localhost:5173/1",
1068 });
1069 yield* Effect.promise(() => released.promise);
1070 expect(yield* fs.exists(original)).toBe(false);
1071 if (savedPath !== undefined) expect(yield* fs.exists(savedPath)).toBe(false);
1072 const status = yield* broker.invoke<PreviewAutomationStatus>({
1073 scope,
1074 tabId,
1075 operation: "status",
1076 input: {},
1077 });
1078 expect(status.downloads).toEqual([]);
1079 }),
1080 ).pipe(Effect.provide(layer)),
1081);
1082
1083it.live("a page's file picker goes to the controller and takes its uploaded files", () =>
1084 Effect.scoped(
1085 Effect.gen(function* () {
1086 const { browser, tabId } = yield* ready;
1087 const page = contexts[0]!.page;
1088 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
1089 yield* viewer.input({ type: "takeControl" });
1090 const setFiles = vi.fn(async (_files: unknown) => {});
1091 page.emit("filechooser", {
1092 isMultiple: () => false,
1093 element: () => ({ getAttribute: async () => ".csv" }),
1094 setFiles,
1095 });
1096 let offered = yield* Queue.take(viewer.output);
1097 while (offered._tag !== "fileChooser") offered = yield* Queue.take(viewer.output);
1098 expect(offered).toMatchObject({ multiple: false, accept: ".csv" });
1099 const file = (name: string) => ({ name, mimeType: "text/csv", buffer: Buffer.from(name) });
1100 const answer = (chooserId: string) =>
1101 browser.answerFileChooser({
1102 threadId: scope.thread.threadId,
1103 tabId,
1104 chooserId,
1105 files: [file("a.csv"), file("b.csv")],
1106 });
1107 expect(yield* answer("other")).toBe(false);
1108 expect(yield* answer(offered.id)).toBe(true);
1109 expect(setFiles).toHaveBeenCalledExactlyOnceWith([file("a.csv")]);
1110 let closed = yield* Queue.take(viewer.output);
1111 while (closed._tag !== "fileChooserClosed") closed = yield* Queue.take(viewer.output);
1112 expect(closed.id).toBe(offered.id);
1113 expect(yield* answer(offered.id)).toBe(false);
1114 }),
1115 ).pipe(Effect.provide(layer)),
1116);
1117
1118it.live("only the current controller can answer a file picker", () =>
1119 Effect.scoped(
1120 Effect.gen(function* () {
1121 const { browser, tabId } = yield* ready;
1122 const first = yield* browser.attachViewer(viewerInput(tabId, true));
1123 yield* first.input({ type: "takeControl" });
1124 const setFiles = vi.fn(async (_files: unknown) => {});
1125 contexts[0]!.page.emit("filechooser", {
1126 isMultiple: () => false,
1127 element: () => ({ getAttribute: async () => "" }),
1128 setFiles,
1129 });
1130 let offered = yield* Queue.take(first.output);
1131 while (offered._tag !== "fileChooser") offered = yield* Queue.take(first.output);
1132 const second = yield* browser.attachViewer(viewerInput(tabId, true));
1133 yield* first.input({ type: "releaseControl" });
1134 yield* second.input({ type: "takeControl" });
1135 const answered = yield* browser.answerFileChooser({
1136 threadId: scope.thread.threadId,
1137 tabId,
1138 chooserId: offered.id,
1139 files: [{ name: "a.txt", mimeType: "text/plain", buffer: Buffer.from("a") }],
1140 });
1141 expect(answered).toBe(false);
1142 expect(setFiles).not.toHaveBeenCalled();
1143 }),
1144 ).pipe(Effect.provide(layer)),
1145);
1146
1147it.live("agents read a human's tab with no arguments and act on it only while nobody drives", () =>
1148 Effect.scoped(
1149 Effect.gen(function* () {
1150 const browser = yield* ServerBrowser.ServerBrowser;
1151 const broker = yield* Broker.PreviewAutomationBroker;
1152 const manager = yield* Manager.PreviewManager;
1153 yield* Effect.yieldNow;
1154 const opened = yield* manager.open({
1155 threadId: scope.thread.threadId,
1156 url: "http://localhost:5173/mine",
1157 runtime: "server",
1158 });
1159 const tabId = PreviewTabId.make(opened.tabId);
1160 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
1161 const status = yield* broker.invoke<PreviewAutomationStatus>({
1162 scope,
1163 operation: "status",
1164 input: {},
1165 });
1166 expect(status).toMatchObject({
1167 tabId,
1168 control: { owner: "human", ownedByCaller: false },
1169 });
1170 expect(status.tabs).toEqual([
1171 expect.objectContaining({ tabId, owner: "human", ownedByCaller: false, visible: true }),
1172 ]);
1173 const evaluated = yield* broker
1174 .invoke<void>({ scope, operation: "evaluate", input: { expression: "read()" } })
1175 .pipe(Effect.flip);
1176 expect(evaluated).toMatchObject({
1177 _tag: "PreviewAutomationControlInterruptedError",
1178 reason: "humanControl",
1179 });
1180 yield* broker.invoke<PreviewAutomationSnapshot>({
1181 scope,
1182 tabId,
1183 operation: "snapshot",
1184 input: {},
1185 });
1186 const refused = yield* broker
1187 .invoke<void>({
1188 scope,
1189 tabId,
1190 operation: "navigate",
1191 input: { url: "http://localhost:5173/agent" },
1192 })
1193 .pipe(Effect.flip);
1194 expect(refused).toMatchObject({
1195 _tag: "PreviewAutomationControlInterruptedError",
1196 reason: "humanControl",
1197 });
1198 yield* viewer.input({ type: "releaseControl" });
1199 const released = yield* broker.invoke<PreviewAutomationStatus>({
1200 scope,
1201 tabId,
1202 operation: "status",
1203 input: {},
1204 });
1205 expect(released.control).toMatchObject({ owner: "unclaimed", ownedByCaller: false });
1206 yield* broker.invoke({
1207 scope,
1208 tabId,
1209 operation: "navigate",
1210 input: { url: "http://localhost:5173/agent" },
1211 });
1212 expect(contexts[0]!.page.goto).toHaveBeenCalledWith(
1213 "http://localhost:5173/agent",
1214 expect.anything(),
1215 );
1216 yield* viewer.input({ type: "takeControl" });
1217 const retaken = yield* broker
1218 .invoke<void>({ scope, tabId, operation: "press", input: { key: "Enter" } })
1219 .pipe(Effect.flip);
1220 expect(retaken).toMatchObject({ reason: "humanControl" });
1221 }),
1222 ).pipe(Effect.provide(layer)),
1223);
1224
1225it.live("a session's own tab stays its default while other sessions' tabs are listed", () =>
1226 Effect.scoped(
1227 Effect.gen(function* () {
1228 const { broker, tabId } = yield* ready;
1229 const other = yield* broker.invoke<PreviewAutomationStatus>({
1230 scope: asSession("agent-b"),
1231 operation: "open",
1232 input: { reuseExistingTab: false, show: false },
1233 });
1234 const status = yield* broker.invoke<PreviewAutomationStatus>({
1235 scope,
1236 operation: "status",
1237 input: {},
1238 });
1239 expect(status.tabId).toBe(tabId);
1240 expect(status.tabs).toEqual(
1241 expect.arrayContaining([
1242 expect.objectContaining({ tabId, owner: "agent", ownedByCaller: true }),
1243 expect.objectContaining({ tabId: other.tabId, owner: "agent", ownedByCaller: false }),
1244 ]),
1245 );
1246 }),
1247 ).pipe(Effect.provide(layer)),
1248);
1249
1250it.live(
1251 "preview_open picks a reported profile by id or name and defaults to the reported one",
1252 () =>
1253 Effect.scoped(
1254 Effect.gen(function* () {
1255 const browser = yield* ServerBrowser.ServerBrowser;
1256 const broker = yield* Broker.PreviewAutomationBroker;
1257 const manager = yield* Manager.PreviewManager;
1258 yield* Effect.yieldNow;
1259 yield* browser.reportProfiles({
1260 profiles: [{ id: "profile-work", name: "Work", kind: "persistent" }],
1261 defaultProfileId: "profile-work",
1262 });
1263 const openWith = (profileId?: string) =>
1264 broker.invoke<PreviewAutomationStatus>({
1265 scope,
1266 operation: "open",
1267 input: {
1268 reuseExistingTab: false,
1269 show: false,
1270 ...(profileId === undefined ? {} : { profileId }),
1271 },
1272 });
1273 const byDefault = yield* openWith();
1274 const byName = yield* openWith("WORK");
1275 const byId = yield* openWith("incognito");
1276 const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
1277 const profileOf = (tabId: string | null) =>
1278 sessions.find((session) => session.tabId === tabId)?.profileId;
1279 expect(profileOf(byDefault.tabId)).toBe("profile-work");
1280 expect(profileOf(byName.tabId)).toBe("profile-work");
1281 expect(profileOf(byId.tabId)).toBe("incognito");
1282 expect(contextRequests).toEqual([
1283 { profileId: "profile-work", isolated: false },
1284 { profileId: "profile-work", isolated: false },
1285 { profileId: "incognito", isolated: true },
1286 ]);
1287 expect(byDefault).toMatchObject({
1288 defaultProfileId: "profile-work",
1289 profiles: [
1290 { id: "default", name: "Default" },
1291 { id: "incognito", name: "Incognito", incognito: true },
1292 { id: "profile-work", name: "Work" },
1293 ],
1294 });
1295 const unknown = yield* openWith("Personal").pipe(Effect.flip);
1296 expect(unknown).toMatchObject({
1297 _tag: "PreviewAutomationExecutionError",
1298 reason:
1299 'No browser profile is named "Personal". Use one of: Default (id default), Incognito (id incognito), Work (id profile-work).',
1300 });
1301 }),
1302 ).pipe(Effect.provide(layer)),
1303);