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