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