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

ServerBrowserPage.ts

1,126 lines43.6 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 consoleEntries: ReadonlyArray<PreviewAutomationConsoleEntry>;
523 readonly networkEntries: ReadonlyArray<PreviewAutomationNetworkEntry>;
524 readonly actionTimeline: PreviewAutomationSnapshot["actionTimeline"];
525};
526​
527/** The scale a page renders at and its viewport in device-independent pixels. */
528const renderingOf = async (input: SnapshotInput) => {
529 if (input.renderScale !== "display") {
530 const viewport = input.page.viewportSize() ?? { width: 1280, height: 800 };
531 return { renderScale: input.renderScale, viewport };
532 }
533 // The display ratio a desktop page reports includes its page zoom, and its sizes are CSS pixels.
534 const page = await readPageMetrics(input.cdp);
535 return {
536 renderScale: page.ratio / page.zoom,
537 viewport: {
538 width: Math.round(page.width * page.zoom),
539 height: Math.round(page.height * page.zoom),
540 },
541 };
542};
543​
544const capture = async (
545 input: SnapshotInput,
546 deadline: number,
547): Promise<PreviewAutomationSnapshot> => {
548 const { renderScale, viewport } = await renderingOf(input);
549 // A late metrics reply must not begin a capture after viewers have resumed.
550 if (Date.now() >= deadline) throw tooBusy();
551 const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * renderScale));
552 const state = refsFor(input.page);
553 invalidateRefs(input.page);
554 const generation = state.generation;
555 const { readers, read } = await openReaders(input.page, input.cdp);
556 const before = await read();
557 // Bracket the tree with value reads to detect changes; await tree completion before retrying failed captures.
558 const pageAndScreenshot = Promise.all([
559 input.page.evaluate(SNAPSHOT_SCRIPT) as Promise<
560 Pick<
561 PreviewAutomationSnapshot,
562 "url" | "title" | "loading" | "visibleText" | "interactiveElements"
563 >
564 >,
565 captureViewport(input.cdp, { format: "png" }).then((png) =>
566 scale < 1 ? shrinkPng(input.cdp, png, scale) : png,
567 ),
568 ]);
569 void pageAndScreenshot.catch(constVoid);
570 // Leaves time for the second read; a frame that never loads holds the tree until then.
571 const tree = await input.page.ariaSnapshot({
572 mode: "ai",
573 boxes: true,
574 timeout: Math.max(1, deadline - Date.now() - 2_000),
575 });
576 const after = await read(before);
577 // A value that changed meanwhile may be in the tree under neither reading.
578 if (after.some((values, i) => values && JSON.stringify(values) !== JSON.stringify(before[i])))
579 throw pageChanged();
580 const dotted = dottedPattern(after.flatMap((values) => values ?? []));
581 // Unread frames can expose values only if their content appears in the tree.
582 const unread = readers.flatMap((reader, i) => (after[i] ? [] : reader.frames));
583 const filled = /^\s*- iframe (?:\[active\] )?\[ref=(\S+?)\].*:$/gm;
584 for (const [, ref] of unread.length ? tree.matchAll(filled) : []) {
585 const iframe = await input.page.locator(`aria-ref=${ref}`).elementHandle({ timeout: 2_000 });
586 if (!iframe) throw pageChanged();
587 const frame = await iframe.contentFrame();
588 void iframe.dispose().catch(constVoid);
589 if (frame && unread.includes(frame)) throw tooBusy();
590 }
591 const [page, data] = await pageAndScreenshot;
592 if (state.generation !== generation) throw pageChanged();
593 const mask = (text: string) => (dotted ? text.replace(dotted, MASKED_VALUE) : text);
594 // Redacted before the cut, so a payload crossing it can't leave its start showing, and before
595 // masking, which could hide the `data:` scheme behind a password value's dots.
596 const redacted = withoutTreeDataPayloads(tree);
597 const accessibilityTree = (dotted ? maskTree(redacted, dotted) : redacted)
598 .slice(0, MAX_VISIBLE_TEXT_LENGTH)
599 .replace(/\[ref=((?:f\d+)?e\d+)\]/g, (_match, nativeRef: string) => {
600 const ref = `t3-${generation}-${nativeRef}`;
601 state.refs.set(ref, nativeRef);
602 return `[ref=${ref}]`;
603 });
604 return {
605 ...page,
606 url: withoutDataPayload(page.url),
607 // Mask text before truncating so a value crossing the cut cannot leak its prefix.
608 visibleText: mask(page.visibleText).slice(0, MAX_VISIBLE_TEXT_LENGTH),
609 accessibilityTree,
610 consoleEntries: [...input.consoleEntries],
611 networkEntries: [...input.networkEntries],
612 actionTimeline: [...input.actionTimeline],
613 screenshot: {
614 mimeType: "image/png",
615 data,
616 ...pngSize(data),
617 },
618 };
619};
620​
621/** Snapshots begun per page; observers' snapshots aren't queued, so two can overlap. */
622const snapshotTurns = new WeakMap<Page, number>();
623​
624export const snapshot = async (input: SnapshotInput): Promise<PreviewAutomationSnapshot> => {
625 const deadline = Date.now() + SNAPSHOT_TIMEOUT_MS;
626 let timer: ReturnType<typeof setTimeout> | undefined;
627 const expired = new Promise<never>((_, reject) => {
628 timer = setTimeout(() => reject(tooBusy()), SNAPSHOT_TIMEOUT_MS);
629 });
630 const turn = (snapshotTurns.get(input.page) ?? 0) + 1;
631 snapshotTurns.set(input.page, turn);
632 // Retry only before the deadline and the next snapshot, whose refs a later retry would revoke.
633 const captured = capture(input, deadline).catch((cause: unknown) =>
634 Date.now() < deadline &&
635 snapshotTurns.get(input.page) === turn &&
636 !(cause instanceof Error && cause.message === VALUE_TOO_LONG)
637 ? capture(input, deadline)
638 : Promise.reject(cause),
639 );
640 try {
641 return await Promise.race([captured, expired]);
642 } catch (cause) {
643 throw cause instanceof Error && cause.name === "TimeoutError" ? tooBusy() : cause;
644 } finally {
645 clearTimeout(timer);
646 }
647};
648​
649/** Return when a dialog opens; waiting for the action to finish would block until dialog resolution. */
650export const click = async (
651 page: Page,
652 input: PreviewAutomationClickInput,
653 pointer: PointerReporter = noPointer,
654): Promise<{ readonly x: number; readonly y: number }> => {
655 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
656 const locator = targetLocator(page, input);
657 try {
658 return await clickTarget(page, locator, input, timeout, pointer);
659 } catch (cause) {
660 throw locator === null ? cause : await namedTargetTimeout(locator, input, cause);
661 }
662};
663​
664/**
665 * Playwright's timeout names neither the target nor why it waited. Counting only after the
666 * wait failed keeps auto-wait intact, but the count describes the page after the timeout, not
667 * what the click did: Playwright can dispatch the click and then time out waiting for the
668 * navigation it started.
669 */
670const namedTargetTimeout = async (
671 locator: Locator,
672 input: { readonly locator?: string | undefined; readonly selector?: string | undefined },
673 cause: unknown,
674) => {
675 if (!(cause instanceof Error && cause.name === "TimeoutError")) return cause;
676 const selector = JSON.stringify(input.locator ?? input.selector);
677 // The warning leads and the target is capped, so a reply cut short still carries the warning.
678 const target =
679 selector.length > MAX_TARGET_CHARS ? `${selector.slice(0, MAX_TARGET_CHARS)}...` : selector;
680 // The host's reply must still beat the broker's short grace after the operation timeout.
681 let timer: ReturnType<typeof setTimeout> | undefined;
682 const matches = await Promise.race([
683 locator.count().catch(() => undefined),
684 new Promise<undefined>((resolve) => {
685 timer = setTimeout(() => resolve(undefined), TARGET_COUNT_MS);
686 }),
687 ]).finally(() => clearTimeout(timer));
688 const reason =
689 matches === undefined
690 ? `The click may have happened; check the page before retrying. Whether ${target} still matches an element is unknown.`
691 : matches === 0
692 ? `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.`
693 : `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`;
694 return new ServerBrowserOperationError({
695 tag: "PreviewAutomationTimeoutError",
696 message: reason,
697 detail: { reason },
698 cause,
699 });
700};
701​
702const clickTarget = async (
703 page: Page,
704 locator: Locator | null,
705 input: PreviewAutomationClickInput,
706 timeout: number,
707 pointer: PointerReporter,
708) => {
709 const point = await targetPoint(page, locator, input, timeout);
710 await pointer(point, "click");
711 const options = { button: input.button ?? "left", clickCount: input.clickCount ?? 1 } as const;
712 const clicked =
713 locator === null
714 ? page.mouse.click(point.x, point.y, options)
715 : locator.click({ ...options, timeout });
716 let onDialog = constVoid;
717 const dialogOpened = new Promise<"dialog">((resolve) => {
718 onDialog = () => resolve("dialog");
719 page.once("dialog", onDialog);
720 });
721 try {
722 if ((await Promise.race([clicked, dialogOpened])) === "dialog") void clicked.catch(constVoid);
723 } finally {
724 page.off("dialog", onDialog);
725 }
726 return point;
727};
728​
729export const type = async (page: Page, input: PreviewAutomationTypeInput) => {
730 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
731 const locator = targetLocator(page, input);
732 if (locator !== null && input.clear) {
733 await locator.fill(input.text, { timeout });
734 return;
735 }
736 // A shadow host also matches :focus; use its innermost focused descendant.
737 const target = locator ?? page.locator("*:focus").last();
738 const focused =
739 (locator !== null || (await target.count()) > 0) &&
740 (await target.evaluate(
741 (element) => {
742 // Require an enabled, focused text target to avoid losing input or sending it to the previous field.
743 const control = element as unknown as {
744 readonly type?: string;
745 readonly disabled?: boolean;
746 readonly readOnly?: boolean;
747 readonly isContentEditable?: boolean;
748 readonly focus?: () => void;
749 };
750 const nonText = [
751 "button",
752 "checkbox",
753 "color",
754 "file",
755 "hidden",
756 "image",
757 "radio",
758 "range",
759 "reset",
760 "submit",
761 ];
762 const textControl =
763 element.tagName === "TEXTAREA" ||
764 (element.tagName === "INPUT" && !nonText.includes(control.type ?? "text"));
765 if (!(textControl || control.isContentEditable) || control.disabled || control.readOnly) {
766 return false;
767 }
768 control.focus?.();
769 const root = element.getRootNode() as { readonly activeElement?: typeof element | null };
770 const active = root.activeElement;
771 return active != null && (active === element || element.contains(active));
772 },
773 undefined,
774 { timeout },
775 ));
776 if (focused !== true) {
777 throw new ServerBrowserOperationError({
778 tag: "PreviewAutomationTargetNotEditableError",
779 message: "The target is not an enabled text field, so no text was typed.",
780 });
781 }
782 if (input.clear) {
783 await page.keyboard.press("ControlOrMeta+A");
784 await page.keyboard.press("Delete");
785 }
786 await page.keyboard.insertText(input.text);
787};
788​
789export const hover = async (
790 page: Page,
791 input: PreviewAutomationHoverInput,
792 pointer: PointerReporter = noPointer,
793) => {
794 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
795 const locator = targetLocator(page, input);
796 await pointer(await targetPoint(page, locator, input, timeout), "move");
797 if (locator === null) {
798 await page.mouse.move(input.x ?? 0, input.y ?? 0);
799 return;
800 }
801 await locator.hover({ timeout });
802};
803​
804export const select = async (
805 page: Page,
806 input: PreviewAutomationSelectInput,
807): Promise<PreviewAutomationSelectResult> => {
808 const locator = targetLocator(page, input)!;
809 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
810 const options = await locator.evaluate(
811 (element) =>
812 element.tagName === "SELECT"
813 ? Array.from(
814 (element as unknown as { options: ArrayLike<{ value: string; label: string }> })
815 .options,
816 ({ value, label }) => ({ value, label: label.trim() }),
817 )
818 : null,
819 undefined,
820 { timeout },
821 );
822 const values =
823 options &&
824 input.values.map(
825 (entry) =>
826 (
827 options.find((option) => option.value === entry) ??
828 options.find((option) => option.label === entry.trim())
829 )?.value ?? entry,
830 );
831 if (values === null)
832 throw new ServerBrowserOperationError({
833 tag: "PreviewAutomationTargetNotEditableError",
834 message: "This element is not a <select>. Click a custom dropdown, then click its option.",
835 });
836 return { selected: await locator.selectOption(values, { timeout }) };
837};
838​
839export const drag = async (
840 page: Page,
841 input: PreviewAutomationDragInput,
842 pointer: PointerReporter = noPointer,
843) => {
844 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
845 const source = targetLocator(page, { locator: input.source })!;
846 const target = targetLocator(page, { locator: input.target })!;
847 await pointer(await targetPoint(page, source, {}, timeout), "move");
848 // Observe drag rejection immediately; an unhandled rejection during cursor movement exits the server.
849 const dragFailure = source.dragTo(target, { timeout }).then(
850 () => null,
851 (error: unknown) => ({ error }),
852 );
853 const end = await target.boundingBox({ timeout }).catch(() => null);
854 if (end) await pointer({ x: end.x + end.width / 2, y: end.y + end.height / 2 }, "move");
855 const failure = await dragFailure;
856 if (failure) throw failure.error;
857};
858​
859export const setInputFiles = async (page: Page, input: PreviewAutomationUploadInput) => {
860 const locator = targetLocator(page, input);
861 if (locator === null) return false;
862 await locator.setInputFiles([...input.paths], { timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS });
863 return true;
864};
865​
866export const press = async (page: Page, input: PreviewAutomationPressInput) => {
867 await page.keyboard.press([...(input.modifiers ?? []), input.key].join("+"));
868};
869​
870export const scroll = async (page: Page, input: PreviewAutomationScrollInput) => {
871 const delta = [input.deltaX ?? 0, input.deltaY ?? 0] as const;
872 const locator = targetLocator(page, input);
873 if (locator === null) {
874 // Page-side code is passed as source: the server compiles without DOM types.
875 await page.evaluate(`scrollBy(${delta[0]}, ${delta[1]})`);
876 return;
877 }
878 await locator.evaluate((element, [x, y]) => element.scrollBy(x, y), delta);
879};
880​
881/** Terminate expired page scripts so a hung expression cannot block the tab's control queue. */
882export const evaluate = async (
883 cdp: CDPSession,
884 input: PreviewAutomationEvaluateInput,
885 timeoutMs: number,
886) => {
887 let timer: ReturnType<typeof setTimeout> | undefined;
888 const expired = new Promise<never>((_, reject) => {
889 timer = setTimeout(() => {
890 // Stops a busy script; an awaited promise is abandoned and settles unread.
891 void cdp.send("Runtime.terminateExecution").catch(constVoid);
892 reject(
893 new ServerBrowserOperationError({
894 tag: "PreviewAutomationTimeoutError",
895 message: `Evaluation did not finish within ${timeoutMs}ms and was stopped.`,
896 }),
897 );
898 }, timeoutMs);
899 });
900 const evaluation = cdp.send("Runtime.evaluate", {
901 expression: input.expression,
902 awaitPromise: input.awaitPromise ?? true,
903 returnByValue: input.returnByValue ?? true,
904 });
905 void evaluation.catch(constVoid);
906 const result = await Promise.race([evaluation, expired]).finally(() => clearTimeout(timer));
907 if (result.exceptionDetails) {
908 throw new ServerBrowserOperationError({
909 tag: "PreviewAutomationExecutionError",
910 message: result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,
911 });
912 }
913 const value =
914 "value" in result.result ? result.result.value : (result.result.description ?? null);
915 const actualBytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8");
916 if (actualBytes > MAX_EVALUATION_BYTES) {
917 throw new ServerBrowserOperationError({
918 tag: "PreviewAutomationResultTooLargeError",
919 message: `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,
920 detail: { maximumBytes: MAX_EVALUATION_BYTES },
921 });
922 }
923 return value;
924};
925​
926export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput) => {
927 const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
928 const deadline = Date.now() + timeoutMs;
929 const locator = targetLocator(page, input);
930 const { text, urlIncludes } = input;
931 const checks: Array<() => Promise<boolean>> = [];
932 if (locator !== null) checks.push(async () => (await locator.count()) > 0);
933 if (text !== undefined) {
934 // A navigation can destroy the context mid-check; that counts as not yet.
935 checks.push(() =>
936 page
937 .evaluate(`(document.body?.innerText ?? "").includes(${JSON.stringify(text)})`)
938 .then((found) => found === true)
939 .catch(() => false),
940 );
941 }
942 if (urlIncludes !== undefined) checks.push(async () => page.url().includes(urlIncludes));
943 for (;;) {
944 const results = await Promise.all(checks.map((check) => check()));
945 if (results.every(Boolean)) return;
946 if (Date.now() >= deadline) {
947 throw new ServerBrowserOperationError({
948 tag: "PreviewAutomationTimeoutError",
949 message: `Waited ${timeoutMs}ms without every condition holding.`,
950 });
951 }
952 await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS));
953 }
954};
955​
956const NET_ERROR_CODES: Readonly<Record<string, number>> = {
957 ERR_FAILED: -2,
958 ERR_TIMED_OUT: -7,
959 ERR_CONNECTION_CLOSED: -100,
960 ERR_CONNECTION_RESET: -101,
961 ERR_CONNECTION_REFUSED: -102,
962 ERR_NAME_NOT_RESOLVED: -105,
963 ERR_INTERNET_DISCONNECTED: -106,
964 ERR_ADDRESS_UNREACHABLE: -109,
965 ERR_CERT_AUTHORITY_INVALID: -202,
966 ERR_EMPTY_RESPONSE: -324,
967};
968​
969export const parseNetError = (errorText: string) => {
970 // Names can hold digits, as in ERR_HTTP2_PROTOCOL_ERROR.
971 const description = /ERR_[A-Z\d_]+/.exec(errorText)?.[0] ?? errorText;
972 return { description, code: NET_ERROR_CODES[description] ?? -2 };
973};
974​
975export const recordingEncoderScript = (frameRate: BrowserRecordingFrameRate) => `(() => {
976 const canvas = document.createElement("canvas");
977 const context = canvas.getContext("2d");
978 const chunks = [];
979 let recorder = null;
980 let started = null;
981 let stopped = null;
982 let sizeBytes = 0;
983 let tooLarge = false;
984 let frame = null;
985 let cursor = null;
986 let ring = null;
987 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");
988 let ringTimer = null;
989 let scale = 1;
990 let offsetX = 0;
991 let offsetY = 0;
992 const paint = () => {
993 if (!frame) return;
994 const fit = Math.min(canvas.width / frame.width, canvas.height / frame.height);
995 const width = frame.width * fit;
996 const height = frame.height * fit;
997 offsetX = (canvas.width - width) / 2;
998 offsetY = (canvas.height - height) / 2;
999 if (width < canvas.width || height < canvas.height) {
1000 context.fillStyle = "#000";
1001 context.fillRect(0, 0, canvas.width, canvas.height);
1003 context.drawImage(frame, offsetX, offsetY, width, height);
1004 scale = (width / frame.width) * frame.cssScale;
1005 if (ring) {
1006 const age = (performance.now() - ring.at) / 400;
1007 if (age < 1) {
1008 context.beginPath();
1009 context.arc(offsetX + ring.x * scale, offsetY + ring.y * scale, (8 + 18 * age) * scale, 0, Math.PI * 2);
1010 context.strokeStyle = "rgba(59,130,246," + (0.9 * (1 - age)) + ")";
1011 context.lineWidth = 3 * scale;
1012 context.stroke();
1015 if (cursor) {
1016 // The agent cursor (lucide MousePointer2, as in the live panel), never the human arrow.
1017 const s = 20 / 24 * scale;
1018 context.save();
1019 context.translate(offsetX + cursor.x * scale - 2 * scale, offsetY + cursor.y * scale - 2 * scale);
1020 context.scale(s, s);
1021 context.lineWidth = 2;
1022 context.lineJoin = "round";
1023 context.lineCap = "round";
1024 context.fillStyle = "#fff";
1025 context.strokeStyle = "#2563eb";
1026 context.shadowColor = "rgba(0,0,0,0.25)";
1027 context.shadowBlur = 2;
1028 context.fill(AGENT_CURSOR_PATH);
1029 context.shadowColor = "transparent";
1030 context.stroke(AGENT_CURSOR_PATH);
1031 context.restore();
1033 };
1034 window.__t3Recorder = {
1035 async frame(base64, cssWidth) {
1036 if (tooLarge) return false;
1037 const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
1038 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" }));
1039 if (tooLarge) { bitmap.close(); return false; }
1040 if (!recorder) {
1041 canvas.width = bitmap.width;
1042 canvas.height = bitmap.height;
1043 const mimeType = ["video/mp4;codecs=avc1.640033", "video/webm;codecs=vp9", "video/webm"].find((type) => MediaRecorder.isTypeSupported(type));
1044 const bitsPerSecond = Math.min(50e6, Math.max(2.5e6, bitmap.width * bitmap.height * ${frameRate} * 0.05));
1045 recorder = new MediaRecorder(canvas.captureStream(${frameRate}), { mimeType, videoBitsPerSecond: bitsPerSecond });
1046 started = new Promise((resolve, reject) => {
1047 recorder.onstart = resolve;
1048 recorder.onerror = (event) => reject(event.error);
1049 });
1050 stopped = new Promise((resolve) => { recorder.onstop = resolve; });
1051 recorder.ondataavailable = (event) => {
1052 if (tooLarge || event.data.size === 0) return;
1053 sizeBytes += event.data.size;
1054 if (sizeBytes > ${PROVIDER_SEND_TURN_MAX_FILE_BYTES}) {
1055 tooLarge = true;
1056 chunks.length = 0;
1057 clearInterval(ringTimer);
1058 frame?.close();
1059 frame = null;
1060 if (recorder.state !== "inactive") recorder.stop();
1061 for (const track of recorder.stream.getTracks()) track.stop();
1062 return;
1064 chunks.push(event.data);
1065 };
1066 recorder.start(1000);
1068 // Frame px per page CSS px, before fitting into the canvas.
1069 bitmap.cssScale = bitmap.width / cssWidth;
1070 frame?.close();
1071 frame = bitmap;
1072 paint();
1073 await started;
1074 return true;
1075 },
1076 cursor(x, y, click) {
1077 if (tooLarge) return;
1078 cursor = { x, y };
1079 if (click) {
1080 ring = { x, y, at: performance.now() };
1081 clearInterval(ringTimer);
1082 ringTimer = setInterval(() => {
1083 paint();
1084 if (performance.now() - ring.at > 400) { ring = null; clearInterval(ringTimer); paint(); }
1085 }, 33);
1087 paint();
1088 },
1089 async stop() {
1090 if (!recorder) return { mimeType: null, count: 0, bytes: 0 };
1091 if (recorder.state !== "inactive") {
1092 // Consume the cached frame, then wait for the final paint to reach the
1093 // capture stream. Animation ticks alone can stop before it is delivered.
1094 const video = document.createElement("video");
1095 video.muted = true;
1096 video.srcObject = recorder.stream;
1097 const nextFrame = () => Promise.race([
1098 new Promise(resolve => video.requestVideoFrameCallback(resolve)),
1099 stopped,
1100 ]);
1101 const initial = nextFrame();
1102 void video.play().catch(() => {});
1103 await initial;
1104 if (recorder.state !== "inactive") {
1105 const delivered = nextFrame();
1106 recorder.stream.getVideoTracks()[0].requestFrame();
1107 paint();
1108 await delivered;
1110 video.pause();
1111 video.srcObject = null;
1112 if (recorder.state !== "inactive") recorder.stop();
1114 await stopped;
1115 return { mimeType: recorder.mimeType, count: chunks.length, bytes: sizeBytes };
1116 },
1117 async chunk(index) {
1118 const bytes = new Uint8Array(await chunks[index].arrayBuffer());
1119 let binary = "";
1120 for (let offset = 0; offset < bytes.length; offset += 0x8000) {
1121 binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
1123 return btoa(binary);
1124 },
1125 };
1126})()`;