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

ServerBrowser.test.ts

1,150 lines44.0 KB

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