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

ServerBrowserPage.ts

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