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