Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ServerBrowserPage.ts

1,052 lines40.7 KB

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