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

ServerBrowserPage.ts

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