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
956/** Terminate expired page scripts so a hung expression cannot block the tab's control queue. */
957export const evaluate = async (
958 cdp: CDPSession,
959 input: PreviewAutomationEvaluateInput,
960 timeoutMs: number,
961) => {
962 let timer: ReturnType<typeof setTimeout> | undefined;
963 let timedOut = false;
964 const expired = new Promise<never>((_, reject) => {
965 timer = setTimeout(() => {
966 timedOut = true;
967 // Stops a busy script; an awaited promise is abandoned and settles unread.
968 void cdp.send("Runtime.terminateExecution").catch(constVoid);
969 reject(
970 new ServerBrowserOperationError({
971 tag: "PreviewAutomationTimeoutError",
972 message: `Evaluation did not finish within ${timeoutMs}ms and was stopped.`,
973 }),
974 );
975 }, timeoutMs);
976 });
977 const params = {
978 expression: input.expression,
979 awaitPromise: input.awaitPromise ?? true,
980 returnByValue: true,
981 };
982 // The devtools console's replMode allows top-level await but returns a trailing promise unawaited,
983 // so it only retries what the page's parser rejected. A parse error has a scriptId but no stack and
984 // ran nothing; a browser-internal rejection has neither.
985 const evaluation = cdp.send("Runtime.evaluate", params).then((classic) => {
986 const failure = classic.exceptionDetails;
987 const unparsed =
988 failure?.exception?.className === "SyntaxError" &&
989 failure.scriptId !== undefined &&
990 failure.stackTrace === undefined;
991 return unparsed && !timedOut && input.expression.includes("await")
992 ? cdp.send("Runtime.evaluate", { ...params, replMode: true })
993 : classic;
994 });
995 void evaluation.catch(constVoid);
996 const result = await Promise.race([evaluation, expired]).finally(() => clearTimeout(timer));
997 if (result.exceptionDetails) {
998 throw new ServerBrowserOperationError({
999 tag: "PreviewAutomationExecutionError",
1000 message: result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,
1001 });
1002 }
1003 const value =
1004 "value" in result.result ? result.result.value : (result.result.description ?? null);
1005 const actualBytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8");
1006 if (actualBytes > MAX_EVALUATION_BYTES) {
1007 throw new ServerBrowserOperationError({
1008 tag: "PreviewAutomationResultTooLargeError",
1009 message: `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,
1010 detail: { maximumBytes: MAX_EVALUATION_BYTES },
1011 });
1012 }
1013 return value;
1014};
1015
1016export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput) => {
1017 const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1018 const locator = targetLocator(page, input);
1019 const { text, urlIncludes } = input;
1020 const checks: Array<() => Promise<boolean>> = [];
1021 if (locator !== null) checks.push(async () => (await locator.count()) > 0);
1022 if (text !== undefined) {
1023 // A navigation can destroy the context mid-check; that counts as not yet.
1024 checks.push(() =>
1025 page
1026 .evaluate(`(document.body?.innerText ?? "").includes(${JSON.stringify(text)})`)
1027 .then((found) => found === true)
1028 .catch(() => false),
1029 );
1030 }
1031 if (urlIncludes !== undefined) checks.push(async () => page.url().includes(urlIncludes));
1032 // `count()` and `evaluate()` take no timeout; a stalled check would hold the tab's control queue.
1033 let timer: ReturnType<typeof setTimeout> | undefined;
1034 const expired = new Promise<never>((_, reject) => {
1035 timer = setTimeout(
1036 () =>
1037 reject(
1038 new ServerBrowserOperationError({
1039 tag: "PreviewAutomationTimeoutError",
1040 message: `Waited ${timeoutMs}ms without every condition holding.`,
1041 }),
1042 ),
1043 timeoutMs,
1044 );
1045 });
1046 try {
1047 for (;;) {
1048 const results = await Promise.race([Promise.all(checks.map((check) => check())), expired]);
1049 if (results.every(Boolean)) return;
1050 await Promise.race([new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS)), expired]);
1051 }
1052 } finally {
1053 clearTimeout(timer);
1054 }
1055};
1056
1057const NET_ERROR_CODES: Readonly<Record<string, number>> = {
1058 ERR_FAILED: -2,
1059 ERR_TIMED_OUT: -7,
1060 ERR_CONNECTION_CLOSED: -100,
1061 ERR_CONNECTION_RESET: -101,
1062 ERR_CONNECTION_REFUSED: -102,
1063 ERR_NAME_NOT_RESOLVED: -105,
1064 ERR_INTERNET_DISCONNECTED: -106,
1065 ERR_ADDRESS_UNREACHABLE: -109,
1066 ERR_CERT_AUTHORITY_INVALID: -202,
1067 ERR_EMPTY_RESPONSE: -324,
1068};
1069
1070export const parseNetError = (errorText: string) => {
1071 // Names can hold digits, as in ERR_HTTP2_PROTOCOL_ERROR.
1072 const description = /ERR_[A-Z\d_]+/.exec(errorText)?.[0] ?? errorText;
1073 return { description, code: NET_ERROR_CODES[description] ?? -2 };
1074};
1075
1076export const recordingEncoderScript = (frameRate: BrowserRecordingFrameRate) => `(() => {
1077 const canvas = document.createElement("canvas");
1078 const context = canvas.getContext("2d");
1079 const chunks = [];
1080 let recorder = null;
1081 let started = null;
1082 let stopped = null;
1083 let sizeBytes = 0;
1084 let tooLarge = false;
1085 let frame = null;
1086 let cursor = null;
1087 let ring = null;
1088 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");
1089 let ringTimer = null;
1090 let scale = 1;
1091 let offsetX = 0;
1092 let offsetY = 0;
1093 const paint = () => {
1094 if (!frame) return;
1095 const fit = Math.min(canvas.width / frame.width, canvas.height / frame.height);
1096 const width = frame.width * fit;
1097 const height = frame.height * fit;
1098 offsetX = (canvas.width - width) / 2;
1099 offsetY = (canvas.height - height) / 2;
1100 if (width < canvas.width || height < canvas.height) {
1101 context.fillStyle = "#000";
1102 context.fillRect(0, 0, canvas.width, canvas.height);
1103 }
1104 context.drawImage(frame, offsetX, offsetY, width, height);
1105 scale = (width / frame.width) * frame.cssScale;
1106 if (ring) {
1107 const age = (performance.now() - ring.at) / 400;
1108 if (age < 1) {
1109 context.beginPath();
1110 context.arc(offsetX + ring.x * scale, offsetY + ring.y * scale, (8 + 18 * age) * scale, 0, Math.PI * 2);
1111 context.strokeStyle = "rgba(59,130,246," + (0.9 * (1 - age)) + ")";
1112 context.lineWidth = 3 * scale;
1113 context.stroke();
1114 }
1115 }
1116 if (cursor) {
1117 // The agent cursor (lucide MousePointer2, as in the live panel), never the human arrow.
1118 const s = 20 / 24 * scale;
1119 context.save();
1120 context.translate(offsetX + cursor.x * scale - 2 * scale, offsetY + cursor.y * scale - 2 * scale);
1121 context.scale(s, s);
1122 context.lineWidth = 2;
1123 context.lineJoin = "round";
1124 context.lineCap = "round";
1125 context.fillStyle = "#fff";
1126 context.strokeStyle = "#2563eb";
1127 context.shadowColor = "rgba(0,0,0,0.25)";
1128 context.shadowBlur = 2;
1129 context.fill(AGENT_CURSOR_PATH);
1130 context.shadowColor = "transparent";
1131 context.stroke(AGENT_CURSOR_PATH);
1132 context.restore();
1133 }
1134 };
1135 window.__t3Recorder = {
1136 async frame(base64, cssWidth) {
1137 if (tooLarge) return false;
1138 // A per-character atob copy costs ~30 ms on a 3200x1800 frame and throttles recordings.
1139 const bytes = Uint8Array.fromBase64(base64);
1140 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" }));
1141 if (tooLarge) { bitmap.close(); return false; }
1142 if (!recorder) {
1143 canvas.width = bitmap.width;
1144 canvas.height = bitmap.height;
1145 const mimeType = ["video/mp4;codecs=avc1.640033", "video/webm;codecs=vp9", "video/webm"].find((type) => MediaRecorder.isTypeSupported(type));
1146 const bitsPerSecond = Math.min(50e6, Math.max(2.5e6, bitmap.width * bitmap.height * ${frameRate} * 0.05));
1147 recorder = new MediaRecorder(canvas.captureStream(${frameRate}), { mimeType, videoBitsPerSecond: bitsPerSecond });
1148 started = new Promise((resolve, reject) => {
1149 recorder.onstart = resolve;
1150 recorder.onerror = (event) => reject(event.error);
1151 });
1152 stopped = new Promise((resolve) => { recorder.onstop = resolve; });
1153 recorder.ondataavailable = (event) => {
1154 if (tooLarge || event.data.size === 0) return;
1155 sizeBytes += event.data.size;
1156 if (sizeBytes > ${PROVIDER_SEND_TURN_MAX_FILE_BYTES}) {
1157 tooLarge = true;
1158 chunks.length = 0;
1159 clearInterval(ringTimer);
1160 frame?.close();
1161 frame = null;
1162 if (recorder.state !== "inactive") recorder.stop();
1163 for (const track of recorder.stream.getTracks()) track.stop();
1164 return;
1165 }
1166 chunks.push(event.data);
1167 };
1168 recorder.start(1000);
1169 }
1170 // Frame px per page CSS px, before fitting into the canvas.
1171 bitmap.cssScale = bitmap.width / cssWidth;
1172 frame?.close();
1173 frame = bitmap;
1174 paint();
1175 await started;
1176 return true;
1177 },
1178 cursor(x, y, click) {
1179 if (tooLarge) return;
1180 cursor = { x, y };
1181 if (click) {
1182 ring = { x, y, at: performance.now() };
1183 clearInterval(ringTimer);
1184 ringTimer = setInterval(() => {
1185 paint();
1186 if (performance.now() - ring.at > 400) { ring = null; clearInterval(ringTimer); paint(); }
1187 }, 33);
1188 }
1189 paint();
1190 },
1191 async stop() {
1192 if (!recorder) return { mimeType: null, count: 0, bytes: 0 };
1193 if (recorder.state !== "inactive") {
1194 // Consume the cached frame, then wait for the final paint to reach the
1195 // capture stream. Animation ticks alone can stop before it is delivered.
1196 const video = document.createElement("video");
1197 video.muted = true;
1198 video.srcObject = recorder.stream;
1199 const nextFrame = () => Promise.race([
1200 new Promise(resolve => video.requestVideoFrameCallback(resolve)),
1201 stopped,
1202 ]);
1203 const initial = nextFrame();
1204 void video.play().catch(() => {});
1205 await initial;
1206 if (recorder.state !== "inactive") {
1207 const delivered = nextFrame();
1208 recorder.stream.getVideoTracks()[0].requestFrame();
1209 paint();
1210 await delivered;
1211 }
1212 video.pause();
1213 video.srcObject = null;
1214 if (recorder.state !== "inactive") recorder.stop();
1215 }
1216 await stopped;
1217 return { mimeType: recorder.mimeType, count: chunks.length, bytes: sizeBytes };
1218 },
1219 async chunk(index) {
1220 const bytes = new Uint8Array(await chunks[index].arrayBuffer());
1221 if (typeof bytes.toBase64 === "function") return bytes.toBase64();
1222 let binary = "";
1223 for (let offset = 0; offset < bytes.length; offset += 0x8000) {
1224 binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
1225 }
1226 return btoa(binary);
1227 },
1228 download() {
1229 const link = document.createElement("a");
1230 link.href = URL.createObjectURL(new Blob(chunks, { type: recorder.mimeType }));
1231 link.download = "recording";
1232 link.click();
1233 },
1234 };
1235})()`;