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