Open History to see the last commit
1import { PreviewAutomationEvaluateInput } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import {
4 chromium,
5 type Browser,
6 type BrowserContext,
7 type CDPSession,
8 type Page,
9} from "playwright-core";
10import {
11 afterAll,
12 afterEach,
13 beforeAll,
14 beforeEach,
15 describe,
16 expect,
17 it,
18 vi,
19} from "vite-plus/test";
20
21import * as ServerBrowserPage from "./ServerBrowserPage.ts";
22import { SessionControl } from "./SessionControl.ts";
23
24const decodeEvaluateInput = Schema.decodeUnknownSync(PreviewAutomationEvaluateInput);
25
26describe("snapshot deadline diagnostics", () => {
27 const never = () => new Promise<never>(() => {});
28 const stalledSnapshot = async (options: {
29 readonly stalled?: "metrics";
30 readonly page?: Partial<Record<keyof Page, unknown>>;
31 readonly advanceMs: number;
32 }) => {
33 vi.useFakeTimers();
34 try {
35 const frame = {};
36 const page = {
37 viewportSize: () => ({ width: 1280, height: 800 }),
38 mainFrame: () => frame,
39 frames: () => [frame],
40 on: () => {},
41 evaluate: async () => ({
42 url: "about:blank",
43 title: "",
44 loading: false,
45 visibleText: "",
46 interactiveElements: [],
47 }),
48 ariaSnapshot: async () => "",
49 ...options.page,
50 } as unknown as Page;
51 const cdp = {
52 send: async (method: string) => {
53 if (options.stalled === "metrics") return never();
54 if (method === "Page.captureScreenshot") return { data: "" };
55 if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
56 if (method === "Page.createIsolatedWorld") return { executionContextId: 1 };
57 if (method === "Runtime.evaluate") return { result: { value: [] } };
58 throw new Error(`Unexpected command: ${method}`);
59 },
60 } as unknown as CDPSession;
61 const captured = ServerBrowserPage.snapshot({
62 page,
63 cdp,
64 renderScale: options.stalled === "metrics" ? "display" : 1,
65 consoleEntries: [],
66 networkEntries: [],
67 actionTimeline: [],
68 }).catch((error: unknown) => error);
69 await vi.advanceTimersByTimeAsync(options.advanceMs);
70 return await captured;
71 } finally {
72 vi.useRealTimers();
73 }
74 };
75
76 it("identifies a stalled metrics read", async () => {
77 expect(await stalledSnapshot({ stalled: "metrics", advanceMs: 10_000 })).toMatchObject({
78 tag: "PreviewAutomationTimeoutError",
79 detail: { timeoutMs: 10_000, pendingStages: ["metrics"] },
80 });
81 });
82
83 it("keeps an accessibility tree that hit its own timeout", async () => {
84 const timedOut = Object.assign(new Error("Timeout exceeded"), { name: "TimeoutError" });
85 const captured = await stalledSnapshot({
86 page: { ariaSnapshot: () => Promise.reject(timedOut) },
87 advanceMs: 0,
88 });
89 expect(captured).toMatchObject({
90 tag: "PreviewAutomationTimeoutError",
91 detail: { timeoutMs: 10_000 },
92 });
93 expect((captured as ServerBrowserPage.ServerBrowserOperationError).detail).toMatchObject({
94 pendingStages: expect.arrayContaining(["accessibility tree"]),
95 });
96 });
97
98 it("omits a timed-out stage after it succeeds on retry", async () => {
99 let attempts = 0;
100 const timedOut = Object.assign(new Error("Timeout exceeded"), { name: "TimeoutError" });
101 expect(
102 await stalledSnapshot({
103 page: {
104 evaluate: never,
105 ariaSnapshot: async () => {
106 if (attempts++ === 0) throw timedOut;
107 return "";
108 },
109 },
110 advanceMs: 10_000,
111 }),
112 ).toMatchObject({ detail: { timeoutMs: 10_000, pendingStages: ["page state"] } });
113 });
114
115 it.each(["elementHandle", "contentFrame"] as const)(
116 "identifies stalled iframe %s lookup",
117 async (stage) => {
118 const main = {};
119 const child = { evaluate: never, parentFrame: () => main };
120 const captured = await stalledSnapshot({
121 page: {
122 mainFrame: () => main,
123 frames: () => [main, child],
124 context: () => ({
125 newCDPSession: () =>
126 Promise.reject(new Error("Only this preview tab's page can be attached")),
127 }),
128 ariaSnapshot: async () => "- iframe [ref=f1]:\n - text: inside",
129 locator: () => ({
130 elementHandle:
131 stage === "elementHandle" ? never : async () => ({ contentFrame: never }),
132 }),
133 },
134 advanceMs: 10_000,
135 });
136 expect(captured).toMatchObject({
137 detail: { timeoutMs: 10_000, pendingStages: expect.arrayContaining(["frames"]) },
138 });
139 },
140 );
141
142 it("reports a frame that didn't answer as the frame's own timeout", async () => {
143 const main = {};
144 // A desktop tab refuses frame sessions, so the frame is read in its own world.
145 const child = { evaluate: never, parentFrame: () => main };
146 const captured = await stalledSnapshot({
147 page: {
148 mainFrame: () => main,
149 frames: () => [main, child],
150 context: () => ({
151 newCDPSession: () =>
152 Promise.reject(new Error("Only this preview tab's page can be attached")),
153 }),
154 ariaSnapshot: async () => "- iframe [ref=f1]:\n - text: inside",
155 locator: () => ({
156 elementHandle: async () => ({ contentFrame: async () => child, dispose: async () => {} }),
157 }),
158 },
159 // Both attempts wait out the frame; neither reaches the capture deadline.
160 advanceMs: 2_000,
161 });
162 expect(captured).toMatchObject({
163 tag: "PreviewAutomationTimeoutError",
164 detail: { timeoutMs: 1_000, pendingStages: ["frames"] },
165 });
166 });
167});
168
169describe("server browser capture deadlines", () => {
170 it("releases control after an unanswered capture and ignores its late reply", async () => {
171 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
172 try {
173 const captured = Promise.withResolvers<{ data: string }>();
174 const send = vi.fn(async (method: string) =>
175 method === "Page.captureScreenshot"
176 ? captured.promise
177 : { result: { value: "still responsive" } },
178 );
179 const cdp = { send } as unknown as CDPSession;
180 const control = new SessionControl("agent");
181 let outcome: unknown;
182 const capture = control
183 .agent("agent", () => ServerBrowserPage.captureViewport(cdp, { format: "png" }))
184 .catch((cause: unknown) => {
185 outcome = cause;
186 });
187 const evaluation = control.agent("agent", () =>
188 ServerBrowserPage.evaluate(cdp, { expression: "document.title" }, 1_000),
189 );
190
191 await vi.advanceTimersByTimeAsync(3_000);
192 expect(outcome).toMatchObject({
193 tag: "PreviewAutomationExecutionError",
194 message: expect.stringContaining("not producing screenshot frames"),
195 });
196 await capture;
197 expect(await evaluation).toBe("still responsive");
198 expect(vi.getTimerCount()).toBe(0);
199
200 captured.resolve({ data: "late-frame" });
201 await captured.promise;
202 expect(outcome).toBeInstanceOf(ServerBrowserPage.ServerBrowserOperationError);
203 expect(send.mock.calls.map(([method]) => method)).toEqual([
204 "Page.captureScreenshot",
205 "Runtime.evaluate",
206 ]);
207 } finally {
208 vi.useRealTimers();
209 }
210 });
211});
212
213describe("server browser element refs", () => {
214 let browser: Browser;
215 let context: BrowserContext;
216 let page: Page;
217 let cdp: CDPSession;
218
219 beforeAll(async () => {
220 browser = await chromium.launch({ headless: true });
221 });
222 afterAll(async () => {
223 await browser?.close();
224 });
225 beforeEach(async () => {
226 context = await browser.newContext();
227 page = await context.newPage();
228 cdp = await context.newCDPSession(page);
229 });
230 afterEach(async () => {
231 await context.close();
232 });
233
234 const takeSnapshot = () =>
235 ServerBrowserPage.snapshot({
236 page,
237 cdp,
238 renderScale: 1,
239 consoleEntries: [],
240 networkEntries: [],
241 actionTimeline: [],
242 });
243 const locators = (tree: unknown) => {
244 expect(typeof tree).toBe("string");
245 return Array.from(
246 String(tree).matchAll(/\[ref=([^\]]+)\]/g),
247 (match) => `aria-ref=${match[1]}`,
248 );
249 };
250 const buttonLocator = (tree: unknown, name: string) => {
251 const line = String(tree)
252 .split("\n")
253 .find((line) => line.includes(`button "${name}"`));
254 const locator = locators(line)[0];
255 expect(locator).toBeDefined();
256 return locator!;
257 };
258 const repeatedRows = `<ul>${Array.from({ length: 5 }, (_, i) => `<li>row ${i + 1}<button data-testid="delete-row" onclick="this.parentElement.remove()">delete</button></li>`).join("")}</ul>`;
259
260 it("clicks the fifth repeated delete control without touching row one", async () => {
261 await page.setContent(repeatedRows);
262 const result = await takeSnapshot();
263 const buttons = String(result.accessibilityTree)
264 .split("\n")
265 .filter((line) => line.includes('button "delete"'));
266 expect(buttons).toHaveLength(5);
267 await ServerBrowserPage.click(page, { locator: locators(buttons[4])[0]!, timeoutMs: 1_000 });
268 expect(await page.locator("li").allTextContents()).toEqual([
269 "row 1delete",
270 "row 2delete",
271 "row 3delete",
272 "row 4delete",
273 ]);
274 });
275
276 it("returns from a click once it opens a dialog", async () => {
277 await page.setContent(
278 `<button onclick="document.body.dataset.answer = String(confirm('sure?'))">Confirm</button>`,
279 );
280 const dialog = new Promise<import("playwright-core").Dialog>((resolve) =>
281 page.once("dialog", resolve),
282 );
283 await ServerBrowserPage.click(page, {
284 locator: buttonLocator((await takeSnapshot()).accessibilityTree, "Confirm"),
285 timeoutMs: 1_000,
286 });
287 await (await dialog).accept();
288 await expect.poll(() => page.locator("body").getAttribute("data-answer")).toBe("true");
289 });
290
291 it("rejects ambiguous CSS controls without clicking any row", async () => {
292 await page.setContent(repeatedRows);
293 await expect(
294 ServerBrowserPage.click(page, {
295 selector: 'button[data-testid="delete-row"]',
296 timeoutMs: 1_000,
297 }),
298 ).rejects.toThrow(/strict mode violation/);
299 expect(await page.locator("li").count()).toBe(5);
300 });
301
302 it("tells a click target that matches nothing from one that never becomes clickable", async () => {
303 await page.setContent(`<button hidden>hidden</button>`);
304 const failure = (selector: string) =>
305 ServerBrowserPage.click(page, { selector, timeoutMs: 500 }).then(
306 () => expect.unreachable(),
307 ServerBrowserPage.toOperationError,
308 );
309
310 const absent = await failure(".definitely-no-such-t3-target");
311 expect(absent.tag).toBe("PreviewAutomationTimeoutError");
312 expect(absent.message).toBe(
313 'The click may have happened and removed its target or navigated; check the page before retrying. No element matches ".definitely-no-such-t3-target" after the timeout; take a fresh snapshot and use its locator.',
314 );
315 expect(absent.cause).toMatchObject({ name: "TimeoutError" });
316 const hidden = await failure("button");
317 expect(hidden.tag).toBe("PreviewAutomationTimeoutError");
318 expect(hidden.message).toBe(
319 'The click may have happened; check the page before retrying. "button" still matches an element after the timeout. Playwright last saw: element is not visible.',
320 );
321 });
322
323 it("gives a late target only the click's remaining time, not a fresh timeout", async () => {
324 await page.setContent(`<script>
325 setTimeout(() => document.body.insertAdjacentHTML("beforeend",
326 '<button id="save" disabled onclick="document.body.dataset.clicked = 1">Save</button>'), 1000);
327 setTimeout(() => document.querySelector("#save").disabled = false, 2500);
328 </script>`);
329 await expect(
330 ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 2_000 }),
331 ).rejects.toThrow();
332 expect(await page.locator("body").getAttribute("data-clicked")).toBeNull();
333 });
334
335 it("does not retarget a removed ref to a replacement node", async () => {
336 await page.setContent("<button onclick=\"this.textContent='clicked'\">original</button>");
337 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original");
338 await page.setContent("<button onclick=\"this.textContent='clicked'\">replacement</button>");
339 await expect(ServerBrowserPage.click(page, { locator, timeoutMs: 100 })).rejects.toThrow();
340 expect(await page.locator("button").textContent()).toBe("replacement");
341 });
342
343 it("targets iframe input refs and preserves the parent form", async () => {
344 await page.setContent(
345 '<input aria-label="parent"><iframe srcdoc="<input aria-label=child>"></iframe>',
346 );
347 await page.frameLocator("iframe").getByRole("textbox").waitFor();
348 const result = await takeSnapshot();
349 const line = String(result.accessibilityTree)
350 .split("\n")
351 .find((line) => line.includes('textbox "child"'));
352 const locator = locators(line)[0]!;
353 await ServerBrowserPage.type(page, { locator, text: "inside iframe", clear: true });
354 expect(await page.frameLocator("iframe").getByRole("textbox").inputValue()).toBe(
355 "inside iframe",
356 );
357 expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
358 });
359
360 it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
361 await page.setContent(`
362 <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
363 <input aria-label="Username" value="maria">
364 <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
365 <input type="password" role="combobox" aria-label="Code" value="role-pass">
366 <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
367 <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
368 <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
369 <iframe id="blank" src="javascript:false"></iframe>
370 <p>Order styled-pass-2</p>
371 <script>
372 // A frame that never commits a document, filled by its parent.
373 blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
374 // Page script can't change the value the snapshot sees.
375 Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
376 </script>`);
377 await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
378 await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
379 const result = await takeSnapshot();
380 const tree = String(result.accessibilityTree);
381 expect(tree).toContain('textbox "blank"');
382 expect(tree).not.toMatch(
383 /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
384 );
385 expect(result.visibleText).not.toContain("editable-pass");
386 expect(result.visibleText).toContain("Order ••••••••-2");
387 expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
388 const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
389 expect(line).toMatch(/: •+$/);
390 await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
391 expect(await page.locator("#pw").inputValue()).toBe("next");
392 });
393
394 it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
395 await page.setContent(`
396 <input type="password" aria-label="PIN" value="123">
397 <input type="password" aria-label="Phrase" value="open sesame">
398 <p>PIN: 123. Code (123) id 1234</p>
399 <p>open sesame</p>`);
400 const text = (await takeSnapshot()).visibleText;
401 expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
402 expect(text).not.toMatch(/open|sesame/);
403 await page.setContent(`
404 <p>${"x".repeat(19_995)}long-secret</p>
405 <input type="password" aria-label="Long" value="long-secret">`);
406 const cut = (await takeSnapshot()).visibleText;
407 expect(cut.length).toBe(20_000);
408 expect(cut.slice(-8)).toBe("xxx•••••");
409 });
410
411 it("shows a data: link or blocked data: navigation by media type only", async () => {
412 // Chromium keeps raw spaces and quotes in both, so a payload can't be cut at either.
413 await page.setContent(`
414 <a download href="data:text/plain;charset="a,b",head PAYLOAD'tail">Key</a>
415 <a href="https://example.com/data:report,2026">Report</a>
416 <a href="#">data:text/plain,label</a>
417 <a href='"data:text/plain,relative'>Relative</a>
418 <a href=" data:text/plain,PAYLOAD">Spaced</a>
419 <a href="da	ta:text/plain,PAYLOAD">Tabbed</a>
420 <a href="data:text/plain,head
PAYLOAD">Separated</a>
421 <a href="data:PAYLOAD,x">Typeless</a>
422 <a href="data:text/plain,PAYLOAD">Vertical tab</a>
423 <a href="data:text/plain,PAYLOAD">Backspace</a>
424 <a id="controlled">Controlled</a>
425 <a id="escaped">Escaped</a>
426 <script>
427 controlled.href = "\\x01data:text/plain,PAYLOAD";
428 escaped.href = "\\x02da\\tta:text/plain,PAYLOAD";
429 </script>`);
430 const tree = String((await takeSnapshot()).accessibilityTree);
431 expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8);
432 expect(tree).toContain("/url: data:,…");
433 expect(tree).toContain("/url: https://example.com/data:report,2026");
434 expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/);
435 expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/);
436 expect(tree).toContain('/url: "\\"data:text/plain,relative"');
437 });
438
439 it("redacts a data: link whose scheme a password value would mask", async () => {
440 await page.setContent(`
441 <input type="password" aria-label="Scheme" value="data">
442 <a download href="data:text/plain,PAYLOAD">Key</a>`);
443 const tree = String((await takeSnapshot()).accessibilityTree);
444 expect(tree).toContain("/url: ••••••••:text/plain,…");
445 expect(tree).not.toContain("PAYLOAD");
446 });
447
448 it("shows a data: page's own URL by media type only", async () => {
449 await page.goto("data:text/html,<title>Key</title>PAYLOAD");
450 expect((await takeSnapshot()).url).toBe("data:text/html,…");
451 });
452
453 it("rejects refs from another tab", async () => {
454 await page.setContent("<button>same label</button>");
455 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
456 const other = await context.newPage();
457 await other.setContent("<button>same label</button>");
458 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
459 });
460
461 it("revokes refs after navigation even when labels are identical", async () => {
462 await page.goto("data:text/html,<button>continue</button>");
463 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
464 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
465 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
466 });
467
468 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
469 "does not allow native refs to bypass generation validation (%s)",
470 async (locator) => {
471 await page.setContent("<button>continue</button>");
472 await takeSnapshot();
473 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
474 },
475 );
476
477 it("preserves quoted attribute values containing ref engine text", async () => {
478 await page.setContent(
479 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
480 );
481 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
482 expect(await page.locator("button").textContent()).toBe("saved");
483 });
484
485 it("evaluates top-level await and returns the last expression's value", async () => {
486 await page.setContent("<title>Ready</title>");
487 const result = await ServerBrowserPage.evaluate(
488 cdp,
489 { expression: "await Promise.resolve(); document.title" },
490 5_000,
491 );
492 expect(result).toBe("Ready");
493 });
494
495 it("returns object contents even when a legacy caller asks for a remote reference", async () => {
496 const input = decodeEvaluateInput({
497 expression: "({ answer: 42, nested: { ready: true } })",
498 returnByValue: false,
499 });
500 const result = await ServerBrowserPage.evaluate(cdp, input, 5_000);
501 expect(result).toEqual({ answer: 42, nested: { ready: true } });
502 });
503
504 it("still awaits the promise an async function returns", async () => {
505 const result = await ServerBrowserPage.evaluate(
506 cdp,
507 { expression: "(async () => { await 0; return 1 })()" },
508 5_000,
509 );
510 expect(result).toBe(1);
511 });
512
513 it("does not rerun an expression whose SyntaxError is thrown at runtime", async () => {
514 const evaluation = ServerBrowserPage.evaluate(
515 cdp,
516 { expression: "window.runs = (window.runs ?? 0) + 1; new Function('await 0')" },
517 5_000,
518 );
519 await expect(evaluation).rejects.toThrow("await is only valid");
520 expect(await page.evaluate("window.runs")).toBe(1);
521 });
522
523 it("does not rerun an expression whose awaited browser call rejects with a SyntaxError", async () => {
524 let posts = 0;
525 await page.route("http://preview.test/**", (route) => {
526 if (route.request().method() === "POST") posts++;
527 return route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" });
528 });
529 await page.goto("http://preview.test/");
530 const evaluation = ServerBrowserPage.evaluate(
531 cdp,
532 {
533 expression:
534 "(async () => { const r = await fetch('/api', { method: 'POST' }); return r.json() })()",
535 },
536 5_000,
537 );
538 await expect(evaluation).rejects.toThrow("is not valid JSON");
539 expect(posts).toBe(1);
540 });
541
542 it("returns the result of a top-level await expression that reloads the page", async () => {
543 await page.route("http://preview.test/", (route) =>
544 route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" }),
545 );
546 await page.goto("http://preview.test/");
547 const result = await ServerBrowserPage.evaluate(
548 cdp,
549 { expression: "await 0; location.reload(); ({ clicked: true })" },
550 5_000,
551 );
552 expect(result).toEqual({ clicked: true });
553 });
554});
555
556describe("server browser snapshot screenshot", () => {
557 let browser: Browser;
558 let context: BrowserContext;
559
560 beforeAll(async () => {
561 // ServerBrowserContexts launches with these, and the capture scale depends on them.
562 browser = await chromium.launch({
563 headless: true,
564 args: ["--disable-gpu", "--force-device-scale-factor=2"],
565 });
566 });
567 afterAll(async () => {
568 await browser?.close();
569 });
570 beforeEach(async () => {
571 context = await browser.newContext({
572 viewport: { width: 1280, height: 800 },
573 deviceScaleFactor: 2,
574 });
575 });
576 afterEach(async () => {
577 await context.close();
578 });
579
580 // Blue on the left half and red on the right, so a mirrored left half shows up on the right.
581 const halves = (overlay: string) => `
582 <style>
583 body { margin: 0; background: white; }
584 .half { position: absolute; top: 0; width: 640px; height: 800px; }
585 .overlay { position: fixed; inset: 0; ${overlay} }
586 </style>
587 <div class="half" style="left: 0; background: #2563eb"></div>
588 <div class="half" style="left: 640px; background: #ef4444"></div>
589 <div class="overlay"></div>`;
590
591 const screenshotOf = async (html: string) => {
592 const page = await context.newPage();
593 await page.setContent(html);
594 const { screenshot, fullScreenshot } = await ServerBrowserPage.snapshot({
595 page,
596 cdp: await context.newCDPSession(page),
597 renderScale: 2,
598 fullScreenshot: true,
599 consoleEntries: [],
600 networkEntries: [],
601 actionTimeline: [],
602 });
603 // The server has no DOM types, so the decoder runs as page source.
604 const points = [
605 [0.15, 0.75],
606 [0.85, 0.25],
607 [0.85, 0.75],
608 ];
609 const pixels = (await page.evaluate(`(async () => {
610 const bytes = Uint8Array.from(atob(${JSON.stringify(screenshot.data)}), (char) => char.charCodeAt(0));
611 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
612 const canvas = document.createElement("canvas");
613 canvas.width = bitmap.width;
614 canvas.height = bitmap.height;
615 const context = canvas.getContext("2d");
616 context.drawImage(bitmap, 0, 0);
617 return ${JSON.stringify(points)}.map(([x, y]) =>
618 Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data),
619 );
620 })()`)) as Array<[number, number, number, number]>;
621 return { screenshot, fullScreenshot, pixels };
622 };
623 const colorOf = ([red, green, blue]: readonly [number, number, number, number]) =>
624 blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`;
625
626 it("captures a blurred backdrop-filter page as rendered, not mirrored", async () => {
627 const { screenshot, pixels } = await screenshotOf(halves("backdrop-filter: blur(4px);"));
628
629 expect({
630 size: [screenshot.width, screenshot.height],
631 colors: pixels.map(colorOf),
632 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
633 });
634
635 it("captures a plain page at the shrunk size with its content in place", async () => {
636 const { screenshot, fullScreenshot, pixels } = await screenshotOf(halves(""));
637
638 expect({
639 size: [screenshot.width, screenshot.height],
640 fullSize: [fullScreenshot?.width, fullScreenshot?.height],
641 colors: pixels.map(colorOf),
642 }).toEqual({ size: [1280, 800], fullSize: [2560, 1600], colors: ["blue", "red", "red"] });
643 });
644
645 it("records the destination of a finite entrance animation without waiting on infinite ones", async () => {
646 const page = await context.newPage();
647 await page.setContent(`
648 <style>
649 body { margin: 0; background: #2563eb; }
650 @keyframes enter { from { opacity: 0; } to { opacity: 1; } }
651 @keyframes pulse { from { opacity: 0.5; } to { opacity: 1; } }
652 button { animation: pulse 2s infinite; }
653 #paused { animation: enter 2s paused; }
654 #overlay { display: none; position: fixed; inset: 0; background: #ef4444; }
655 #overlay.open { display: block; animation: enter 200ms both; }
656 </style>
657 <button onclick="document.querySelector('#overlay').classList.add('open')">Open</button>
658 <div id="paused"></div>
659 <div id="overlay"></div>
660 `);
661 await page.getByRole("button", { name: "Open" }).click();
662 const frame = await ServerBrowserPage.captureFinalRecordingFrame(
663 await context.newCDPSession(page),
664 80,
665 );
666 expect(frame).toBeDefined();
667 const pixel = (await page.evaluate(`(async () => {
668 const bytes = Uint8Array.from(atob(${JSON.stringify(frame)}), char => char.charCodeAt(0));
669 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" }));
670 const canvas = document.createElement("canvas");
671 canvas.width = bitmap.width;
672 canvas.height = bitmap.height;
673 const context = canvas.getContext("2d");
674 context.drawImage(bitmap, 0, 0);
675 return Array.from(context.getImageData(bitmap.width / 2, bitmap.height / 2, 1, 1).data);
676 })()`)) as [number, number, number, number];
677 expect(colorOf(pixel)).toBe("red");
678 });
679
680 it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => {
681 const page = await context.newPage();
682 await page.goto("data:text/xml,<a/>");
683 const { screenshot } = await ServerBrowserPage.snapshot({
684 page,
685 cdp: await context.newCDPSession(page),
686 renderScale: 2,
687 consoleEntries: [],
688 networkEntries: [],
689 actionTimeline: [],
690 });
691
692 expect([screenshot.width, screenshot.height]).toEqual([1280, 800]);
693 });
694});
695
696describe("server browser drag", () => {
697 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
698 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
699 const box = { x: 0, y: 0, width: 20, height: 20 };
700 const targetBox = Promise.withResolvers<typeof box>();
701 const page = {
702 locator: (selector: string) =>
703 selector === "#card"
704 ? {
705 scrollIntoViewIfNeeded: async () => {},
706 boundingBox: async () => box,
707 dragTo: () => Promise.reject(timedOut),
708 }
709 : { boundingBox: () => targetBox.promise },
710 } as unknown as Page;
711 const unobserved: Array<unknown> = [];
712 const onUnhandled = (reason: unknown) => unobserved.push(reason);
713 process.on("unhandledRejection", onUnhandled);
714 try {
715 let finished = false;
716 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
717 () => null,
718 (error: unknown) => error,
719 );
720 void settled.then(() => (finished = true));
721 // Two macrotask turns: Node reports a rejection nobody observed after the first.
722 for (let turn = 0; turn < 2; turn++) {
723 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
724 await new Promise((resolve) => setImmediate(resolve));
725 }
726 expect(finished).toBe(false);
727 targetBox.resolve(box);
728
729 expect(await settled).toBe(timedOut);
730 expect(unobserved).toEqual([]);
731 } finally {
732 process.off("unhandledRejection", onUnhandled);
733 }
734 });
735
736 it("moves the mouse after dragstart, so pages that track a drag with mousemove see it", async () => {
737 const browser = await chromium.launch({ headless: true });
738 try {
739 const page = await browser.newPage();
740 await page.setContent(`
741 <div style="display:flex;gap:40px">
742 <div id="source" draggable="true" style="width:200px;height:120px">source</div>
743 <div id="target" style="width:200px;height:120px">target</div>
744 </div>
745 <script>
746 window.events = [];
747 let dragging = false;
748 source.addEventListener("dragstart", (event) => {
749 event.preventDefault();
750 dragging = true;
751 events.push("dragstart");
752 });
753 addEventListener("mousemove", () => dragging && events.push("mousemove"));
754 addEventListener("mouseup", () => events.push("mouseup"));
755 </script>`);
756
757 await ServerBrowserPage.drag(page, { source: "#source", target: "#target" });
758
759 const events = (await page.evaluate("window.events")) as Array<string>;
760 expect(events.slice(0, 2)).toEqual(["dragstart", "mousemove"]);
761 expect(events.at(-1)).toBe("mouseup");
762 } finally {
763 await browser.close();
764 }
765 });
766});
767
768describe("server browser click", () => {
769 it("clicks a target the page replaced while it was being scrolled into view", async () => {
770 let scrolls = 0;
771 const clicks: Array<unknown> = [];
772 const page = {
773 locator: () => ({
774 // Playwright resolves the node once; a page re-rendering it detaches that node.
775 scrollIntoViewIfNeeded: async () => {
776 if (scrolls++ === 0) {
777 throw new Error("locator.scrollIntoViewIfNeeded: Element is not attached to the DOM");
778 }
779 },
780 boundingBox: async () => ({ x: 0, y: 0, width: 20, height: 20 }),
781 click: async (options: unknown) => {
782 clicks.push(options);
783 },
784 count: async () => 1,
785 }),
786 once: () => {},
787 off: () => {},
788 } as unknown as Page;
789
790 await expect(ServerBrowserPage.click(page, { selector: "#save" })).resolves.toEqual({
791 x: 10,
792 y: 10,
793 });
794 expect(clicks).toHaveLength(1);
795 });
796
797 it("retries a replaced target only within the action's timeout", async () => {
798 vi.useFakeTimers();
799 try {
800 const timeouts: Array<number | undefined> = [];
801 const clicks: Array<unknown> = [];
802 const detached = new Error(
803 "locator.scrollIntoViewIfNeeded: Element is not attached to the DOM",
804 );
805 const page = {
806 locator: () => ({
807 scrollIntoViewIfNeeded: async (options?: { timeout?: number }) => {
808 timeouts.push(options?.timeout);
809 vi.advanceTimersByTime(60);
810 throw detached;
811 },
812 click: async (options: unknown) => {
813 clicks.push(options);
814 },
815 }),
816 } as unknown as Page;
817
818 await expect(
819 ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 100 }),
820 ).rejects.toBe(detached);
821 expect(timeouts).toEqual([100, 40]);
822 expect(clicks).toHaveLength(0);
823 } finally {
824 vi.useRealTimers();
825 }
826 });
827});
828
829describe("server browser evaluate", () => {
830 it("does not retry a parse error that arrives after the timeout", async () => {
831 vi.useFakeTimers();
832 try {
833 const classic = Promise.withResolvers<unknown>();
834 const send = vi.fn((method: string) =>
835 method === "Runtime.evaluate" ? classic.promise : Promise.resolve({}),
836 );
837 const cdp = { send } as unknown as CDPSession;
838 const evaluation = ServerBrowserPage.evaluate(cdp, { expression: "await 0; 1" }, 10);
839 const rejected = expect(evaluation).rejects.toMatchObject({
840 tag: "PreviewAutomationTimeoutError",
841 });
842 await vi.advanceTimersByTimeAsync(10);
843 await rejected;
844 classic.resolve({
845 result: { type: "object" },
846 exceptionDetails: {
847 text: "Uncaught",
848 scriptId: "4",
849 exception: { type: "object", className: "SyntaxError" },
850 },
851 });
852 await classic.promise;
853 expect(send.mock.calls.map(([method]) => method)).toEqual([
854 "Runtime.evaluate",
855 "Runtime.terminateExecution",
856 ]);
857 } finally {
858 vi.useRealTimers();
859 }
860 });
861});
862
863describe("server browser unresponsive script", () => {
864 it("leaves a page that answers alone", async () => {
865 const send = vi.fn(async (_method: string) => ({}));
866 await ServerBrowserPage.stopUnresponsiveScript({ send } as unknown as CDPSession);
867 expect(send.mock.calls.map(([method]) => method)).toEqual(["Runtime.evaluate"]);
868 });
869});
870
871describe("server browser wait", () => {
872 it("ends at its timeout when a check never answers", async () => {
873 // As on a desktop tab whose Playwright utility world never answers.
874 const page = {
875 locator: () => ({ count: () => new Promise<number>(() => {}) }),
876 } as unknown as Page;
877 vi.useFakeTimers();
878 try {
879 let failure: unknown;
880 void ServerBrowserPage.waitFor(page, { selector: "button", timeoutMs: 300 }).catch(
881 (error: unknown) => (failure = error),
882 );
883 await vi.advanceTimersByTimeAsync(300);
884 expect(failure).toMatchObject({ tag: "PreviewAutomationTimeoutError" });
885 } finally {
886 vi.useRealTimers();
887 }
888 });
889});
890
891describe("server browser net errors", () => {
892 it.each([
893 ["net::ERR_CONNECTION_REFUSED", "ERR_CONNECTION_REFUSED", -102],
894 [
895 "page.goto: net::ERR_HTTP2_PROTOCOL_ERROR at https://localhost:5173/",
896 "ERR_HTTP2_PROTOCOL_ERROR",
897 -2,
898 ],
899 ["net::ERR_TLS13_DOWNGRADE_DETECTED", "ERR_TLS13_DOWNGRADE_DETECTED", -2],
900 ])("reads the whole error name from %j", (errorText, description, code) => {
901 expect(ServerBrowserPage.parseNetError(errorText)).toEqual({ description, code });
902 });
903});