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