Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off - Playwright callbacks run outside the Effect runtime.
2
3import {
4 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
5 type PreviewAutomationClickInput,
6 type PreviewAutomationConsoleEntry,
7 type PreviewAutomationDragInput,
8 type PreviewAutomationEvaluateInput,
9 type PreviewAutomationHoverInput,
10 type PreviewAutomationNetworkEntry,
11 type PreviewAutomationPressInput,
12 type PreviewAutomationScrollInput,
13 type PreviewAutomationSelectInput,
14 type PreviewAutomationSelectResult,
15 type PreviewAutomationSnapshot,
16 type PreviewAutomationTypeInput,
17 type PreviewAutomationUploadInput,
18 type PreviewAutomationWaitForInput,
19} from "@t3tools/contracts";
20import { constVoid } from "effect/Function";
21import type { CDPSession, Frame, Locator, Page } from "playwright-core";
22import * as NodeCrypto from "node:crypto";
23import { BrowserControlInterrupted } from "./SessionControl.ts";
24
25const MAX_EVALUATION_BYTES = 64_000;
26const MAX_VISIBLE_TEXT_LENGTH = 20_000;
27const MAX_SCREENSHOT_WIDTH = 1280;
28const WAIT_POLL_MS = 100;
29export const DIAGNOSTIC_BUFFER_LIMIT = 200;
30
31export class ServerBrowserOperationError extends Error {
32 readonly tag: string;
33 readonly detail: unknown;
34
35 constructor(tag: string, message: string, detail?: unknown) {
36 super(message);
37 this.tag = tag;
38 this.detail = detail;
39 }
40}
41
42export const toOperationError = (cause: unknown): ServerBrowserOperationError => {
43 if (cause instanceof BrowserControlInterrupted)
44 return new ServerBrowserOperationError(
45 "PreviewAutomationControlInterruptedError",
46 cause.message,
47 cause.reason,
48 );
49 if (cause instanceof ServerBrowserOperationError) return cause;
50 const message = cause instanceof Error ? cause.message : String(cause);
51 const firstLine = message.split("\n")[0] ?? message;
52 if (cause instanceof Error && cause.name === "TimeoutError") {
53 return new ServerBrowserOperationError("PreviewAutomationTimeoutError", firstLine);
54 }
55 if (
56 /while parsing selector|Unknown engine|Unexpected token|strict mode violation/i.test(message)
57 ) {
58 return new ServerBrowserOperationError("PreviewAutomationInvalidSelectorError", firstLine);
59 }
60 if (/not an <input>|not editable|not an editable/i.test(message)) {
61 return new ServerBrowserOperationError("PreviewAutomationTargetNotEditableError", firstLine);
62 }
63 return new ServerBrowserOperationError("PreviewAutomationExecutionError", firstLine);
64};
65
66const DEFAULT_TIMEOUT_MS = 15_000;
67
68const pageRefs = new WeakMap<Page, { generation: string; refs: Map<string, string> }>();
69// A compact runtime namespace prevents old refs from aliasing after a server restart.
70const refNamespace = NodeCrypto.randomUUID().slice(0, 8);
71let snapshotSequence = 0;
72const nextRefGeneration = () => `${refNamespace}-${(++snapshotSequence).toString(36)}`;
73
74/** A takeover revokes previously issued refs even when the document stays unchanged. */
75export const invalidateRefs = (page: Page) => {
76 const state = pageRefs.get(page);
77 if (state) {
78 state.generation = nextRefGeneration();
79 state.refs.clear();
80 }
81};
82
83const refsFor = (page: Page) => {
84 let state = pageRefs.get(page);
85 if (!state) {
86 state = { generation: nextRefGeneration(), refs: new Map<string, string>() };
87 pageRefs.set(page, state);
88 page.on("framenavigated", () => invalidateRefs(page));
89 page.on("framedetached", () => invalidateRefs(page));
90 }
91 return state;
92};
93
94const targetLocator = (
95 page: Page,
96 input: { readonly locator?: string | undefined; readonly selector?: string | undefined },
97): Locator | null => {
98 const selector = input.locator ?? input.selector;
99 if (selector === undefined) return null;
100 // Ignore quoted/escaped CSS values when looking for a selector-engine boundary.
101 const engines = selector.replace(
102 /\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g,
103 " ",
104 );
105 if (/(?:^|>>)\s*\*?aria-ref\s*=/.test(engines)) {
106 const ref = /^\s*aria-ref\s*=\s*(\S+)\s*$/.exec(selector)?.[1];
107 const nativeRef = ref === undefined ? undefined : pageRefs.get(page)?.refs.get(ref);
108 if (nativeRef === undefined) {
109 throw new ServerBrowserOperationError(
110 "PreviewAutomationInvalidSelectorError",
111 "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.",
112 { staleRef: true },
113 );
114 }
115 return page.locator(`aria-ref=${nativeRef}`);
116 }
117 // Playwright's strict locators reject ambiguous controls rather than acting on row one.
118 return page.locator(selector);
119};
120
121export type PointerReporter = (
122 point: { readonly x: number; readonly y: number },
123 phase: "move" | "click",
124) => Promise<void>;
125const noPointer: PointerReporter = async () => {};
126
127const targetPoint = async (
128 page: Page,
129 locator: Locator | null,
130 input: { readonly x?: number | undefined; readonly y?: number | undefined },
131 timeout: number,
132) => {
133 if (locator === null) return { x: input.x ?? 0, y: input.y ?? 0 };
134 await locator.scrollIntoViewIfNeeded({ timeout });
135 const box = await locator.boundingBox({ timeout });
136 if (box) return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
137 const viewport = page.viewportSize();
138 return { x: (viewport?.width ?? 0) / 2, y: (viewport?.height ?? 0) / 2 };
139};
140
141const SNAPSHOT_SCRIPT = `(() => {
142 return {
143 url: location.href,
144 title: document.title,
145 loading: document.readyState !== "complete",
146 visibleText: document.body?.innerText || "",
147 interactiveElements: [],
148 };
149})()`;
150
151const MASKED_VALUE = "••••••••";
152// The broker waits 15s for the host; a snapshot, retry included, answers well before.
153const SNAPSHOT_TIMEOUT_MS = 10_000;
154// How long a frame in another process gets to answer; one that crashed never does.
155const FRAME_ANSWER_MS = 1_000;
156
157// Values the page draws as dots (password fields, and text fields whose CSS
158// draws dots), normalized like accessible text. Open shadow roots included.
159const DOTTED_SCRIPT = `(() => {
160 const values = [];
161 const visit = (root) => {
162 for (const element of root.querySelectorAll("*")) {
163 if (element.shadowRoot) visit(element.shadowRoot);
164 const field = element.localName === "input" || element.localName === "textarea";
165 if (!field && !element.isContentEditable) continue;
166 const dots = getComputedStyle(element).getPropertyValue("-webkit-text-security");
167 if (element.type !== "password" && (dots === "none" || dots === "")) continue;
168 // Raw as page text shows it, and normalized as the tree does.
169 for (const value of field ? [element.value, element.defaultValue] : [element.textContent ?? ""])
170 values.push(value, value.replace(/[\\u200b\\u00ad]/g, "").trim().replace(/\\s+/g, " "));
171 }
172 };
173 visit(document);
174 return [...new Set(values.filter((value) => value.trim()))];
175})()`;
176
177const pageChanged = () =>
178 new ServerBrowserOperationError(
179 "PreviewAutomationExecutionError",
180 "The page changed while capturing its snapshot. Take another snapshot.",
181 );
182
183const tooBusy = () =>
184 new ServerBrowserOperationError(
185 "PreviewAutomationTimeoutError",
186 "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.",
187 );
188
189const VALUE_TOO_LONG = "A password field holds a value too long to hide, so no snapshot was taken.";
190
191/** A frame in another process keeps one CDP session, so none pile up across snapshots. */
192const frameSessions = new WeakMap<Frame, Promise<CDPSession>>();
193
194/** The value, or undefined when it fails or takes longer than a frame may. */
195const answered = <A>(promise: Promise<A>) => {
196 let timer: ReturnType<typeof setTimeout> | undefined;
197 const late = new Promise<undefined>((resolve) => {
198 timer = setTimeout(() => resolve(undefined), FRAME_ANSWER_MS);
199 });
200 return Promise.race([promise.catch(() => undefined), late]).finally(() => clearTimeout(timer));
201};
202
203/**
204 * Reads dotted values in isolated worlds, where page script can't change what `value`
205 * returns, through the CDP session of the process each frame renders in. A frame in
206 * another process that can't be attached, as in desktop tabs where only the page can,
207 * is read in the page's own world, where its script can change `value`. `read` gives
208 * each reader's values, or undefined for one that didn't answer, and fails when the
209 * page's own frames don't or frames came or went.
210 */
211const openReaders = async (page: Page, cdp: CDPSession) => {
212 const frames = page.frames();
213 const owners = new Map<Frame, CDPSession | null | undefined>(
214 await Promise.all(
215 frames.map(async (frame) => {
216 if (frame === page.mainFrame()) return [frame, cdp] as const;
217 const session = frameSessions.get(frame) ?? page.context().newCDPSession(frame);
218 frameSessions.set(frame, session);
219 try {
220 return [frame, await session] as const;
221 } catch (cause) {
222 frameSessions.delete(frame);
223 // CdpRelay refuses all but the page. Any other refusal reads the frame through its
224 // parent's session, which fails the read if the frame isn't there.
225 const desktop = String(cause).includes("Only this preview tab's page can be attached");
226 return [frame, desktop ? null : undefined] as const;
227 }
228 }),
229 ),
230 );
231 const ownerOf = (frame: Frame): CDPSession | null => {
232 const owner = owners.get(frame);
233 if (owner !== undefined) return owner;
234 const parent = frame.parentFrame();
235 return parent ? ownerOf(parent) : null;
236 };
237 const sessionReader = (frame: Frame, session: CDPSession) => {
238 const owned = frames.filter((each) => ownerOf(each) === session);
239 const open = async () => {
240 const { frameTree } = await session.send("Page.getFrameTree");
241 const ids = (node: typeof frameTree): Array<string> => [
242 node.frame.id,
243 ...(node.childFrames ?? []).flatMap(ids),
244 ];
245 // A frame Playwright knows but this session doesn't would go unread.
246 if (ids(frameTree).length !== owned.length) throw pageChanged();
247 return Promise.all(
248 ids(frameTree).map(async (frameId) => {
249 const world = await session.send("Page.createIsolatedWorld", {
250 frameId,
251 worldName: "t3-preview",
252 });
253 return world.executionContextId;
254 }),
255 );
256 };
257 let contexts: ReturnType<typeof open> | undefined;
258 const read = async () => {
259 const values = (contexts ??= open()).then((ids) =>
260 Promise.all(
261 ids.map(async (contextId) => {
262 const { result, exceptionDetails } = await session.send("Runtime.evaluate", {
263 contextId,
264 expression: DOTTED_SCRIPT,
265 returnByValue: true,
266 });
267 if (exceptionDetails) throw pageChanged();
268 return result.value as Array<string>;
269 }),
270 ),
271 );
272 try {
273 return (await values).flat();
274 } catch (cause) {
275 // The frame may have moved to another process; the next snapshot opens a new session.
276 if (session !== cdp) {
277 frameSessions.delete(frame);
278 void session.detach().catch(constVoid);
279 }
280 throw cause;
281 }
282 };
283 return { frames: owned, read };
284 };
285 const readers = [
286 sessionReader(page.mainFrame(), cdp),
287 ...frames.flatMap((frame) => {
288 const owner = owners.get(frame);
289 if (owner) return owner === cdp ? [] : [sessionReader(frame, owner)];
290 const own = () => frame.evaluate(DOTTED_SCRIPT) as Promise<Array<string>>;
291 return ownerOf(frame) === null ? [{ frames: [frame], read: own }] : [];
292 }),
293 ];
294 return {
295 readers,
296 /** Readers that didn't answer `before` aren't asked again. */
297 read: async (before?: ReadonlyArray<unknown>) => {
298 const now = page.frames();
299 // A frame added since the readers opened has none.
300 if (now.length !== frames.length || now.some((frame, i) => frame !== frames[i])) {
301 throw pageChanged();
302 }
303 return Promise.all(
304 readers.map((reader, i) => {
305 if (i === 0) return reader.read().catch(() => Promise.reject(pageChanged()));
306 return before && !before[i] ? undefined : answered(reader.read());
307 }),
308 );
309 },
310 };
311};
312
313/**
314 * Matches each value as the snapshot prints it: raw, as a JSON name, as a
315 * quoted value, and with '' for each quote inside a quoted key. A value under
316 * four characters only matches between non-word characters; inside other words
317 * it would mask unrelated text.
318 */
319const dottedPattern = (values: ReadonlyArray<string>) => {
320 const sources = values
321 .flatMap((value) => {
322 const json = JSON.stringify(value).slice(1, -1);
323 // Playwright writes control characters like JSON does, with \xNN for the unnamed ones.
324 const quoted = value.replace(/[\\"\p{Cc}]/gu, (char) =>
325 '\\"\b\f\n\r\t'.includes(char)
326 ? JSON.stringify(char).slice(1, -1)
327 : `\\x${char.charCodeAt(0).toString(16).padStart(2, "0")}`,
328 );
329 const forms = [value, json, quoted].flatMap((form) => [form, form.replaceAll("'", "''")]);
330 return [...new Set(forms)].map((form) => ({ form, word: value.length < 4 }));
331 })
332 // Longest first, so a form inside another never leaves the rest showing.
333 .toSorted((a, b) => b.form.length - a.form.length)
334 .map(({ form, word }) => {
335 const literal = form.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
336 return word ? `(?<![\\p{L}\\p{N}_])${literal}(?![\\p{L}\\p{N}_])` : literal;
337 });
338 if (sources.length === 0) return undefined;
339 const pattern = new RegExp(sources.join("|"), "gu");
340 try {
341 // Compiles it now, for one-byte and two-byte text: one too large fails only when it
342 // first runs on each, naming every value.
343 pattern.test("");
344 pattern.test("\u2022");
345 } catch {
346 throw new ServerBrowserOperationError("PreviewAutomationExecutionError", VALUE_TOO_LONG);
347 }
348 return pattern;
349};
350
351// `- role "name" [attribute]...: value`, the key single-quoted when it holds ": ". A name
352// that starts and ends with "/" prints unquoted. Only Playwright's own attributes count, so
353// text around a value in a name can't pass for one.
354const TREE_LINE =
355 /^(\s*- '?[^\s"':]+)( "(?:[^"\\]|\\.)*"| \/(?:.*?\/)?)?((?: \[(?:active|checked(?:=mixed)?|disabled|expanded|level=\d+|pressed(?:=mixed)?|selected|ref=(?:f\d+)?e\d+|cursor=pointer|box=-?\d+,-?\d+,\d+,\d+)\])*'?)(:.*)?$/;
356
357/**
358 * Masks each value on a line, except one that only matches inside the role or attributes,
359 * so refs keep working. A "/.../" name has no closing mark, so a value can seem to cross it.
360 */
361const maskTree = (tree: string, dotted: RegExp) =>
362 tree
363 .split("\n")
364 .map((line) => {
365 const node = TREE_LINE.exec(line);
366 const name = node?.[1]?.length ?? 0;
367 const attributes = name + (node?.[2]?.length ?? 0);
368 const end = attributes + (node?.[3]?.length ?? 0);
369 const kept = (from: number, to: number) => to <= name || (from >= attributes && to <= end);
370 return line.replace(dotted, (match: string, offset: number) =>
371 kept(offset, offset + match.length) ? match : MASKED_VALUE,
372 );
373 })
374 .join("\n");
375
376/** Chromium sizes the capture, so the reported size is read from the PNG header. */
377const pngSize = (base64: string) => {
378 const header = Buffer.from(base64.slice(0, 32), "base64");
379 return { width: header.readUInt32BE(16), height: header.readUInt32BE(20) };
380};
381
382type Viewport = { readonly width: number; readonly height: number };
383
384/**
385 * A page's display ratio and CSS viewport, read in an isolated world since page script can
386 * reassign `devicePixelRatio`, `innerWidth`, and `innerHeight` in its own, and its page zoom.
387 */
388export const readPageMetrics = async (cdp: CDPSession) => {
389 const { frameTree } = await cdp.send("Page.getFrameTree");
390 const { executionContextId } = await cdp.send("Page.createIsolatedWorld", {
391 frameId: frameTree.frame.id,
392 worldName: "t3-preview-metrics",
393 });
394 let { cssVisualViewport } = await cdp.send("Page.getLayoutMetrics");
395 // Desktop zoom applies asynchronously; bracket the CSS metrics to reject a torn read.
396 for (let attempt = 0; attempt < 3; attempt += 1) {
397 const zoom = cssVisualViewport.zoom ?? 1;
398 const { result } = await cdp.send("Runtime.evaluate", {
399 expression: "({ ratio: devicePixelRatio, width: innerWidth, height: innerHeight })",
400 contextId: executionContextId,
401 returnByValue: true,
402 });
403 ({ cssVisualViewport } = await cdp.send("Page.getLayoutMetrics"));
404 if ((cssVisualViewport.zoom ?? 1) === zoom) {
405 const { ratio, width, height } = result.value as {
406 readonly ratio: number;
407 readonly width: number;
408 readonly height: number;
409 };
410 return {
411 ratio,
412 width,
413 height,
414 zoom,
415 offset: { x: cssVisualViewport.pageX * zoom, y: cssVisualViewport.pageY * zoom },
416 };
417 }
418 }
419 throw new Error(
420 "The page's zoom kept changing while the snapshot read its size. Try the snapshot again.",
421 );
422};
423
424// Scaled captures repaint live screencasts, so callers pause them. Clips use document offsets.
425export const captureViewport = async (
426 page: Page,
427 cdp: CDPSession,
428 options: {
429 readonly format: "png" | "jpeg";
430 readonly quality?: number;
431 readonly scale: number;
432 readonly viewport?: Viewport;
433 readonly offset?: { readonly x: number; readonly y: number } | undefined;
434 },
435) => {
436 let clip;
437 if (options.scale < 1) {
438 const viewport = options.viewport ?? page.viewportSize() ?? { width: 1280, height: 800 };
439 let offset = options.offset;
440 if (!offset) {
441 const { cssVisualViewport } = await cdp.send("Page.getLayoutMetrics");
442 const zoom = cssVisualViewport.zoom ?? 1;
443 offset = { x: cssVisualViewport.pageX * zoom, y: cssVisualViewport.pageY * zoom };
444 }
445 clip = {
446 ...offset,
447 ...viewport,
448 scale: options.scale,
449 };
450 }
451 const { data } = await cdp.send("Page.captureScreenshot", {
452 format: options.format,
453 ...(options.quality === undefined ? {} : { quality: options.quality }),
454 ...(clip ? { clip } : {}),
455 });
456 return data;
457};
458
459type SnapshotInput = {
460 readonly page: Page;
461 readonly cdp: CDPSession;
462 /** Headless pages render at the scale the server set; a desktop page at its display's. */
463 readonly renderScale: number | "display";
464 readonly consoleEntries: ReadonlyArray<PreviewAutomationConsoleEntry>;
465 readonly networkEntries: ReadonlyArray<PreviewAutomationNetworkEntry>;
466 readonly actionTimeline: PreviewAutomationSnapshot["actionTimeline"];
467};
468
469/** The scale a page renders at and its viewport in device-independent pixels, a clip's units. */
470const renderingOf = async (input: SnapshotInput) => {
471 if (input.renderScale !== "display") {
472 const viewport = input.page.viewportSize() ?? { width: 1280, height: 800 };
473 return { renderScale: input.renderScale, viewport, offset: undefined };
474 }
475 // The display ratio a desktop page reports includes its page zoom, and its sizes are CSS pixels.
476 const page = await readPageMetrics(input.cdp);
477 return {
478 renderScale: page.ratio / page.zoom,
479 offset: page.offset,
480 viewport: {
481 width: Math.round(page.width * page.zoom),
482 height: Math.round(page.height * page.zoom),
483 },
484 };
485};
486
487const capture = async (
488 input: SnapshotInput,
489 deadline: number,
490): Promise<PreviewAutomationSnapshot> => {
491 const { renderScale, viewport, offset } = await renderingOf(input);
492 // A late metrics reply must not begin a capture after viewers have resumed.
493 if (Date.now() >= deadline) throw tooBusy();
494 const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * renderScale));
495 const state = refsFor(input.page);
496 invalidateRefs(input.page);
497 const generation = state.generation;
498 const { readers, read } = await openReaders(input.page, input.cdp);
499 const before = await read();
500 // Taken between the reads, so a value that changes during either fails the comparison.
501 // Awaited after the tree: a capture that fails has finished its tree before a retry starts.
502 const pageAndScreenshot = Promise.all([
503 input.page.evaluate(SNAPSHOT_SCRIPT) as Promise<
504 Pick<
505 PreviewAutomationSnapshot,
506 "url" | "title" | "loading" | "visibleText" | "interactiveElements"
507 >
508 >,
509 captureViewport(input.page, input.cdp, { format: "png", scale, viewport, offset }),
510 ]);
511 void pageAndScreenshot.catch(constVoid);
512 // Leaves time for the second read; a frame that never loads holds the tree until then.
513 const tree = await input.page.ariaSnapshot({
514 mode: "ai",
515 boxes: true,
516 timeout: Math.max(1, deadline - Date.now() - 2_000),
517 });
518 const after = await read(before);
519 // A value that changed meanwhile may be in the tree under neither reading.
520 if (after.some((values, i) => values && JSON.stringify(values) !== JSON.stringify(before[i])))
521 throw pageChanged();
522 const dotted = dottedPattern(after.flatMap((values) => values ?? []));
523 // A frame that didn't answer both times, such as one that crashed, can only hold values the
524 // tree shows if the tree shows its content.
525 const unread = readers.flatMap((reader, i) => (after[i] ? [] : reader.frames));
526 const filled = /^\s*- iframe (?:\[active\] )?\[ref=(\S+?)\].*:$/gm;
527 for (const [, ref] of unread.length ? tree.matchAll(filled) : []) {
528 const iframe = await input.page.locator(`aria-ref=${ref}`).elementHandle({ timeout: 2_000 });
529 if (!iframe) throw pageChanged();
530 const frame = await iframe.contentFrame();
531 void iframe.dispose().catch(constVoid);
532 if (frame && unread.includes(frame)) throw tooBusy();
533 }
534 const [page, data] = await pageAndScreenshot;
535 if (state.generation !== generation) throw pageChanged();
536 const mask = (text: string) => (dotted ? text.replace(dotted, MASKED_VALUE) : text);
537 const accessibilityTree = (dotted ? maskTree(tree, dotted) : tree)
538 .slice(0, MAX_VISIBLE_TEXT_LENGTH)
539 .replace(/\[ref=((?:f\d+)?e\d+)\]/g, (_match, nativeRef: string) => {
540 const ref = `t3-${generation}-${nativeRef}`;
541 state.refs.set(ref, nativeRef);
542 return `[ref=${ref}]`;
543 });
544 return {
545 ...page,
546 // Text that holds a value would otherwise show where the tree masked it. Masked before
547 // the cut, so a value crossing it can't leave its start showing.
548 visibleText: mask(page.visibleText).slice(0, MAX_VISIBLE_TEXT_LENGTH),
549 accessibilityTree,
550 consoleEntries: [...input.consoleEntries],
551 networkEntries: [...input.networkEntries],
552 actionTimeline: [...input.actionTimeline],
553 screenshot: {
554 mimeType: "image/png",
555 data,
556 ...pngSize(data),
557 },
558 };
559};
560
561/** Snapshots begun per page; observers' snapshots aren't queued, so two can overlap. */
562const snapshotTurns = new WeakMap<Page, number>();
563
564export const snapshot = async (input: SnapshotInput): Promise<PreviewAutomationSnapshot> => {
565 const deadline = Date.now() + SNAPSHOT_TIMEOUT_MS;
566 let timer: ReturnType<typeof setTimeout> | undefined;
567 const expired = new Promise<never>((_, reject) => {
568 timer = setTimeout(() => reject(tooBusy()), SNAPSHOT_TIMEOUT_MS);
569 });
570 const turn = (snapshotTurns.get(input.page) ?? 0) + 1;
571 snapshotTurns.set(input.page, turn);
572 // A page that changed mid-capture, like one rotating ads, has usually settled by a second
573 // try. None starts late or after another snapshot began, since it would revoke the refs of
574 // whichever snapshot came next.
575 const captured = capture(input, deadline).catch((cause: unknown) =>
576 Date.now() < deadline &&
577 snapshotTurns.get(input.page) === turn &&
578 !(cause instanceof Error && cause.message === VALUE_TOO_LONG)
579 ? capture(input, deadline)
580 : Promise.reject(cause),
581 );
582 try {
583 return await Promise.race([captured, expired]);
584 } catch (cause) {
585 throw cause instanceof Error && cause.name === "TimeoutError" ? tooBusy() : cause;
586 } finally {
587 clearTimeout(timer);
588 }
589};
590
591/**
592 * A click whose handler opens a dialog does not finish until the dialog is
593 * resolved, so it returns as soon as the dialog opens; status then reports it.
594 */
595export const click = async (
596 page: Page,
597 input: PreviewAutomationClickInput,
598 pointer: PointerReporter = noPointer,
599): Promise<{ readonly x: number; readonly y: number }> => {
600 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
601 const locator = targetLocator(page, input);
602 const point = await targetPoint(page, locator, input, timeout);
603 await pointer(point, "click");
604 const options = { button: input.button ?? "left", clickCount: input.clickCount ?? 1 } as const;
605 const clicked =
606 locator === null
607 ? page.mouse.click(point.x, point.y, options)
608 : locator.click({ ...options, timeout });
609 let onDialog = constVoid;
610 const dialogOpened = new Promise<"dialog">((resolve) => {
611 onDialog = () => resolve("dialog");
612 page.once("dialog", onDialog);
613 });
614 try {
615 if ((await Promise.race([clicked, dialogOpened])) === "dialog") void clicked.catch(constVoid);
616 } finally {
617 page.off("dialog", onDialog);
618 }
619 return point;
620};
621
622export const type = async (page: Page, input: PreviewAutomationTypeInput) => {
623 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
624 const locator = targetLocator(page, input);
625 if (locator !== null && input.clear) {
626 await locator.fill(input.text, { timeout });
627 return;
628 }
629 // A shadow host also matches :focus; use its innermost focused descendant.
630 const target = locator ?? page.locator("*:focus").last();
631 const focused =
632 (locator !== null || (await target.count()) > 0) &&
633 (await target.evaluate(
634 (element) => {
635 // Like the desktop host: an enabled text control or contenteditable
636 // that actually takes focus. Anything else would swallow the text or
637 // send it to whichever field had focus before.
638 const control = element as unknown as {
639 readonly type?: string;
640 readonly disabled?: boolean;
641 readonly readOnly?: boolean;
642 readonly isContentEditable?: boolean;
643 readonly focus?: () => void;
644 };
645 const nonText = [
646 "button",
647 "checkbox",
648 "color",
649 "file",
650 "hidden",
651 "image",
652 "radio",
653 "range",
654 "reset",
655 "submit",
656 ];
657 const textControl =
658 element.tagName === "TEXTAREA" ||
659 (element.tagName === "INPUT" && !nonText.includes(control.type ?? "text"));
660 if (!(textControl || control.isContentEditable) || control.disabled || control.readOnly) {
661 return false;
662 }
663 control.focus?.();
664 const root = element.getRootNode() as { readonly activeElement?: typeof element | null };
665 const active = root.activeElement;
666 return active != null && (active === element || element.contains(active));
667 },
668 undefined,
669 { timeout },
670 ));
671 if (focused !== true) {
672 throw new ServerBrowserOperationError(
673 "PreviewAutomationTargetNotEditableError",
674 "The target is not an enabled text field, so no text was typed.",
675 );
676 }
677 if (input.clear) {
678 await page.keyboard.press("ControlOrMeta+A");
679 await page.keyboard.press("Delete");
680 }
681 await page.keyboard.insertText(input.text);
682};
683
684export const hover = async (
685 page: Page,
686 input: PreviewAutomationHoverInput,
687 pointer: PointerReporter = noPointer,
688) => {
689 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
690 const locator = targetLocator(page, input);
691 await pointer(await targetPoint(page, locator, input, timeout), "move");
692 if (locator === null) {
693 await page.mouse.move(input.x ?? 0, input.y ?? 0);
694 return;
695 }
696 await locator.hover({ timeout });
697};
698
699export const select = async (
700 page: Page,
701 input: PreviewAutomationSelectInput,
702): Promise<PreviewAutomationSelectResult> => {
703 const locator = targetLocator(page, input)!;
704 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
705 const options = await locator.evaluate(
706 (element) =>
707 element.tagName === "SELECT"
708 ? Array.from(
709 (element as unknown as { options: ArrayLike<{ value: string; label: string }> })
710 .options,
711 ({ value, label }) => ({ value, label: label.trim() }),
712 )
713 : null,
714 undefined,
715 { timeout },
716 );
717 const values =
718 options &&
719 input.values.map(
720 (entry) =>
721 (
722 options.find((option) => option.value === entry) ??
723 options.find((option) => option.label === entry.trim())
724 )?.value ?? entry,
725 );
726 if (values === null)
727 throw new ServerBrowserOperationError(
728 "PreviewAutomationTargetNotEditableError",
729 "This element is not a <select>. Click a custom dropdown, then click its option.",
730 );
731 return { selected: await locator.selectOption(values, { timeout }) };
732};
733
734export const drag = async (
735 page: Page,
736 input: PreviewAutomationDragInput,
737 pointer: PointerReporter = noPointer,
738) => {
739 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
740 const source = targetLocator(page, { locator: input.source })!;
741 const target = targetLocator(page, { locator: input.target })!;
742 await pointer(await targetPoint(page, source, {}, timeout), "move");
743 // Observe the drag's outcome as it starts: a rejection nobody handles while the cursor
744 // moves exits the server.
745 const dragFailure = source.dragTo(target, { timeout }).then(
746 () => null,
747 (error: unknown) => ({ error }),
748 );
749 const end = await target.boundingBox({ timeout }).catch(() => null);
750 if (end) await pointer({ x: end.x + end.width / 2, y: end.y + end.height / 2 }, "move");
751 const failure = await dragFailure;
752 if (failure) throw failure.error;
753};
754
755export const setInputFiles = async (page: Page, input: PreviewAutomationUploadInput) => {
756 const locator = targetLocator(page, input);
757 if (locator === null) return false;
758 await locator.setInputFiles([...input.paths], { timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS });
759 return true;
760};
761
762export const press = async (page: Page, input: PreviewAutomationPressInput) => {
763 await page.keyboard.press([...(input.modifiers ?? []), input.key].join("+"));
764};
765
766export const scroll = async (page: Page, input: PreviewAutomationScrollInput) => {
767 const delta = [input.deltaX ?? 0, input.deltaY ?? 0] as const;
768 const locator = targetLocator(page, input);
769 if (locator === null) {
770 // Page-side code is passed as source: the server compiles without DOM types.
771 await page.evaluate(`scrollBy(${delta[0]}, ${delta[1]})`);
772 return;
773 }
774 await locator.evaluate((element, [x, y]) => element.scrollBy(x, y), delta);
775};
776
777/**
778 * Runs an agent's expression, bounded by its request's deadline. Past it, the
779 * page's script is terminated and the call fails, so the tab's control queue
780 * frees for the next request instead of waiting on the script.
781 */
782export const evaluate = async (
783 cdp: CDPSession,
784 input: PreviewAutomationEvaluateInput,
785 timeoutMs: number,
786) => {
787 let timer: ReturnType<typeof setTimeout> | undefined;
788 const expired = new Promise<never>((_, reject) => {
789 timer = setTimeout(() => {
790 // Stops a busy script; an awaited promise is abandoned and settles unread.
791 void cdp.send("Runtime.terminateExecution").catch(constVoid);
792 reject(
793 new ServerBrowserOperationError(
794 "PreviewAutomationTimeoutError",
795 `Evaluation did not finish within ${timeoutMs}ms and was stopped.`,
796 ),
797 );
798 }, timeoutMs);
799 });
800 const evaluation = cdp.send("Runtime.evaluate", {
801 expression: input.expression,
802 awaitPromise: input.awaitPromise ?? true,
803 returnByValue: input.returnByValue ?? true,
804 });
805 void evaluation.catch(constVoid);
806 const result = await Promise.race([evaluation, expired]).finally(() => clearTimeout(timer));
807 if (result.exceptionDetails) {
808 throw new ServerBrowserOperationError(
809 "PreviewAutomationExecutionError",
810 result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,
811 );
812 }
813 const value =
814 "value" in result.result ? result.result.value : (result.result.description ?? null);
815 const actualBytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8");
816 if (actualBytes > MAX_EVALUATION_BYTES) {
817 throw new ServerBrowserOperationError(
818 "PreviewAutomationResultTooLargeError",
819 `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,
820 { maximumBytes: MAX_EVALUATION_BYTES },
821 );
822 }
823 return value;
824};
825
826export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput) => {
827 const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
828 const deadline = Date.now() + timeoutMs;
829 const locator = targetLocator(page, input);
830 const { text, urlIncludes } = input;
831 const checks: Array<() => Promise<boolean>> = [];
832 if (locator !== null) checks.push(async () => (await locator.count()) > 0);
833 if (text !== undefined) {
834 // A navigation can destroy the context mid-check; that counts as not yet.
835 checks.push(() =>
836 page
837 .evaluate(`(document.body?.innerText ?? "").includes(${JSON.stringify(text)})`)
838 .then((found) => found === true)
839 .catch(() => false),
840 );
841 }
842 if (urlIncludes !== undefined) checks.push(async () => page.url().includes(urlIncludes));
843 for (;;) {
844 const results = await Promise.all(checks.map((check) => check()));
845 if (results.every(Boolean)) return;
846 if (Date.now() >= deadline) {
847 throw new ServerBrowserOperationError(
848 "PreviewAutomationTimeoutError",
849 `Waited ${timeoutMs}ms without every condition holding.`,
850 );
851 }
852 await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS));
853 }
854};
855
856const NET_ERROR_CODES: Readonly<Record<string, number>> = {
857 ERR_FAILED: -2,
858 ERR_TIMED_OUT: -7,
859 ERR_CONNECTION_CLOSED: -100,
860 ERR_CONNECTION_RESET: -101,
861 ERR_CONNECTION_REFUSED: -102,
862 ERR_NAME_NOT_RESOLVED: -105,
863 ERR_INTERNET_DISCONNECTED: -106,
864 ERR_ADDRESS_UNREACHABLE: -109,
865 ERR_CERT_AUTHORITY_INVALID: -202,
866 ERR_EMPTY_RESPONSE: -324,
867};
868
869export const parseNetError = (errorText: string) => {
870 const description = /ERR_[A-Z_]+/.exec(errorText)?.[0] ?? errorText;
871 return { description, code: NET_ERROR_CODES[description] ?? -2 };
872};
873
874export const RECORDING_ENCODER_SCRIPT = `(() => {
875 const canvas = document.createElement("canvas");
876 const context = canvas.getContext("2d");
877 const chunks = [];
878 let recorder = null;
879 let started = null;
880 let stopped = null;
881 let sizeBytes = 0;
882 let tooLarge = false;
883 let frame = null;
884 let cursor = null;
885 let ring = null;
886 const AGENT_CURSOR_PATH = new Path2D("M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z");
887 let ringTimer = null;
888 let scale = 1;
889 let offsetX = 0;
890 let offsetY = 0;
891 const paint = () => {
892 if (!frame) return;
893 const fit = Math.min(canvas.width / frame.width, canvas.height / frame.height);
894 const width = frame.width * fit;
895 const height = frame.height * fit;
896 offsetX = (canvas.width - width) / 2;
897 offsetY = (canvas.height - height) / 2;
898 if (width < canvas.width || height < canvas.height) {
899 context.fillStyle = "#000";
900 context.fillRect(0, 0, canvas.width, canvas.height);
901 }
902 context.drawImage(frame, offsetX, offsetY, width, height);
903 scale = (width / frame.width) * frame.cssScale;
904 if (ring) {
905 const age = (performance.now() - ring.at) / 400;
906 if (age < 1) {
907 context.beginPath();
908 context.arc(offsetX + ring.x * scale, offsetY + ring.y * scale, (8 + 18 * age) * scale, 0, Math.PI * 2);
909 context.strokeStyle = "rgba(59,130,246," + (0.9 * (1 - age)) + ")";
910 context.lineWidth = 3 * scale;
911 context.stroke();
912 }
913 }
914 if (cursor) {
915 // The agent cursor (lucide MousePointer2, as in the live panel), never the human arrow.
916 const s = 20 / 24 * scale;
917 context.save();
918 context.translate(offsetX + cursor.x * scale - 2 * scale, offsetY + cursor.y * scale - 2 * scale);
919 context.scale(s, s);
920 context.lineWidth = 2;
921 context.lineJoin = "round";
922 context.lineCap = "round";
923 context.fillStyle = "#fff";
924 context.strokeStyle = "#2563eb";
925 context.shadowColor = "rgba(0,0,0,0.25)";
926 context.shadowBlur = 2;
927 context.fill(AGENT_CURSOR_PATH);
928 context.shadowColor = "transparent";
929 context.stroke(AGENT_CURSOR_PATH);
930 context.restore();
931 }
932 };
933 window.__t3Recorder = {
934 async frame(base64, cssWidth) {
935 if (tooLarge) return false;
936 const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
937 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" }));
938 if (tooLarge) { bitmap.close(); return false; }
939 if (!recorder) {
940 canvas.width = bitmap.width;
941 canvas.height = bitmap.height;
942 const mimeType = ["video/mp4;codecs=avc1.640033", "video/webm;codecs=vp9", "video/webm"].find((type) => MediaRecorder.isTypeSupported(type));
943 const bitsPerSecond = Math.min(50e6, Math.max(2.5e6, bitmap.width * bitmap.height * 30 * 0.05));
944 recorder = new MediaRecorder(canvas.captureStream(30), { mimeType, videoBitsPerSecond: bitsPerSecond });
945 started = new Promise((resolve, reject) => {
946 recorder.onstart = resolve;
947 recorder.onerror = (event) => reject(event.error);
948 });
949 stopped = new Promise((resolve) => { recorder.onstop = resolve; });
950 recorder.ondataavailable = (event) => {
951 if (tooLarge || event.data.size === 0) return;
952 sizeBytes += event.data.size;
953 if (sizeBytes > ${PROVIDER_SEND_TURN_MAX_FILE_BYTES}) {
954 tooLarge = true;
955 chunks.length = 0;
956 clearInterval(ringTimer);
957 frame?.close();
958 frame = null;
959 if (recorder.state !== "inactive") recorder.stop();
960 for (const track of recorder.stream.getTracks()) track.stop();
961 return;
962 }
963 chunks.push(event.data);
964 };
965 recorder.start(1000);
966 }
967 // Frame px per page CSS px, before fitting into the canvas.
968 bitmap.cssScale = bitmap.width / cssWidth;
969 frame?.close();
970 frame = bitmap;
971 paint();
972 await started;
973 return true;
974 },
975 cursor(x, y, click) {
976 if (tooLarge) return;
977 cursor = { x, y };
978 if (click) {
979 ring = { x, y, at: performance.now() };
980 clearInterval(ringTimer);
981 ringTimer = setInterval(() => {
982 paint();
983 if (performance.now() - ring.at > 400) { ring = null; clearInterval(ringTimer); paint(); }
984 }, 33);
985 }
986 paint();
987 },
988 async stop() {
989 if (!recorder) return { mimeType: null, count: 0, bytes: 0 };
990 if (recorder.state !== "inactive") {
991 // Consume the cached frame, then wait for the final paint to reach the
992 // capture stream. Animation ticks alone can stop before it is delivered.
993 const video = document.createElement("video");
994 video.muted = true;
995 video.srcObject = recorder.stream;
996 const nextFrame = () => Promise.race([
997 new Promise(resolve => video.requestVideoFrameCallback(resolve)),
998 stopped,
999 ]);
1000 const initial = nextFrame();
1001 void video.play().catch(() => {});
1002 await initial;
1003 if (recorder.state !== "inactive") {
1004 const delivered = nextFrame();
1005 recorder.stream.getVideoTracks()[0].requestFrame();
1006 paint();
1007 await delivered;
1008 }
1009 video.pause();
1010 video.srcObject = null;
1011 if (recorder.state !== "inactive") recorder.stop();
1012 }
1013 await stopped;
1014 return { mimeType: recorder.mimeType, count: chunks.length, bytes: sizeBytes };
1015 },
1016 async chunk(index) {
1017 const bytes = new Uint8Array(await chunks[index].arrayBuffer());
1018 let binary = "";
1019 for (let offset = 0; offset < bytes.length; offset += 0x8000) {
1020 binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
1021 }
1022 return btoa(binary);
1023 },
1024 };
1025})()`;