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

ServerBrowser.test.ts

1,092 lines44.0 KB

1import * as NodeEvents from "node:events";
2​
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { it } from "@effect/vitest";
5import {
6 EnvironmentId,
7 PreviewTabId,
8 ProviderInstanceId,
9 ThreadId,
10 type PreviewAutomationSnapshot,
11 type PreviewAutomationStatus,
12} from "@t3tools/contracts";
13import * as Clock from "effect/Clock";
14import * as Effect from "effect/Effect";
15import * as Fiber from "effect/Fiber";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Queue from "effect/Queue";
20import * as Stream from "effect/Stream";
21import type { BrowserContext, Page } from "playwright-core";
22import { beforeEach, expect, vi } from "vite-plus/test";
23​
24import * as ServerConfig from "../config.ts";
25import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
26import * as Broker from "../mcp/PreviewAutomationBroker.ts";
27import * as DesktopChannel from "./DesktopBrowserChannel.ts";
28import * as Manager from "./Manager.ts";
29import * as ServerBrowser from "./ServerBrowser.ts";
30import * as PreviewBrowser from "./PreviewBrowser.ts";
31​
32// Keep the manager, broker, ownership, refs, and viewer paths real; replace Chromium I/O only.
33vi.mock("./ServerBrowserContexts.ts", () => ({
34 ServerBrowserContexts: class {
35 private readonly onClose: ((context: BrowserContext) => void) | undefined;
36 constructor(options: { onContextClose?: (context: BrowserContext) => void }) {
37 this.onClose = options.onContextClose;
38 }
39 async contextFor() {
40 if (contextFailure) throw contextFailure;
41 await contextGate?.promise;
42 const context = makeContext(this.onClose);
43 contexts.push(context);
44 return context as unknown as BrowserContext;
45 }
46 async scratchPage() {
47 return makeContext().page as unknown as Page;
48 }
49 async connectDesktopPage(endpoint: string) {
50 const context = makeContext();
51 desktopConnections.push({ endpoint, context });
52 return { browser: { close: async () => {} }, page: context.page as unknown as Page };
53 }
54 async close() {
55 for (const context of contexts) await context.close();
56 }
57 },
58}));
59​
60function makeSession() {
61 return {
62 on: vi.fn(),
63 detach: vi.fn(async () => {}),
64 send: vi.fn(async (method: string, _input?: unknown): Promise<Record<string, unknown>> => {
65 if (method === "Page.getNavigationHistory") return { currentIndex: 0, entries: [{}] };
66 if (method === "Page.getLayoutMetrics") return { cssVisualViewport: { pageX: 0, pageY: 0 } };
67 if (method === "Page.captureScreenshot") return { data: "ZnJhbWU=" };
68 return { result: { value: "evaluated" } };
69 }),
70 };
72​
73function makeContext(onClose?: (context: BrowserContext) => void) {
74 const events = new NodeEvents.EventEmitter();
75 const sessions: ReturnType<typeof makeSession>[] = [];
76 let url = "about:blank";
77 let viewport = { width: 1280, height: 800 };
78 let closed = false;
79 let contextClosed = false;
80 const page = {
81 on: (name: string, callback: (...args: unknown[]) => void) => events.on(name, callback),
82 once: (name: string, callback: (...args: unknown[]) => void) => events.once(name, callback),
83 off: (name: string, callback: (...args: unknown[]) => void) => events.off(name, callback),
84 emit: (name: string, ...args: unknown[]) => events.emit(name, ...args),
85 emitAsync: (name: string, ...args: unknown[]) =>
86 Promise.all(events.listeners(name).map((listener) => listener(...args))),
87 setDefaultTimeout: vi.fn(),
88 setDefaultNavigationTimeout: vi.fn(),
89 context: () => context,
90 mainFrame: () => page,
91 url: () => url,
92 title: vi.fn(async () => "test page"),
93 viewportSize: () => viewport,
94 setViewportSize: vi.fn(async (size: typeof viewport) => {
95 viewport = size;
96 }),
97 goto: vi.fn(async (next: string) => {
98 url = next;
99 events.emit("load");
100 }),
101 goBack: vi.fn(async () => {}),
102 goForward: vi.fn(async () => {}),
103 reload: vi.fn(async () => {}),
104 emulateMedia: vi.fn(async () => {}),
105 waitForLoadState: vi.fn(async () => {}),
106 evaluate: vi.fn(async () => ({
107 url,
108 title: "test page",
109 loading: false,
110 visibleText: "delete",
111 interactiveElements: [],
112 })),
113 ariaSnapshot: vi.fn(async () => '- button "delete" [ref=e1]'),
114 locator: vi.fn(() => {
115 throw new Error("Unexpected locator action");
116 }),
117 isClosed: () => closed,
118 close: vi.fn(async () => {
119 if (!closed) {
120 closed = true;
121 events.emit("close");
122 }
123 }),
124 };
125 const context = {
126 page,
127 sessions,
128 newPage: async () => page as unknown as Page,
129 grantPermissions: vi.fn(async () => {}),
130 exposeBinding: vi.fn(async (_name: string, binding: ClipboardBinding) => {
131 clipboardBinding = binding;
132 }),
133 addInitScript: vi.fn(async () => {}),
134 newCDPSession: async () => {
135 const session = makeSession();
136 sessions.push(session);
137 return session;
138 },
139 close: vi.fn(async () => {
140 if (contextClosed) return;
141 contextClosed = true;
142 await page.close();
143 onClose?.(context as unknown as BrowserContext);
144 }),
145 };
146 return context;
148​
149const contexts: ReturnType<typeof makeContext>[] = [];
150let contextGate: PromiseWithResolvers<void> | null = null;
151type ClipboardBinding = (source: { page: unknown }, text: unknown) => void;
152let clipboardBinding: ClipboardBinding | null = null;
153let contextFailure: Error | null = null;
154/** Server tabs the fake desktop renders, and the endpoints the server connected to. */
155let desktopRendersNext = false;
156/** Pages the fake desktop takes back; the channel's detached stream emits them. */
157const desktopDetaches = new NodeEvents.EventEmitter();
158const desktopTabs = new Set<string>();
159const desktopRenders = (tabId: string) => {
160 if (desktopRendersNext) {
161 desktopRendersNext = false;
162 desktopTabs.add(tabId);
163 }
164 return desktopTabs.has(tabId);
165};
166const releasedDesktopTabs: Array<string> = [];
167const desktopConnections: Array<{ endpoint: string; context: ReturnType<typeof makeContext> }> = [];
168const testThread = {
169 threadId: ThreadId.make("browser-test-thread"),
170 providerSessionId: "agent-a",
171 providerInstanceId: ProviderInstanceId.make("codex"),
172};
173const scope = {
174 environmentId: EnvironmentId.make("browser-test-environment"),
175 thread: testThread,
176 client: undefined,
177 requestNamespace: "browser-test",
178 capabilities: new Set(["preview"] as const),
179 issuedAt: 1,
180};
181/** The same thread, as another of its agent sessions. */
182const asSession = (providerSessionId: string) => ({
183 ...scope,
184 thread: { ...testThread, providerSessionId },
185});
186const dependencies = Layer.mergeAll(
187 Broker.layer,
188 Manager.layer,
189 Layer.succeed(ServerEnvironment.ServerEnvironment, {
190 getEnvironmentId: Effect.succeed(scope.environmentId),
191 getDescriptor: Effect.die("unused descriptor"),
192 }),
193 Layer.succeed(PreviewBrowser.PreviewBrowser, {
194 executable: Effect.die("mock Chromium does not need an executable"),
195 installed: Effect.die("mock Chromium does not need an executable"),
196 }),
197 Layer.succeed(DesktopChannel.DesktopBrowserChannel, {
198 // Only tabs a test marks render on the desktop; the rest stay headless.
199 available: true,
200 awaitAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)),
201 detached: Stream.callback<{ threadId: string; tabId: string }>((queue) =>
202 Effect.acquireRelease(
203 Effect.sync(() => {
204 const onDetach = (key: { threadId: string; tabId: string }) =>
205 Queue.offerUnsafe(queue, key);
206 desktopDetaches.on("detach", onDetach);
207 return onDetach;
208 }),
209 (onDetach) => Effect.sync(() => desktopDetaches.off("detach", onDetach)),
210 ),
211 ),
212 isAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)),
213 endpoint: (key) =>
214 Effect.acquireRelease(Effect.succeed(`ws://desktop/${key.tabId}`), () =>
215 Effect.sync(() => releasedDesktopTabs.push(key.tabId)),
216 ),
217 pointer: () => Effect.void,
218 }),
219).pipe(
220 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-server-browser-" })),
221 Layer.provideMerge(NodeServices.layer),
222);
223const layer = ServerBrowser.layer.pipe(Layer.provideMerge(dependencies));
224const ready = Effect.gen(function* () {
225 const browser = yield* ServerBrowser.ServerBrowser;
226 const broker = yield* Broker.PreviewAutomationBroker;
227 yield* Effect.yieldNow;
228 const opened = yield* broker.invoke<PreviewAutomationStatus>({
229 scope,
230 operation: "open",
231 input: { reuseExistingTab: false, show: false },
232 });
233 const tabId = PreviewTabId.make(opened.tabId!);
234 return { browser, broker, tabId };
235});
236/** Fills a viewer's output the way a viewer that stopped reading leaves it. */
237const stallViewer = (
238 viewer: ServerBrowser.ServerBrowserViewer,
239 item: ServerBrowser.ServerBrowserViewerOutput,
240) => {
241 // The service hands out the read side of a queue it also writes to.
242 const output = viewer.output as unknown as Queue.Queue<ServerBrowser.ServerBrowserViewerOutput>;
243 while (Queue.offerUnsafe(output, item));
244};
245const viewerInput = (tabId: string, canOperate: boolean) => ({
246 threadId: scope.thread.threadId,
247 tabId,
248 canOperate,
249 maxWidth: 1280,
250 maxHeight: 800,
251 quality: 70,
252});
253​
254beforeEach(() => {
255 contexts.length = 0;
256 contextGate = null;
257 contextFailure = null;
258 desktopTabs.clear();
259 desktopRendersNext = false;
260 releasedDesktopTabs.length = 0;
261 desktopConnections.length = 0;
262});
263​
264it.live("readiness none responds immediately but takeover input waits for navigation commit", () =>
265 Effect.scoped(
266 Effect.gen(function* () {
267 const { browser, broker, tabId } = yield* ready;
268 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
269 const committed = Promise.withResolvers<void>();
270 const events: string[] = [];
271 contexts[0]!.page.goto.mockImplementationOnce(async () => {
272 await committed.promise;
273 events.push("navigation committed");
274 });
275 yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));
276 const response = yield* broker.invoke<PreviewAutomationStatus>({
277 scope,
278 tabId,
279 operation: "navigate",
280 input: { url: "http://localhost:5173/next", readiness: "none" },
281 });
282 expect(response.available).toBe(true);
283 expect(events).toEqual([]);
284 yield* Queue.clear(viewer.output);
285 const takeover = yield* viewer.input({ type: "takeControl" }).pipe(Effect.forkScoped);
286 let control = yield* Queue.take(viewer.output);
287 while (control._tag !== "control" || control.controller !== "you") {
288 control = yield* Queue.take(viewer.output);
289 }
290 const cdp = contexts[0]!.sessions.at(-1)!;
291 const send = cdp.send.getMockImplementation()!;
292 cdp.send.mockImplementation(async (operation, input) => {
293 if (operation === "Input.insertText") events.push("human typed");
294 return send(operation, input);
295 });
296 const typing = yield* viewer.input({ type: "text", text: "hello" }).pipe(Effect.forkScoped);
297 yield* broker.invoke({ scope, tabId, operation: "status", input: {} });
298 expect(events).toEqual([]);
299 committed.resolve();
300 yield* Fiber.join(takeover);
301 yield* Fiber.join(typing);
302 expect(events).toEqual(["navigation committed", "human typed"]);
303 }),
304 ).pipe(Effect.provide(layer)),
305);
306​
307it.live.each([
308 { method: "goto" as const, message: { type: "navigate", url: "http://localhost:5173/next" } },
309 { method: "goBack" as const, message: { type: "history", delta: -1 } },
310 { method: "goForward" as const, message: { type: "history", delta: 1 } },
311 { method: "reload" as const, message: { type: "reload" } },
312])("release waits for viewer $method to commit before agent actions", ({ method, message }) =>
313 Effect.scoped(
314 Effect.gen(function* () {
315 const { browser, broker, tabId } = yield* ready;
316 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
317 yield* viewer.input({ type: "takeControl" });
318 yield* Queue.clear(viewer.output);
319 const started = Promise.withResolvers<void>();
320 const committed = Promise.withResolvers<void>();
321 const events: string[] = [];
322 contexts[0]!.page[method].mockImplementationOnce(async () => {
323 started.resolve();
324 await committed.promise;
325 events.push("navigation committed");
326 });
327 const navigate = yield* viewer.input(message).pipe(Effect.forkScoped);
328 yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));
329 yield* Effect.promise(() => started.promise);
330 const releasing = yield* viewer.input({ type: "releaseControl" }).pipe(Effect.forkScoped);
331 let control = yield* Queue.take(viewer.output);
332 while (control._tag !== "control" || control.controller !== "agent") {
333 control = yield* Queue.take(viewer.output);
334 }
335 const cdp = contexts[0]!.sessions[0]!;
336 const send = cdp.send.getMockImplementation()!;
337 cdp.send.mockImplementation(async (operation, input) => {
338 if (operation === "Runtime.evaluate") events.push("agent acted");
339 return send(operation, input);
340 });
341 const resumed = yield* broker
342 .invoke({
343 scope,
344 tabId,
345 operation: "evaluate",
346 input: { expression: "resumed()" },
347 })
348 .pipe(Effect.forkScoped);
349 yield* broker.invoke({ scope, tabId, operation: "status", input: {} });
350 expect(events).toEqual([]);
351 committed.resolve();
352 yield* Fiber.join(navigate);
353 yield* Fiber.join(releasing);
354 yield* Fiber.join(resumed);
355 expect(events).toEqual(["navigation committed", "agent acted"]);
356 const calls = contexts[0]!.page[method].mock.calls;
357 expect(calls[0]?.at(-1)).toMatchObject({ waitUntil: "commit", timeout: 15_000 });
358 }),
359 ).pipe(Effect.provide(layer)),
360);
361​
362it.live("enforces provider ownership and explicit targets when a session has multiple tabs", () =>
363 Effect.scoped(
364 Effect.gen(function* () {
365 const { broker, tabId } = yield* ready;
366 const foreign = yield* broker
367 .invoke<void>({
368 scope: asSession("agent-b"),
369 tabId,
370 operation: "evaluate",
371 input: { expression: "foreign()" },
372 })
373 .pipe(Effect.flip);
374 expect(foreign).toMatchObject({
375 _tag: "PreviewAutomationControlInterruptedError",
376 reason: "agentMismatch",
377 });
378 expect(contexts[0]!.sessions[0]!.send).not.toHaveBeenCalledWith(
379 "Runtime.evaluate",
380 expect.anything(),
381 );
382 yield* broker.invoke({
383 scope,
384 operation: "open",
385 input: { reuseExistingTab: false, show: false },
386 });
387 const ambiguous = yield* broker
388 .invoke<void>({ scope, operation: "evaluate", input: { expression: "ambiguous()" } })
389 .pipe(Effect.flip);
390 expect(ambiguous).toMatchObject({
391 _tag: "PreviewAutomationControlInterruptedError",
392 reason: "tabRequired",
393 });
394 const ambiguousStop = yield* broker
395 .invoke<void>({ scope, operation: "recordingStop", input: {} })
396 .pipe(Effect.flip);
397 expect(ambiguousStop).toMatchObject({
398 _tag: "PreviewAutomationControlInterruptedError",
399 reason: "tabRequired",
400 });
401 const explicitStop = yield* broker
402 .invoke<void>({ scope, tabId, operation: "recordingStop", input: {} })
403 .pipe(Effect.flip);
404 expect(explicitStop).toMatchObject({
405 _tag: "PreviewAutomationExecutionError",
406 cause: { _tag: "PreviewAutomationRecordingNotActiveError" },
407 });
408 const result = yield* broker.invoke({
409 scope,
410 tabId,
411 operation: "evaluate",
412 input: { expression: "owned()" },
413 });
414 expect(result).toBe("evaluated");
415 expect(contexts).toHaveLength(2);
416 }),
417 ).pipe(Effect.provide(layer)),
418);
419​
420it.live("streams to a read-only viewer without allowing takeover, input, or viewport changes", () =>
421 Effect.scoped(
422 Effect.gen(function* () {
423 const { browser, tabId } = yield* ready;
424 const viewer = yield* browser.attachViewer(viewerInput(tabId, false));
425 const page = contexts[0]!.page;
426 page.setViewportSize.mockClear();
427 const session = contexts[0]!.sessions.at(-1)!;
428 session.send.mockClear();
429 for (const message of [
430 { type: "takeControl" },
431 { type: "key", action: "down", key: "a", text: "a" },
432 { type: "resize", width: 390, height: 844 },
433 { type: "viewport", setting: { _tag: "freeform", width: 390, height: 844 } },
434 ])
435 yield* viewer.input(message);
436 expect(page.setViewportSize).not.toHaveBeenCalled();
437 expect(session.send.mock.calls.some(([method]) => method.startsWith("Input."))).toBe(false);
438 const outputs = yield* Queue.takeAll(viewer.output);
439 expect(outputs).toContainEqual(
440 expect.objectContaining({ _tag: "frame", data: Buffer.from("frame") }),
441 );
442 expect(outputs).toContainEqual(expect.objectContaining({ _tag: "viewport" }));
443 expect(outputs).toContainEqual(
444 expect.objectContaining({ _tag: "control", canOperate: false, controller: "agent" }),
445 );
446 const operator = yield* browser.attachViewer(viewerInput(tabId, true));
447 yield* operator.input({ type: "takeControl" });
448 yield* operator.input({ type: "text", text: "typed" });
449 yield* operator.input({ type: "resize", width: 390, height: 844 });
450 expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", {
451 text: "typed",
452 });
453 expect(page.setViewportSize).toHaveBeenCalledWith({ width: 390, height: 844 });
454 yield* operator.input({ type: "releaseControl" });
455 }),
456 ).pipe(Effect.provide(layer)),
457);
458​
459it.live("applies any client's viewport, appearance, and zoom to a headless tab", () =>
460 Effect.scoped(
461 Effect.gen(function* () {
462 const { tabId } = yield* ready;
463 const manager = yield* Manager.PreviewManager;
464 const page = contexts[0]!.page;
465 const session = contexts[0]!.sessions[0]!;
466 const target = { threadId: scope.thread.threadId, tabId };
467 // The agent owns this tab, and the client sends no takeover first.
468 yield* manager.resize({ ...target, viewport: { _tag: "freeform", width: 390, height: 844 } });
469 yield* manager.adjust({ ...target, colorScheme: "dark", zoomFactor: 1.25 });
470 // Settings apply in order, so the reload landing means the earlier ones did too.
471 const reloaded = Promise.withResolvers<void>();
472 const send = session.send.getMockImplementation()!;
473 session.send.mockImplementation(async (method, input) => {
474 if (method === "Page.reload") reloaded.resolve();
475 return send(method, input);
476 });
477 yield* manager.adjust({ ...target, hardReload: true });
478 yield* Effect.promise(() => reloaded.promise);
479 expect(session.send).toHaveBeenCalledWith("Page.reload", { ignoreCache: true });
480 expect(page.setViewportSize).toHaveBeenCalledWith({ width: 390, height: 844 });
481 expect(page.emulateMedia).toHaveBeenCalledWith({ colorScheme: "dark" });
482 // Zoom lays the page out in fewer CSS pixels and draws each one larger.
483 expect(session.send).toHaveBeenCalledWith("Emulation.setDeviceMetricsOverride", {
484 width: 312,
485 height: 675,
486 deviceScaleFactor: 2.5,
487 mobile: false,
488 });
489 }),
490 ).pipe(Effect.provide(layer)),
491);
492​
493it.live(
494 "takeover waits for the running agent and revokes snapshot refs before returning control",
495 () =>
496 Effect.scoped(
497 Effect.gen(function* () {
498 const { browser, broker, tabId } = yield* ready;
499 const snapshot = yield* broker.invoke<PreviewAutomationSnapshot>({
500 scope,
501 tabId,
502 operation: "snapshot",
503 input: {},
504 });
505 const ref = /\[ref=([^\]]+)\]/.exec(String(snapshot.accessibilityTree))![1]!;
506 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
507 const started = Promise.withResolvers<void>();
508 const finish = Promise.withResolvers<Record<string, unknown>>();
509 const session = contexts[0]!.sessions[0]!;
510 session.send.mockImplementationOnce(async () => {
511 started.resolve();
512 return finish.promise;
513 });
514 const running = yield* broker
515 .invoke({ scope, tabId, operation: "evaluate", input: { expression: "pending()" } })
516 .pipe(Effect.forkScoped);
517 yield* Effect.addFinalizer(() =>
518 Effect.sync(() => finish.resolve({ result: { value: "finished" } })),
519 );
520 yield* Effect.promise(() => started.promise);
521 const takeover = yield* viewer.input({ type: "takeControl" }).pipe(Effect.forkScoped);
522 let control = yield* Queue.take(viewer.output);
523 while (control._tag !== "control" || control.controller !== "you") {
524 control = yield* Queue.take(viewer.output);
525 }
526 const rejected = yield* broker
527 .invoke<void>({ scope, tabId, operation: "evaluate", input: { expression: "racing()" } })
528 .pipe(Effect.flip);
529 expect(rejected).toMatchObject({
530 _tag: "PreviewAutomationControlInterruptedError",
531 reason: "humanControl",
532 });
533 finish.resolve({ result: { value: "finished" } });
534 expect(yield* Fiber.join(running)).toBe("finished");
535 yield* Fiber.join(takeover);
536 yield* viewer.input({ type: "releaseControl" });
537 const stale = yield* broker
538 .invoke<void>({ scope, tabId, operation: "click", input: { locator: `aria-ref=${ref}` } })
539 .pipe(Effect.flip);
540 expect(stale._tag).toBe("PreviewAutomationInvalidSelectorError");
541 expect(contexts[0]!.page.locator).not.toHaveBeenCalled();
542 expect(
543 yield* broker.invoke({
544 scope,
545 tabId,
546 operation: "evaluate",
547 input: { expression: "resumed()" },
548 }),
549 ).toBe("evaluated");
550 }),
551 ).pipe(Effect.provide(layer)),
552);
553​
554it.live("reports a pending dialog without evaluating the page and resolves it explicitly", () =>
555 Effect.scoped(
556 Effect.gen(function* () {
557 const { broker, tabId } = yield* ready;
558 const page = contexts[0]!.page;
559 yield* broker.invoke({
560 scope,
561 tabId,
562 operation: "navigate",
563 input: { url: "http://localhost:5173" },
564 });
565 const started = Promise.withResolvers<void>();
566 const resolvedEvaluation = Promise.withResolvers<Record<string, unknown>>();
567 const session = contexts[0]!.sessions[0]!;
568 const send = session.send.getMockImplementation()!;
569 session.send.mockImplementation(async (method, input) => {
570 if (method !== "Runtime.evaluate") return send(method, input);
571 started.resolve();
572 return resolvedEvaluation.promise;
573 });
574 const blockedAction = yield* broker
575 .invoke({
576 scope,
577 tabId,
578 operation: "evaluate",
579 input: { expression: 'confirm("Delete row?")' },
580 })
581 .pipe(Effect.forkScoped);
582 yield* Effect.addFinalizer(() =>
583 Effect.sync(() => resolvedEvaluation.resolve({ result: { value: true } })),
584 );
585 yield* Effect.promise(() => started.promise);
586 const dialog = {
587 type: () => "confirm",
588 message: () => "Delete row?",
589 defaultValue: () => "",
590 accept: vi.fn(async () => {
591 resolvedEvaluation.resolve({ result: { value: true } });
592 }),
593 dismiss: vi.fn(async () => {}),
594 };
595 page.emit("dialog", dialog);
596 page.title.mockClear();
597 const status = yield* broker.invoke<PreviewAutomationStatus>({
598 scope,
599 tabId,
600 operation: "status",
601 input: {},
602 });
603 expect(status.dialog).toMatchObject({ type: "confirm", message: "Delete row?" });
604 expect(page.title).not.toHaveBeenCalled();
605 expect(dialog.dismiss).not.toHaveBeenCalled();
606 const reuse = yield* broker
607 .invoke<void>({
608 scope,
609 tabId,
610 operation: "open",
611 input: { url: "http://localhost:5173/other" },
612 })
613 .pipe(Effect.flip);
614 expect(reuse).toMatchObject({
615 _tag: "PreviewAutomationControlInterruptedError",
616 reason: "dialogPending",
617 });
618 expect(page.goto).toHaveBeenCalledTimes(1);
619 yield* broker.invoke({ scope, tabId, operation: "dialog", input: { accept: true } });
620 expect(yield* Fiber.join(blockedAction)).toBe(true);
621 expect(dialog.accept).toHaveBeenCalledTimes(1);
622 const resolved = yield* broker.invoke<PreviewAutomationStatus>({
623 scope,
624 tabId,
625 operation: "status",
626 input: {},
627 });
628 expect(resolved.dialog).toBeNull();
629 }),
630 ).pipe(Effect.provide(layer)),
631);
632​
633it.live("the owner can close a tab while an agent action waits on its dialog", () =>
634 Effect.scoped(
635 Effect.gen(function* () {
636 const { broker, tabId } = yield* ready;
637 const page = contexts[0]!.page;
638 const started = Promise.withResolvers<void>();
639 const finish = Promise.withResolvers<Record<string, unknown>>();
640 contexts[0]!.sessions[0]!.send.mockImplementationOnce(async () => {
641 started.resolve();
642 return finish.promise;
643 });
644 page.on("close", () => finish.resolve({ result: { value: "closed" } }));
645 const running = yield* broker
646 .invoke({
647 scope,
648 tabId,
649 operation: "evaluate",
650 input: { expression: 'confirm("Delete?")' },
651 })
652 .pipe(Effect.forkScoped);
653 yield* Effect.addFinalizer(() =>
654 Effect.sync(() => finish.resolve({ result: { value: "cleanup" } })),
655 );
656 yield* Effect.promise(() => started.promise);
657 page.emit("dialog", {
658 type: () => "confirm",
659 message: () => "Delete?",
660 defaultValue: () => "",
661 accept: vi.fn(),
662 dismiss: vi.fn(),
663 });
664 const foreign = yield* broker
665 .invoke<void>({
666 scope: asSession("agent-b"),
667 tabId,
668 operation: "close",
669 input: {},
670 })
671 .pipe(Effect.flip);
672 expect(foreign).toMatchObject({
673 _tag: "PreviewAutomationControlInterruptedError",
674 reason: "agentMismatch",
675 });
676 expect(page.close).not.toHaveBeenCalled();
677 yield* broker.invoke({ scope, tabId, operation: "close", input: {} });
678 expect(yield* Fiber.join(running)).toBe("closed");
679 expect(page.close).toHaveBeenCalled();
680 const manager = yield* Manager.PreviewManager;
681 expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength(0);
682 const afterClose = yield* broker
683 .invoke<void>({ scope, tabId, operation: "evaluate", input: { expression: "late()" } })
684 .pipe(Effect.flip);
685 expect(afterClose._tag).toBe("PreviewAutomationTabNotFoundError");
686 }),
687 ).pipe(Effect.provide(layer)),
688);
689​
690it.live("a popup becomes the agent's own tab and keeps its opener page", () =>
691 Effect.scoped(
692 Effect.gen(function* () {
693 const { broker, tabId } = yield* ready;
694 const opener = contexts[0]!.page;
695 const popup = makeContext();
696 opener.emit("popup", popup.page);
697 const manager = yield* Manager.PreviewManager;
698 let sessions = (yield* manager.list({ threadId: scope.thread.threadId })).sessions;
699 while (sessions.length < 2) {
700 yield* Effect.sleep("5 millis");
701 sessions = (yield* manager.list({ threadId: scope.thread.threadId })).sessions;
702 }
703 const popupTab = sessions.find((session) => session.tabId !== tabId)!;
704 const opened = sessions.find((session) => session.tabId === tabId)!;
705 expect(popupTab).toMatchObject({ automationOwner: opened.automationOwner, reveal: false });
706 const status = yield* broker.invoke<PreviewAutomationStatus>({
707 scope,
708 tabId,
709 operation: "status",
710 input: {},
711 });
712 expect(status.tabs).toEqual(
713 expect.arrayContaining([
714 expect.objectContaining({ tabId }),
715 expect.objectContaining({ tabId: popupTab.tabId, openerTabId: tabId }),
716 ]),
717 );
718 expect(opener.goto).not.toHaveBeenCalled();
719 expect(opener.close).not.toHaveBeenCalled();
720 // The page the popup script holds is the tab, so closing it ends the tab.
721 yield* Effect.promise(() => popup.page.close());
722 while ((yield* manager.list({ threadId: scope.thread.threadId })).sessions.length > 1) {
723 yield* Effect.sleep("5 millis");
724 }
725 }),
726 ).pipe(Effect.provide(layer)),
727);
728​
729it.live("closing a tab while a viewer is still opening it does not leave its page behind", () =>
730 Effect.scoped(
731 Effect.gen(function* () {
732 const browser = yield* ServerBrowser.ServerBrowser;
733 const manager = yield* Manager.PreviewManager;
734 yield* Effect.yieldNow;
735 // The background open fails, so the tab exists only as a session.
736 contextFailure = new Error("first launch failed");
737 const snapshot = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" });
738 yield* Effect.sleep("10 millis");
739 contextFailure = null;
740 contextGate = Promise.withResolvers<void>();
741 const attaching = yield* browser
742 .attachViewer(viewerInput(snapshot.tabId, false))
743 .pipe(Effect.flip, Effect.forkScoped);
744 yield* Effect.sleep("10 millis");
745 yield* manager.close({ threadId: scope.thread.threadId, tabId: snapshot.tabId });
746 yield* Effect.sleep("10 millis");
747 contextGate.resolve();
748 expect((yield* Fiber.join(attaching))._tag).toBe("ServerBrowserTabNotFoundError");
749 expect(contexts).toHaveLength(1);
750 expect(contexts[0]!.page.close).toHaveBeenCalled();
751 }),
752 ).pipe(Effect.provide(layer)),
753);
754​
755it.live("page copies reach only the controlling viewer right after its input", () =>
756 Effect.scoped(
757 Effect.gen(function* () {
758 const { browser, tabId } = yield* ready;
759 const page = contexts[0]!.page;
760 const watcher = yield* browser.attachViewer(viewerInput(tabId, false));
761 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
762 yield* viewer.input({ type: "takeControl" });
763 const clipboard = (queue: typeof viewer.output) =>
764 Queue.clear(queue).pipe(
765 Effect.map((items) => items.filter((item) => item._tag === "clipboard")),
766 );
767 // A page writing on its own, without a recent gesture, stays on the server.
768 clipboardBinding!({ page }, "unprompted");
769 expect(yield* clipboard(viewer.output)).toEqual([]);
770 yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 });
771 const cdp = contexts[0]!.sessions.at(-1)!;
772 expect(cdp.send).toHaveBeenCalledWith(
773 "Input.dispatchKeyEvent",
774 expect.objectContaining({ key: "c", commands: ["copy"] }),
775 );
776 clipboardBinding!({ page }, "copied");
777 expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "copied" }]);
778 expect(yield* clipboard(watcher.output)).toEqual([]);
779 }),
780 ).pipe(Effect.provide(layer)),
781);
782​
783it.live("a page download is saved, offered to the controller, and listed for the agent", () =>
784 Effect.scoped(
785 Effect.gen(function* () {
786 const { browser, broker, tabId } = yield* ready;
787 const page = contexts[0]!.page;
788 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
789 yield* viewer.input({ type: "takeControl" });
790 yield* Queue.clear(viewer.output);
791 // Stands in for Chromium, which writes the file itself.
792 const saved = yield* Queue.unbounded<string>();
793 const written = Promise.withResolvers<void>();
794 page.emit("download", {
795 failure: async () => null,
796 saveAs: (path: string) => {
797 Queue.offerUnsafe(saved, path);
798 return written.promise;
799 },
800 suggestedFilename: () => "report.csv",
801 url: () => "blob:http://localhost:5173/1",
802 });
803 const fs = yield* FileSystem.FileSystem;
804 const path = yield* Queue.take(saved);
805 yield* fs.writeFileString(path, "a,b");
806 written.resolve();
807 let offered = yield* Queue.take(viewer.output);
808 while (offered._tag !== "download") offered = yield* Queue.take(viewer.output);
809 expect(offered).toMatchObject({ _tag: "download", fileName: "report.csv", sizeBytes: 3 });
810 const file = yield* browser.openDownload({
811 threadId: scope.thread.threadId,
812 tabId,
813 downloadId: offered.id,
814 });
815 expect(Option.isSome(file) && file.value.fileName).toBe("report.csv");
816 const status = yield* broker.invoke<PreviewAutomationStatus>({
817 scope,
818 tabId,
819 operation: "status",
820 input: {},
821 });
822 expect(status.downloads).toEqual([
823 expect.objectContaining({ fileName: "report.csv", sizeBytes: 3 }),
824 ]);
825 expect(
826 Option.isNone(
827 yield* browser.openDownload({
828 threadId: scope.thread.threadId,
829 tabId,
830 downloadId: "guess",
831 }),
832 ),
833 ).toBe(true);
834 }),
835 ).pipe(Effect.provide(layer)),
836);
837​
838it.live("a page's file picker goes to the controller and takes its uploaded files", () =>
839 Effect.scoped(
840 Effect.gen(function* () {
841 const { browser, tabId } = yield* ready;
842 const page = contexts[0]!.page;
843 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
844 yield* viewer.input({ type: "takeControl" });
845 const setFiles = vi.fn(async (_files: unknown) => {});
846 page.emit("filechooser", {
847 isMultiple: () => false,
848 element: () => ({ getAttribute: async () => ".csv" }),
849 setFiles,
850 });
851 let offered = yield* Queue.take(viewer.output);
852 while (offered._tag !== "fileChooser") offered = yield* Queue.take(viewer.output);
853 expect(offered).toMatchObject({ multiple: false, accept: ".csv" });
854 const file = (name: string) => ({ name, mimeType: "text/csv", buffer: Buffer.from(name) });
855 const answer = (chooserId: string) =>
856 browser.answerFileChooser({
857 threadId: scope.thread.threadId,
858 tabId,
859 chooserId,
860 files: [file("a.csv"), file("b.csv")],
861 });
862 expect(yield* answer("other")).toBe(false);
863 expect(yield* answer(offered.id)).toBe(true);
864 // A single-file input only receives the first file.
865 expect(setFiles).toHaveBeenCalledExactlyOnceWith([file("a.csv")]);
866 let closed = yield* Queue.take(viewer.output);
867 while (closed._tag !== "fileChooserClosed") closed = yield* Queue.take(viewer.output);
868 expect(closed.id).toBe(offered.id);
869 expect(yield* answer(offered.id)).toBe(false);
870 }),
871 ).pipe(Effect.provide(layer)),
872);
873​
874it.live("a file picker replaces a stalled viewer backlog instead of being dropped", () =>
875 Effect.scoped(
876 Effect.gen(function* () {
877 const { browser, tabId } = yield* ready;
878 const page = contexts[0]!.page;
879 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
880 yield* viewer.input({ type: "takeControl" });
881 const accept = Promise.withResolvers<string>();
882 page.emit("filechooser", {
883 isMultiple: () => false,
884 element: () => ({ getAttribute: () => accept.promise }),
885 setFiles: async () => {},
886 });
887 // The viewer stopped reading: its output is full when the picker opens.
888 yield* Queue.clear(viewer.output);
889 stallViewer(viewer, { _tag: "viewport", width: 1, height: 1 });
890 accept.resolve(".csv");
891 // The picker is offered within the microtasks that follow its accept attribute.
892 yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
893 expect(yield* Queue.clear(viewer.output)).toEqual([
894 expect.objectContaining({ _tag: "fileChooser", accept: ".csv" }),
895 ]);
896 }),
897 ).pipe(Effect.provide(layer)),
898);
899​
900it.live("control updates replace a stalled viewer backlog in the order they happen", () =>
901 Effect.scoped(
902 Effect.gen(function* () {
903 const { browser, tabId } = yield* ready;
904 const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
905 yield* Queue.clear(viewer.output);
906 // Chromium is slow to take back the frames the replacement drops.
907 const acked = Promise.withResolvers<void>();
908 yield* Effect.addFinalizer(() => Effect.sync(() => acked.resolve()));
909 stallViewer(viewer, {
910 _tag: "frame",
911 data: Buffer.alloc(0),
912 ack: Effect.promise(() => acked.promise),
913 });
914 yield* viewer.input({ type: "takeControl" });
915 yield* viewer.input({ type: "releaseControl" });
916 const controls = (yield* Queue.clear(viewer.output)).flatMap((item) =>
917 item._tag === "control" ? [item.controller] : [],
918 );
919 expect(controls[0]).toBe("you");
920 expect(controls.at(-1)).not.toBe("you");
921 }),
922 ).pipe(Effect.provide(layer)),
923);
924​
925it.live("an agent's tabs stop at the limit until an unwatched idle tab closes", () =>
926 Effect.scoped(
927 Effect.gen(function* () {
928 const { broker, tabId } = yield* ready;
929 const open = broker.invoke<PreviewAutomationStatus>({
930 scope,
931 operation: "open",
932 input: { reuseExistingTab: false, show: false },
933 });
934 for (let count = 1; count < 8; count += 1) yield* open;
935 expect(yield* Effect.flip(open)).toMatchObject({
936 _tag: "PreviewAutomationControlInterruptedError",
937 reason: "tabLimit",
938 });
939 // Another agent session keeps its own budget.
940 yield* broker.invoke({
941 scope: asSession("agent-b"),
942 operation: "open",
943 input: { reuseExistingTab: false, show: false },
944 });
945 const later = (yield* Clock.currentTimeMillis) + 31 * 60 * 1000;
946 const clock = vi.spyOn(Date, "now").mockReturnValue(later);
947 yield* Effect.addFinalizer(() => Effect.sync(() => clock.mockRestore()));
948 // The first tab is watched, so it stays open while the agent's other idle tabs close.
949 const browser = yield* ServerBrowser.ServerBrowser;
950 yield* browser.attachViewer(viewerInput(tabId, false));
951 const reopened = yield* open;
952 const manager = yield* Manager.PreviewManager;
953 const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
954 expect(sessions.map((session) => session.tabId).toSorted()).toEqual(
955 [tabId, reopened.tabId].toSorted(),
956 );
957 }),
958 ).pipe(Effect.provide(layer)),
959);
960​
961it.live("an agent answers the page's file picker or sets files on a file input", () =>
962 Effect.scoped(
963 Effect.gen(function* () {
964 const { broker, tabId } = yield* ready;
965 const page = contexts[0]!.page;
966 const upload = (input: Record<string, unknown>) =>
967 broker.invoke<void>({ scope, tabId, operation: "upload", input });
968 expect(yield* Effect.flip(upload({ paths: ["/tmp/a.csv"] }))).toMatchObject({
969 _tag: "PreviewAutomationExecutionError",
970 });
971 const setFiles = vi.fn(async (_files: unknown) => {});
972 page.emit("filechooser", {
973 isMultiple: () => false,
974 element: () => ({ getAttribute: async () => ".csv" }),
975 setFiles,
976 });
977 const status = broker.invoke<PreviewAutomationStatus>({
978 scope,
979 tabId,
980 operation: "status",
981 input: {},
982 });
983 let opened = yield* status;
984 while (!opened.fileChooser) {
985 yield* Effect.sleep("5 millis");
986 opened = yield* status;
987 }
988 expect(opened.fileChooser).toEqual({ multiple: false, accept: ".csv" });
989 // A single-file picker rejects several files instead of dropping some.
990 yield* Effect.flip(upload({ paths: ["/tmp/a.csv", "/tmp/b.csv"] }));
991 yield* upload({ paths: ["/tmp/a.csv"] });
992 expect(setFiles).toHaveBeenCalledExactlyOnceWith(["/tmp/a.csv"], expect.anything());
993 expect((yield* status).fileChooser).toBeNull();
994​
995 const setInputFiles = vi.fn(async () => {});
996 page.locator.mockReturnValue({ setInputFiles } as never);
997 yield* upload({ paths: ["/tmp/b.csv"], locator: "input[type=file]" });
998 expect(page.locator).toHaveBeenLastCalledWith("input[type=file]");
999 expect(setInputFiles).toHaveBeenCalledWith(["/tmp/b.csv"], expect.anything());
1000 }),
1001 ).pipe(Effect.provide(layer)),
1003​
1004it.live("viewers see the agent's pointer move to its target and click there", () =>
1005 Effect.scoped(
1006 Effect.gen(function* () {
1007 const { browser, broker, tabId } = yield* ready;
1008 const page = contexts[0]!.page;
1009 const viewer = yield* browser.attachViewer(viewerInput(tabId, false));
1010 const click = vi.fn(async () => {});
1011 page.locator.mockReturnValue({
1012 scrollIntoViewIfNeeded: async () => {},
1013 boundingBox: async () => ({ x: 100, y: 40, width: 80, height: 20 }),
1014 click,
1015 } as never);
1016 yield* broker.invoke({ scope, tabId, operation: "click", input: { locator: "#go" } });
1017 const pointers = (yield* Queue.clear(viewer.output)).filter(
1018 (item) => item._tag === "pointer",
1019 );
1020 expect(pointers).toEqual([
1021 expect.objectContaining({ phase: "move", x: 140, y: 50 }),
1022 expect.objectContaining({ phase: "click", x: 140, y: 50 }),
1023 ]);
1024 expect(click).toHaveBeenCalledOnce();
1025 }),
1026 ).pipe(Effect.provide(layer)),
1028​
1029it.live("drives the desktop's own page for a tab the desktop renders", () =>
1030 Effect.scoped(
1031 Effect.gen(function* () {
1032 const browser = yield* ServerBrowser.ServerBrowser;
1033 const broker = yield* Broker.PreviewAutomationBroker;
1034 const manager = yield* Manager.PreviewManager;
1035 yield* Effect.yieldNow;
1036 desktopRendersNext = true;
1037 const opened = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" });
1038 const viewer = yield* browser.attachViewer(viewerInput(opened.tabId, true));
1039 expect(desktopConnections.map((connection) => connection.endpoint)).toEqual([
1040 `ws://desktop/${opened.tabId}`,
1041 ]);
1042 // No headless context was launched for it.
1043 expect(contexts).toEqual([]);
1044 const page = desktopConnections[0]!.context.page;
1045 // The desktop panel sizes its page, so a viewer resize leaves it alone.
1046 yield* viewer.input({ type: "takeControl" });
1047 yield* viewer.input({ type: "resize", width: 390, height: 844 });
1048 expect(page.setViewportSize).not.toHaveBeenCalled();
1049 yield* viewer.input({ type: "releaseControl" });
1050 // Agents reach it through the same engine as a headless tab.
1051 const evaluated = yield* broker.invoke({
1052 scope: asSession("agent-desktop"),
1053 operation: "status",
1054 input: {},
1055 tabId: PreviewTabId.make(opened.tabId),
1056 });
1057 expect(evaluated).toMatchObject({ tabId: opened.tabId });
1058 // Closing the session lets go of the desktop's page without closing it.
1059 yield* manager.close({ threadId: scope.thread.threadId, tabId: opened.tabId });
1060 while (releasedDesktopTabs.length === 0) yield* Effect.yieldNow;
1061 expect(releasedDesktopTabs).toEqual([opened.tabId]);
1062 expect(page.close).not.toHaveBeenCalled();
1063 }),
1064 ).pipe(Effect.provide(layer)),
1066​
1067it.live("a desktop page the desktop takes back reconnects instead of closing", () =>
1068 Effect.scoped(
1069 Effect.gen(function* () {
1070 const browser = yield* ServerBrowser.ServerBrowser;
1071 const manager = yield* Manager.PreviewManager;
1072 yield* Effect.yieldNow;
1073 desktopRendersNext = true;
1074 const opened = yield* manager.open({ threadId: scope.thread.threadId, runtime: "server" });
1075 const viewer = yield* browser.attachViewer(viewerInput(opened.tabId, false));
1076 // Devtools opened on the desktop, so it withdrew the page's debugger.
1077 // The server's listener subscribes in its own fiber; detach once it is there.
1078 while (desktopDetaches.listenerCount("detach") === 0) yield* Effect.yieldNow;
1079 desktopDetaches.emit("detach", { threadId: scope.thread.threadId, tabId: opened.tabId });
1080 let end = yield* Queue.take(viewer.output);
1081 while (end._tag !== "reconnect" && end._tag !== "gone")
1082 end = yield* Queue.take(viewer.output);
1083 expect(end._tag).toBe("reconnect");
1084 expect(releasedDesktopTabs).toEqual([opened.tabId]);
1085 // The session survives, and the next viewer reaches the page again.
1086 const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
1087 expect(sessions.map((session) => session.tabId)).toContain(opened.tabId);
1088 yield* browser.attachViewer(viewerInput(opened.tabId, false));
1089 expect(desktopConnections).toHaveLength(2);
1090 }),
1091 ).pipe(Effect.provide(layer)),