// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off - Playwright callbacks run outside the Effect runtime. import { PROVIDER_SEND_TURN_MAX_FILE_BYTES, type PreviewAutomationClickInput, type PreviewAutomationConsoleEntry, type PreviewAutomationDragInput, type PreviewAutomationEvaluateInput, type PreviewAutomationHoverInput, type PreviewAutomationNetworkEntry, type PreviewAutomationPressInput, type PreviewAutomationScrollInput, type PreviewAutomationSelectInput, type PreviewAutomationSelectResult, type PreviewAutomationSnapshot, type PreviewAutomationTypeInput, type PreviewAutomationUploadInput, type PreviewAutomationWaitForInput, } from "@t3tools/contracts"; import { constVoid } from "effect/Function"; import type { CDPSession, Locator, Page } from "playwright-core"; import * as NodeCrypto from "node:crypto"; import { BrowserControlInterrupted } from "./SessionControl.ts"; const MAX_EVALUATION_BYTES = 64_000; const MAX_VISIBLE_TEXT_LENGTH = 20_000; const MAX_SCREENSHOT_WIDTH = 1280; const WAIT_POLL_MS = 100; export const DIAGNOSTIC_BUFFER_LIMIT = 200; export class ServerBrowserOperationError extends Error { readonly tag: string; readonly detail: unknown; constructor(tag: string, message: string, detail?: unknown) { super(message); this.tag = tag; this.detail = detail; } } export const toOperationError = (cause: unknown): ServerBrowserOperationError => { if (cause instanceof BrowserControlInterrupted) return new ServerBrowserOperationError( "PreviewAutomationControlInterruptedError", cause.message, cause.reason, ); if (cause instanceof ServerBrowserOperationError) return cause; const message = cause instanceof Error ? cause.message : String(cause); const firstLine = message.split("\n")[0] ?? message; if (cause instanceof Error && cause.name === "TimeoutError") { return new ServerBrowserOperationError("PreviewAutomationTimeoutError", firstLine); } if ( /while parsing selector|Unknown engine|Unexpected token|strict mode violation/i.test(message) ) { return new ServerBrowserOperationError("PreviewAutomationInvalidSelectorError", firstLine); } if (/not an |not editable|not an editable/i.test(message)) { return new ServerBrowserOperationError("PreviewAutomationTargetNotEditableError", firstLine); } return new ServerBrowserOperationError("PreviewAutomationExecutionError", firstLine); }; const DEFAULT_TIMEOUT_MS = 15_000; const pageRefs = new WeakMap }>(); // A compact runtime namespace prevents old refs from aliasing after a server restart. const refNamespace = NodeCrypto.randomUUID().slice(0, 8); let snapshotSequence = 0; const nextRefGeneration = () => `${refNamespace}-${(++snapshotSequence).toString(36)}`; /** A takeover revokes previously issued refs even when the document stays unchanged. */ export const invalidateRefs = (page: Page) => { const state = pageRefs.get(page); if (state) { state.generation = nextRefGeneration(); state.refs.clear(); } }; const refsFor = (page: Page) => { let state = pageRefs.get(page); if (!state) { state = { generation: nextRefGeneration(), refs: new Map() }; pageRefs.set(page, state); page.on("framenavigated", () => invalidateRefs(page)); page.on("framedetached", () => invalidateRefs(page)); } return state; }; const targetLocator = ( page: Page, input: { readonly locator?: string | undefined; readonly selector?: string | undefined }, ): Locator | null => { const selector = input.locator ?? input.selector; if (selector === undefined) return null; // Ignore quoted/escaped CSS values when looking for a selector-engine boundary. const engines = selector.replace( /\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, " ", ); if (/(?:^|>>)\s*\*?aria-ref\s*=/.test(engines)) { const ref = /^\s*aria-ref\s*=\s*(\S+)\s*$/.exec(selector)?.[1]; const nativeRef = ref === undefined ? undefined : pageRefs.get(page)?.refs.get(ref); if (nativeRef === undefined) { throw new ServerBrowserOperationError( "PreviewAutomationInvalidSelectorError", "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.", { staleRef: true }, ); } return page.locator(`aria-ref=${nativeRef}`); } // Playwright's strict locators reject ambiguous controls rather than acting on row one. return page.locator(selector); }; /** Shows the agent's pointer to viewers before an action lands at that point. */ export type PointerReporter = ( point: { readonly x: number; readonly y: number }, phase: "move" | "click", ) => Promise; const noPointer: PointerReporter = async () => {}; /** The viewport point an action will hit: the target's center after scrolling it into view. */ const targetPoint = async ( page: Page, locator: Locator | null, input: { readonly x?: number | undefined; readonly y?: number | undefined }, timeout: number, ) => { if (locator === null) return { x: input.x ?? 0, y: input.y ?? 0 }; await locator.scrollIntoViewIfNeeded({ timeout }); const box = await locator.boundingBox({ timeout }); if (box) return { x: box.x + box.width / 2, y: box.y + box.height / 2 }; const viewport = page.viewportSize(); return { x: (viewport?.width ?? 0) / 2, y: (viewport?.height ?? 0) / 2 }; }; const SNAPSHOT_SCRIPT = `(() => { return { url: location.href, title: document.title, loading: document.readyState !== "complete", visibleText: (document.body?.innerText || "").slice(0, ${MAX_VISIBLE_TEXT_LENGTH}), interactiveElements: [], }; })()`; // Scaled captures repaint live screencasts, so callers pause them. Clips use document offsets. export const captureViewport = async ( page: Page, cdp: CDPSession, options: { readonly format: "png" | "jpeg"; readonly quality?: number; readonly scale: number }, ) => { let clip; if (options.scale < 1) { const viewport = page.viewportSize() ?? { width: 1280, height: 800 }; const { cssVisualViewport } = await cdp.send("Page.getLayoutMetrics"); clip = { x: cssVisualViewport.pageX, y: cssVisualViewport.pageY, ...viewport, scale: options.scale, }; } const { data } = await cdp.send("Page.captureScreenshot", { format: options.format, ...(options.quality === undefined ? {} : { quality: options.quality }), ...(clip ? { clip } : {}), }); return data; }; export const snapshot = async (input: { readonly page: Page; readonly cdp: CDPSession; readonly renderScale: number; readonly consoleEntries: ReadonlyArray; readonly networkEntries: ReadonlyArray; readonly actionTimeline: PreviewAutomationSnapshot["actionTimeline"]; }): Promise => { const viewport = input.page.viewportSize() ?? { width: 1280, height: 800 }; const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * input.renderScale)); const state = refsFor(input.page); invalidateRefs(input.page); const generation = state.generation; const [page, tree, data] = await Promise.all([ input.page.evaluate(SNAPSHOT_SCRIPT) as Promise< Pick< PreviewAutomationSnapshot, "url" | "title" | "loading" | "visibleText" | "interactiveElements" > >, input.page.ariaSnapshot({ mode: "ai", boxes: true, timeout: DEFAULT_TIMEOUT_MS }), captureViewport(input.page, input.cdp, { format: "png", scale }), ]); if (state.generation !== generation) { throw new ServerBrowserOperationError( "PreviewAutomationExecutionError", "The page changed while capturing its snapshot. Take another snapshot.", ); } const accessibilityTree = tree .slice(0, MAX_VISIBLE_TEXT_LENGTH) .replace(/\[ref=((?:f\d+)?e\d+)\]/g, (_match, nativeRef: string) => { const ref = `t3-${generation}-${nativeRef}`; state.refs.set(ref, nativeRef); return `[ref=${ref}]`; }); return { ...page, accessibilityTree, consoleEntries: [...input.consoleEntries], networkEntries: [...input.networkEntries], actionTimeline: [...input.actionTimeline], screenshot: { mimeType: "image/png", data, width: Math.round(viewport.width * input.renderScale * scale), height: Math.round(viewport.height * input.renderScale * scale), }, }; }; /** * A click whose handler opens a dialog does not finish until the dialog is * resolved, so it returns as soon as the dialog opens; status then reports it. */ export const click = async ( page: Page, input: PreviewAutomationClickInput, pointer: PointerReporter = noPointer, ): Promise<{ readonly x: number; readonly y: number }> => { const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const locator = targetLocator(page, input); const point = await targetPoint(page, locator, input, timeout); await pointer(point, "click"); const options = { button: input.button ?? "left", clickCount: input.clickCount ?? 1 } as const; const clicked = locator === null ? page.mouse.click(point.x, point.y, options) : locator.click({ ...options, timeout }); let onDialog = constVoid; const dialogOpened = new Promise<"dialog">((resolve) => { onDialog = () => resolve("dialog"); page.once("dialog", onDialog); }); try { if ((await Promise.race([clicked, dialogOpened])) === "dialog") void clicked.catch(constVoid); } finally { page.off("dialog", onDialog); } return point; }; export const type = async (page: Page, input: PreviewAutomationTypeInput) => { const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const locator = targetLocator(page, input); if (locator !== null && input.clear) { await locator.fill(input.text, { timeout }); return; } // A shadow host also matches :focus; use its innermost focused descendant. const target = locator ?? page.locator("*:focus").last(); const focused = (locator !== null || (await target.count()) > 0) && (await target.evaluate( (element) => { // Like the desktop host: an enabled text control or contenteditable // that actually takes focus. Anything else would swallow the text or // send it to whichever field had focus before. const control = element as unknown as { readonly type?: string; readonly disabled?: boolean; readonly readOnly?: boolean; readonly isContentEditable?: boolean; readonly focus?: () => void; }; const nonText = [ "button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit", ]; const textControl = element.tagName === "TEXTAREA" || (element.tagName === "INPUT" && !nonText.includes(control.type ?? "text")); if (!(textControl || control.isContentEditable) || control.disabled || control.readOnly) { return false; } control.focus?.(); const root = element.getRootNode() as { readonly activeElement?: typeof element | null }; const active = root.activeElement; return active != null && (active === element || element.contains(active)); }, undefined, { timeout }, )); if (focused !== true) { throw new ServerBrowserOperationError( "PreviewAutomationTargetNotEditableError", "The target is not an enabled text field, so no text was typed.", ); } if (input.clear) { await page.keyboard.press("ControlOrMeta+A"); await page.keyboard.press("Delete"); } await page.keyboard.insertText(input.text); }; /** Hovering by locator moves the real mouse, so CSS :hover and pointer events both apply. */ export const hover = async ( page: Page, input: PreviewAutomationHoverInput, pointer: PointerReporter = noPointer, ) => { const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const locator = targetLocator(page, input); await pointer(await targetPoint(page, locator, input, timeout), "move"); if (locator === null) { await page.mouse.move(input.x ?? 0, input.y ?? 0); return; } await locator.hover({ timeout }); }; export const select = async ( page: Page, input: PreviewAutomationSelectInput, ): Promise => { const locator = targetLocator(page, input)!; const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; // Each entry matches an option by value first, then by its visible label. const options = await locator.evaluate( (element) => element.tagName === "SELECT" ? Array.from( (element as unknown as { options: ArrayLike<{ value: string; label: string }> }) .options, ({ value, label }) => ({ value, label: label.trim() }), ) : null, undefined, { timeout }, ); const values = options && input.values.map( (entry) => ( options.find((option) => option.value === entry) ?? options.find((option) => option.label === entry.trim()) )?.value ?? entry, ); if (values === null) throw new ServerBrowserOperationError( "PreviewAutomationTargetNotEditableError", "This element is not a