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

ServerBrowserPage.ts

664 lines24.6 KB

1// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off - Playwright callbacks run outside the Effect runtime.
2​
3import {
4 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
5 type PreviewAutomationClickInput,
6 type PreviewAutomationConsoleEntry,
7 type PreviewAutomationDragInput,
8 type PreviewAutomationEvaluateInput,
9 type PreviewAutomationHoverInput,
10 type PreviewAutomationNetworkEntry,
11 type PreviewAutomationPressInput,
12 type PreviewAutomationScrollInput,
13 type PreviewAutomationSelectInput,
14 type PreviewAutomationSelectResult,
15 type PreviewAutomationSnapshot,
16 type PreviewAutomationTypeInput,
17 type PreviewAutomationUploadInput,
18 type PreviewAutomationWaitForInput,
19} from "@t3tools/contracts";
20import { constVoid } from "effect/Function";
21import type { CDPSession, Locator, Page } from "playwright-core";
22import * as NodeCrypto from "node:crypto";
23import { BrowserControlInterrupted } from "./SessionControl.ts";
24​
25const MAX_EVALUATION_BYTES = 64_000;
26const MAX_VISIBLE_TEXT_LENGTH = 20_000;
27const MAX_SCREENSHOT_WIDTH = 1280;
28const WAIT_POLL_MS = 100;
29export const DIAGNOSTIC_BUFFER_LIMIT = 200;
30​
31export class ServerBrowserOperationError extends Error {
32 readonly tag: string;
33 readonly detail: unknown;
34​
35 constructor(tag: string, message: string, detail?: unknown) {
36 super(message);
37 this.tag = tag;
38 this.detail = detail;
39 }
41​
42export const toOperationError = (cause: unknown): ServerBrowserOperationError => {
43 if (cause instanceof BrowserControlInterrupted)
44 return new ServerBrowserOperationError(
45 "PreviewAutomationControlInterruptedError",
46 cause.message,
47 cause.reason,
48 );
49 if (cause instanceof ServerBrowserOperationError) return cause;
50 const message = cause instanceof Error ? cause.message : String(cause);
51 const firstLine = message.split("\n")[0] ?? message;
52 if (cause instanceof Error && cause.name === "TimeoutError") {
53 return new ServerBrowserOperationError("PreviewAutomationTimeoutError", firstLine);
54 }
55 if (
56 /while parsing selector|Unknown engine|Unexpected token|strict mode violation/i.test(message)
57 ) {
58 return new ServerBrowserOperationError("PreviewAutomationInvalidSelectorError", firstLine);
59 }
60 if (/not an <input>|not editable|not an editable/i.test(message)) {
61 return new ServerBrowserOperationError("PreviewAutomationTargetNotEditableError", firstLine);
62 }
63 return new ServerBrowserOperationError("PreviewAutomationExecutionError", firstLine);
64};
65​
66const DEFAULT_TIMEOUT_MS = 15_000;
67​
68const pageRefs = new WeakMap<Page, { generation: string; refs: Map<string, string> }>();
69// A compact runtime namespace prevents old refs from aliasing after a server restart.
70const refNamespace = NodeCrypto.randomUUID().slice(0, 8);
71let snapshotSequence = 0;
72const nextRefGeneration = () => `${refNamespace}-${(++snapshotSequence).toString(36)}`;
73​
74/** A takeover revokes previously issued refs even when the document stays unchanged. */
75export const invalidateRefs = (page: Page) => {
76 const state = pageRefs.get(page);
77 if (state) {
78 state.generation = nextRefGeneration();
79 state.refs.clear();
80 }
81};
82​
83const refsFor = (page: Page) => {
84 let state = pageRefs.get(page);
85 if (!state) {
86 state = { generation: nextRefGeneration(), refs: new Map<string, string>() };
87 pageRefs.set(page, state);
88 page.on("framenavigated", () => invalidateRefs(page));
89 page.on("framedetached", () => invalidateRefs(page));
90 }
91 return state;
92};
93​
94const targetLocator = (
95 page: Page,
96 input: { readonly locator?: string | undefined; readonly selector?: string | undefined },
97): Locator | null => {
98 const selector = input.locator ?? input.selector;
99 if (selector === undefined) return null;
100 // Ignore quoted/escaped CSS values when looking for a selector-engine boundary.
101 const engines = selector.replace(
102 /\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g,
103 " ",
104 );
105 if (/(?:^|>>)\s*\*?aria-ref\s*=/.test(engines)) {
106 const ref = /^\s*aria-ref\s*=\s*(\S+)\s*$/.exec(selector)?.[1];
107 const nativeRef = ref === undefined ? undefined : pageRefs.get(page)?.refs.get(ref);
108 if (nativeRef === undefined) {
109 throw new ServerBrowserOperationError(
110 "PreviewAutomationInvalidSelectorError",
111 "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.",
112 { staleRef: true },
113 );
114 }
115 return page.locator(`aria-ref=${nativeRef}`);
116 }
117 // Playwright's strict locators reject ambiguous controls rather than acting on row one.
118 return page.locator(selector);
119};
120​
121/** Shows the agent's pointer to viewers before an action lands at that point. */
122export type PointerReporter = (
123 point: { readonly x: number; readonly y: number },
124 phase: "move" | "click",
125) => Promise<void>;
126const noPointer: PointerReporter = async () => {};
127​
128/** The viewport point an action will hit: the target's center after scrolling it into view. */
129const targetPoint = async (
130 page: Page,
131 locator: Locator | null,
132 input: { readonly x?: number | undefined; readonly y?: number | undefined },
133 timeout: number,
134) => {
135 if (locator === null) return { x: input.x ?? 0, y: input.y ?? 0 };
136 await locator.scrollIntoViewIfNeeded({ timeout });
137 const box = await locator.boundingBox({ timeout });
138 if (box) return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
139 const viewport = page.viewportSize();
140 return { x: (viewport?.width ?? 0) / 2, y: (viewport?.height ?? 0) / 2 };
141};
142​
143const SNAPSHOT_SCRIPT = `(() => {
144 return {
145 url: location.href,
146 title: document.title,
147 loading: document.readyState !== "complete",
148 visibleText: (document.body?.innerText || "").slice(0, ${MAX_VISIBLE_TEXT_LENGTH}),
149 interactiveElements: [],
150 };
151})()`;
152​
153// Scaled captures repaint live screencasts, so callers pause them. Clips use document offsets.
154export const captureViewport = async (
155 page: Page,
156 cdp: CDPSession,
157 options: { readonly format: "png" | "jpeg"; readonly quality?: number; readonly scale: number },
158) => {
159 let clip;
160 if (options.scale < 1) {
161 const viewport = page.viewportSize() ?? { width: 1280, height: 800 };
162 const { cssVisualViewport } = await cdp.send("Page.getLayoutMetrics");
163 clip = {
164 x: cssVisualViewport.pageX,
165 y: cssVisualViewport.pageY,
166 ...viewport,
167 scale: options.scale,
168 };
169 }
170 const { data } = await cdp.send("Page.captureScreenshot", {
171 format: options.format,
172 ...(options.quality === undefined ? {} : { quality: options.quality }),
173 ...(clip ? { clip } : {}),
174 });
175 return data;
176};
177​
178export const snapshot = async (input: {
179 readonly page: Page;
180 readonly cdp: CDPSession;
181 readonly renderScale: number;
182 readonly consoleEntries: ReadonlyArray<PreviewAutomationConsoleEntry>;
183 readonly networkEntries: ReadonlyArray<PreviewAutomationNetworkEntry>;
184 readonly actionTimeline: PreviewAutomationSnapshot["actionTimeline"];
185}): Promise<PreviewAutomationSnapshot> => {
186 const viewport = input.page.viewportSize() ?? { width: 1280, height: 800 };
187 const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * input.renderScale));
188 const state = refsFor(input.page);
189 invalidateRefs(input.page);
190 const generation = state.generation;
191 const [page, tree, data] = await Promise.all([
192 input.page.evaluate(SNAPSHOT_SCRIPT) as Promise<
193 Pick<
194 PreviewAutomationSnapshot,
195 "url" | "title" | "loading" | "visibleText" | "interactiveElements"
196 >
197 >,
198 input.page.ariaSnapshot({ mode: "ai", boxes: true, timeout: DEFAULT_TIMEOUT_MS }),
199 captureViewport(input.page, input.cdp, { format: "png", scale }),
200 ]);
201 if (state.generation !== generation) {
202 throw new ServerBrowserOperationError(
203 "PreviewAutomationExecutionError",
204 "The page changed while capturing its snapshot. Take another snapshot.",
205 );
206 }
207 const accessibilityTree = tree
208 .slice(0, MAX_VISIBLE_TEXT_LENGTH)
209 .replace(/\[ref=((?:f\d+)?e\d+)\]/g, (_match, nativeRef: string) => {
210 const ref = `t3-${generation}-${nativeRef}`;
211 state.refs.set(ref, nativeRef);
212 return `[ref=${ref}]`;
213 });
214 return {
215 ...page,
216 accessibilityTree,
217 consoleEntries: [...input.consoleEntries],
218 networkEntries: [...input.networkEntries],
219 actionTimeline: [...input.actionTimeline],
220 screenshot: {
221 mimeType: "image/png",
222 data,
223 width: Math.round(viewport.width * input.renderScale * scale),
224 height: Math.round(viewport.height * input.renderScale * scale),
225 },
226 };
227};
228​
229/**
230 * A click whose handler opens a dialog does not finish until the dialog is
231 * resolved, so it returns as soon as the dialog opens; status then reports it.
232 */
233export const click = async (
234 page: Page,
235 input: PreviewAutomationClickInput,
236 pointer: PointerReporter = noPointer,
237): Promise<{ readonly x: number; readonly y: number }> => {
238 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
239 const locator = targetLocator(page, input);
240 const point = await targetPoint(page, locator, input, timeout);
241 await pointer(point, "click");
242 const options = { button: input.button ?? "left", clickCount: input.clickCount ?? 1 } as const;
243 const clicked =
244 locator === null
245 ? page.mouse.click(point.x, point.y, options)
246 : locator.click({ ...options, timeout });
247 let onDialog = constVoid;
248 const dialogOpened = new Promise<"dialog">((resolve) => {
249 onDialog = () => resolve("dialog");
250 page.once("dialog", onDialog);
251 });
252 try {
253 if ((await Promise.race([clicked, dialogOpened])) === "dialog") void clicked.catch(constVoid);
254 } finally {
255 page.off("dialog", onDialog);
256 }
257 return point;
258};
259​
260export const type = async (page: Page, input: PreviewAutomationTypeInput) => {
261 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
262 const locator = targetLocator(page, input);
263 if (locator !== null && input.clear) {
264 await locator.fill(input.text, { timeout });
265 return;
266 }
267 // A shadow host also matches :focus; use its innermost focused descendant.
268 const target = locator ?? page.locator("*:focus").last();
269 const focused =
270 (locator !== null || (await target.count()) > 0) &&
271 (await target.evaluate(
272 (element) => {
273 // Like the desktop host: an enabled text control or contenteditable
274 // that actually takes focus. Anything else would swallow the text or
275 // send it to whichever field had focus before.
276 const control = element as unknown as {
277 readonly type?: string;
278 readonly disabled?: boolean;
279 readonly readOnly?: boolean;
280 readonly isContentEditable?: boolean;
281 readonly focus?: () => void;
282 };
283 const nonText = [
284 "button",
285 "checkbox",
286 "color",
287 "file",
288 "hidden",
289 "image",
290 "radio",
291 "range",
292 "reset",
293 "submit",
294 ];
295 const textControl =
296 element.tagName === "TEXTAREA" ||
297 (element.tagName === "INPUT" && !nonText.includes(control.type ?? "text"));
298 if (!(textControl || control.isContentEditable) || control.disabled || control.readOnly) {
299 return false;
300 }
301 control.focus?.();
302 const root = element.getRootNode() as { readonly activeElement?: typeof element | null };
303 const active = root.activeElement;
304 return active != null && (active === element || element.contains(active));
305 },
306 undefined,
307 { timeout },
308 ));
309 if (focused !== true) {
310 throw new ServerBrowserOperationError(
311 "PreviewAutomationTargetNotEditableError",
312 "The target is not an enabled text field, so no text was typed.",
313 );
314 }
315 if (input.clear) {
316 await page.keyboard.press("ControlOrMeta+A");
317 await page.keyboard.press("Delete");
318 }
319 await page.keyboard.insertText(input.text);
320};
321​
322/** Hovering by locator moves the real mouse, so CSS :hover and pointer events both apply. */
323export const hover = async (
324 page: Page,
325 input: PreviewAutomationHoverInput,
326 pointer: PointerReporter = noPointer,
327) => {
328 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
329 const locator = targetLocator(page, input);
330 await pointer(await targetPoint(page, locator, input, timeout), "move");
331 if (locator === null) {
332 await page.mouse.move(input.x ?? 0, input.y ?? 0);
333 return;
334 }
335 await locator.hover({ timeout });
336};
337​
338export const select = async (
339 page: Page,
340 input: PreviewAutomationSelectInput,
341): Promise<PreviewAutomationSelectResult> => {
342 const locator = targetLocator(page, input)!;
343 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
344 // Each entry matches an option by value first, then by its visible label.
345 const options = await locator.evaluate(
346 (element) =>
347 element.tagName === "SELECT"
348 ? Array.from(
349 (element as unknown as { options: ArrayLike<{ value: string; label: string }> })
350 .options,
351 ({ value, label }) => ({ value, label: label.trim() }),
352 )
353 : null,
354 undefined,
355 { timeout },
356 );
357 const values =
358 options &&
359 input.values.map(
360 (entry) =>
361 (
362 options.find((option) => option.value === entry) ??
363 options.find((option) => option.label === entry.trim())
364 )?.value ?? entry,
365 );
366 if (values === null)
367 throw new ServerBrowserOperationError(
368 "PreviewAutomationTargetNotEditableError",
369 "This element is not a <select>. Click a custom dropdown, then click its option.",
370 );
371 return { selected: await locator.selectOption(values, { timeout }) };
372};
373​
374export const drag = async (
375 page: Page,
376 input: PreviewAutomationDragInput,
377 pointer: PointerReporter = noPointer,
378) => {
379 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
380 const source = targetLocator(page, { locator: input.source })!;
381 const target = targetLocator(page, { locator: input.target })!;
382 await pointer(await targetPoint(page, source, {}, timeout), "move");
383 // The cursor travels with the drag; the page sees one continuous gesture.
384 const dropped = source.dragTo(target, { timeout });
385 const end = await target.boundingBox({ timeout }).catch(() => null);
386 if (end) await pointer({ x: end.x + end.width / 2, y: end.y + end.height / 2 }, "move");
387 await dropped;
388};
389​
390/** Sets files on one file input; false when no locator or selector names one. */
391export const setInputFiles = async (page: Page, input: PreviewAutomationUploadInput) => {
392 const locator = targetLocator(page, input);
393 if (locator === null) return false;
394 await locator.setInputFiles([...input.paths], { timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS });
395 return true;
396};
397​
398export const press = async (page: Page, input: PreviewAutomationPressInput) => {
399 await page.keyboard.press([...(input.modifiers ?? []), input.key].join("+"));
400};
401​
402export const scroll = async (page: Page, input: PreviewAutomationScrollInput) => {
403 const delta = [input.deltaX ?? 0, input.deltaY ?? 0] as const;
404 const locator = targetLocator(page, input);
405 if (locator === null) {
406 // Page-side code is passed as source: the server compiles without DOM types.
407 await page.evaluate(`scrollBy(${delta[0]}, ${delta[1]})`);
408 return;
409 }
410 await locator.evaluate((element, [x, y]) => element.scrollBy(x, y), delta);
411};
412​
413/**
414 * Runs an agent's expression, bounded by its request's deadline. Past it, the
415 * page's script is terminated and the call fails, so the tab's control queue
416 * frees for the next request instead of waiting on the script.
417 */
418export const evaluate = async (
419 cdp: CDPSession,
420 input: PreviewAutomationEvaluateInput,
421 timeoutMs: number,
422) => {
423 let timer: ReturnType<typeof setTimeout> | undefined;
424 const expired = new Promise<never>((_, reject) => {
425 timer = setTimeout(() => {
426 // Stops a busy script; an awaited promise is abandoned and settles unread.
427 void cdp.send("Runtime.terminateExecution").catch(constVoid);
428 reject(
429 new ServerBrowserOperationError(
430 "PreviewAutomationTimeoutError",
431 `Evaluation did not finish within ${timeoutMs}ms and was stopped.`,
432 ),
433 );
434 }, timeoutMs);
435 });
436 const evaluation = cdp.send("Runtime.evaluate", {
437 expression: input.expression,
438 awaitPromise: input.awaitPromise ?? true,
439 returnByValue: input.returnByValue ?? true,
440 });
441 void evaluation.catch(constVoid);
442 const result = await Promise.race([evaluation, expired]).finally(() => clearTimeout(timer));
443 if (result.exceptionDetails) {
444 throw new ServerBrowserOperationError(
445 "PreviewAutomationExecutionError",
446 result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,
447 );
448 }
449 const value =
450 "value" in result.result ? result.result.value : (result.result.description ?? null);
451 const actualBytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8");
452 if (actualBytes > MAX_EVALUATION_BYTES) {
453 throw new ServerBrowserOperationError(
454 "PreviewAutomationResultTooLargeError",
455 `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,
456 { maximumBytes: MAX_EVALUATION_BYTES },
457 );
458 }
459 return value;
460};
461​
462export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput) => {
463 const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
464 const deadline = Date.now() + timeoutMs;
465 const locator = targetLocator(page, input);
466 const { text, urlIncludes } = input;
467 const checks: Array<() => Promise<boolean>> = [];
468 // Like the desktop host: the selector must match an element, visible or not.
469 if (locator !== null) checks.push(async () => (await locator.count()) > 0);
470 if (text !== undefined) {
471 // A navigation can destroy the context mid-check; that counts as not yet.
472 checks.push(() =>
473 page
474 .evaluate(`(document.body?.innerText ?? "").includes(${JSON.stringify(text)})`)
475 .then((found) => found === true)
476 .catch(() => false),
477 );
478 }
479 if (urlIncludes !== undefined) checks.push(async () => page.url().includes(urlIncludes));
480 for (;;) {
481 const results = await Promise.all(checks.map((check) => check()));
482 if (results.every(Boolean)) return;
483 if (Date.now() >= deadline) {
484 throw new ServerBrowserOperationError(
485 "PreviewAutomationTimeoutError",
486 `Waited ${timeoutMs}ms without every condition holding.`,
487 );
488 }
489 await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS));
490 }
491};
492​
493const NET_ERROR_CODES: Readonly<Record<string, number>> = {
494 ERR_FAILED: -2,
495 ERR_TIMED_OUT: -7,
496 ERR_CONNECTION_CLOSED: -100,
497 ERR_CONNECTION_RESET: -101,
498 ERR_CONNECTION_REFUSED: -102,
499 ERR_NAME_NOT_RESOLVED: -105,
500 ERR_INTERNET_DISCONNECTED: -106,
501 ERR_ADDRESS_UNREACHABLE: -109,
502 ERR_CERT_AUTHORITY_INVALID: -202,
503 ERR_EMPTY_RESPONSE: -324,
504};
505​
506export const parseNetError = (errorText: string) => {
507 const description = /ERR_[A-Z_]+/.exec(errorText)?.[0] ?? errorText;
508 return { description, code: NET_ERROR_CODES[description] ?? -2 };
509};
510​
511// Browser-side encoding avoids ffmpeg. Resizes are letterboxed into the first frame;
512// the agent cursor is drawn here so it never changes the page under test.
513export const RECORDING_ENCODER_SCRIPT = `(() => {
514 const canvas = document.createElement("canvas");
515 const context = canvas.getContext("2d");
516 const chunks = [];
517 let recorder = null;
518 let started = null;
519 let stopped = null;
520 let sizeBytes = 0;
521 let tooLarge = false;
522 let frame = null;
523 let cursor = null;
524 let ring = null;
525 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");
526 let ringTimer = null;
527 let scale = 1;
528 let offsetX = 0;
529 let offsetY = 0;
530 const paint = () => {
531 if (!frame) return;
532 const fit = Math.min(canvas.width / frame.width, canvas.height / frame.height);
533 const width = frame.width * fit;
534 const height = frame.height * fit;
535 offsetX = (canvas.width - width) / 2;
536 offsetY = (canvas.height - height) / 2;
537 if (width < canvas.width || height < canvas.height) {
538 context.fillStyle = "#000";
539 context.fillRect(0, 0, canvas.width, canvas.height);
540 }
541 context.drawImage(frame, offsetX, offsetY, width, height);
542 scale = (width / frame.width) * frame.cssScale;
543 if (ring) {
544 const age = (performance.now() - ring.at) / 400;
545 if (age < 1) {
546 context.beginPath();
547 context.arc(offsetX + ring.x * scale, offsetY + ring.y * scale, (8 + 18 * age) * scale, 0, Math.PI * 2);
548 context.strokeStyle = "rgba(59,130,246," + (0.9 * (1 - age)) + ")";
549 context.lineWidth = 3 * scale;
550 context.stroke();
551 }
552 }
553 if (cursor) {
554 // The agent cursor (lucide MousePointer2, as in the live panel), never the human arrow.
555 const s = 20 / 24 * scale;
556 context.save();
557 context.translate(offsetX + cursor.x * scale - 2 * scale, offsetY + cursor.y * scale - 2 * scale);
558 context.scale(s, s);
559 context.lineWidth = 2;
560 context.lineJoin = "round";
561 context.lineCap = "round";
562 context.fillStyle = "#fff";
563 context.strokeStyle = "#2563eb";
564 context.shadowColor = "rgba(0,0,0,0.25)";
565 context.shadowBlur = 2;
566 context.fill(AGENT_CURSOR_PATH);
567 context.shadowColor = "transparent";
568 context.stroke(AGENT_CURSOR_PATH);
569 context.restore();
570 }
571 };
572 window.__t3Recorder = {
573 async frame(base64, cssWidth) {
574 if (tooLarge) return false;
575 const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
576 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" }));
577 if (tooLarge) { bitmap.close(); return false; }
578 if (!recorder) {
579 canvas.width = bitmap.width;
580 canvas.height = bitmap.height;
581 const mimeType = ["video/mp4;codecs=avc1.640033", "video/webm;codecs=vp9", "video/webm"].find((type) => MediaRecorder.isTypeSupported(type));
582 const bitsPerSecond = Math.min(50e6, Math.max(2.5e6, bitmap.width * bitmap.height * 30 * 0.05));
583 recorder = new MediaRecorder(canvas.captureStream(30), { mimeType, videoBitsPerSecond: bitsPerSecond });
584 started = new Promise((resolve, reject) => {
585 recorder.onstart = resolve;
586 recorder.onerror = (event) => reject(event.error);
587 });
588 stopped = new Promise((resolve) => { recorder.onstop = resolve; });
589 recorder.ondataavailable = (event) => {
590 if (tooLarge || event.data.size === 0) return;
591 sizeBytes += event.data.size;
592 if (sizeBytes > ${PROVIDER_SEND_TURN_MAX_FILE_BYTES}) {
593 tooLarge = true;
594 chunks.length = 0;
595 clearInterval(ringTimer);
596 frame?.close();
597 frame = null;
598 if (recorder.state !== "inactive") recorder.stop();
599 for (const track of recorder.stream.getTracks()) track.stop();
600 return;
601 }
602 chunks.push(event.data);
603 };
604 recorder.start(1000);
605 }
606 // Frame px per page CSS px, before fitting into the canvas.
607 bitmap.cssScale = bitmap.width / cssWidth;
608 frame?.close();
609 frame = bitmap;
610 paint();
611 await started;
612 return true;
613 },
614 cursor(x, y, click) {
615 if (tooLarge) return;
616 cursor = { x, y };
617 if (click) {
618 ring = { x, y, at: performance.now() };
619 clearInterval(ringTimer);
620 ringTimer = setInterval(() => {
621 paint();
622 if (performance.now() - ring.at > 400) { ring = null; clearInterval(ringTimer); paint(); }
623 }, 33);
624 }
625 paint();
626 },
627 async stop() {
628 if (!recorder) return { mimeType: null, count: 0, bytes: 0 };
629 if (recorder.state !== "inactive") {
630 // Consume the cached frame, then wait for the final paint to reach the
631 // capture stream. Animation ticks alone can stop before it is delivered.
632 const video = document.createElement("video");
633 video.muted = true;
634 video.srcObject = recorder.stream;
635 const nextFrame = () => Promise.race([
636 new Promise(resolve => video.requestVideoFrameCallback(resolve)),
637 stopped,
638 ]);
639 const initial = nextFrame();
640 void video.play().catch(() => {});
641 await initial;
642 if (recorder.state !== "inactive") {
643 const delivered = nextFrame();
644 recorder.stream.getVideoTracks()[0].requestFrame();
645 paint();
646 await delivered;
647 }
648 video.pause();
649 video.srcObject = null;
650 if (recorder.state !== "inactive") recorder.stop();
651 }
652 await stopped;
653 return { mimeType: recorder.mimeType, count: chunks.length, bytes: sizeBytes };
654 },
655 async chunk(index) {
656 const bytes = new Uint8Array(await chunks[index].arrayBuffer());
657 let binary = "";
658 for (let offset = 0; offset < bytes.length; offset += 0x8000) {
659 binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
660 }
661 return btoa(binary);
662 },
663 };
664})()`;