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