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