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