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

ServerBrowserPage.test.ts

1,172 lines46.0 KB

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("JPEG screenshot dimensions", () => {
27 const encode = (bytes: number[]) => Buffer.from(bytes).toString("base64");
28 const frame = [0xff, 0xd8, 0xff, 0xc0, 0, 7, 8, 0, 24, 0, 32];
29​
30 it("reads valid dimensions and rejects invalid or incomplete frames", () => {
31 expect(ServerBrowserPage.jpegSize(encode(frame))).toEqual({ width: 32, height: 24 });
32 for (const bytes of [
33 [],
34 [0xff, 0xd8, 0xff, 0xe1, 0, 20, 1],
35 frame.slice(0, -1),
36 [...frame.slice(0, 7), 0, 0, 0, 32],
37 [...frame.slice(0, 9), 0, 0],
38 ]) {
39 expect(() => ServerBrowserPage.jpegSize(encode(bytes))).toThrow("Invalid JPEG screenshot.");
40 }
41 });
42});
43​
44describe("snapshot deadline diagnostics", () => {
45 const never = () => new Promise<never>(() => {});
46 const stalledSnapshot = async (options: {
47 readonly stalled?: "metrics";
48 readonly page?: Partial<Record<keyof Page, unknown>>;
49 readonly advanceMs: number;
50 }) => {
51 vi.useFakeTimers();
52 try {
53 const frame = {};
54 const page = {
55 viewportSize: () => ({ width: 1280, height: 800 }),
56 mainFrame: () => frame,
57 frames: () => [frame],
58 on: () => {},
59 evaluate: async () => ({
60 url: "about:blank",
61 title: "",
62 loading: false,
63 visibleText: "",
64 }),
65 ariaSnapshot: async () => "",
66 ...options.page,
67 } as unknown as Page;
68 const cdp = {
69 send: async (method: string) => {
70 if (options.stalled === "metrics") return never();
71 if (method === "Page.captureScreenshot") return { data: "" };
72 if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
73 if (method === "Page.createIsolatedWorld") return { executionContextId: 1 };
74 if (method === "Runtime.evaluate") return { result: { value: [] } };
75 throw new Error(`Unexpected command: ${method}`);
76 },
77 } as unknown as CDPSession;
78 const captured = ServerBrowserPage.snapshot({
79 page,
80 cdp,
81 renderScale: options.stalled === "metrics" ? "display" : 1,
82 consoleEntries: [],
83 networkEntries: [],
84 actionTimeline: [],
85 }).catch((error: unknown) => error);
86 await vi.advanceTimersByTimeAsync(options.advanceMs);
87 return await captured;
88 } finally {
89 vi.useRealTimers();
90 }
91 };
92​
93 it("identifies a stalled metrics read", async () => {
94 expect(await stalledSnapshot({ stalled: "metrics", advanceMs: 10_000 })).toMatchObject({
95 tag: "PreviewAutomationTimeoutError",
96 detail: { timeoutMs: 10_000, pendingStages: ["metrics"] },
97 });
98 });
99​
100 it("keeps an accessibility tree that hit its own timeout", async () => {
101 const timedOut = Object.assign(new Error("Timeout exceeded"), { name: "TimeoutError" });
102 const captured = await stalledSnapshot({
103 page: { ariaSnapshot: () => Promise.reject(timedOut) },
104 advanceMs: 0,
105 });
106 expect(captured).toMatchObject({
107 tag: "PreviewAutomationTimeoutError",
108 detail: { timeoutMs: 10_000 },
109 });
110 expect((captured as ServerBrowserPage.ServerBrowserOperationError).detail).toMatchObject({
111 pendingStages: expect.arrayContaining(["accessibility tree"]),
112 });
113 });
114​
115 it("omits a timed-out stage after it succeeds on retry", async () => {
116 let attempts = 0;
117 const timedOut = Object.assign(new Error("Timeout exceeded"), { name: "TimeoutError" });
118 expect(
119 await stalledSnapshot({
120 page: {
121 evaluate: never,
122 ariaSnapshot: async () => {
123 if (attempts++ === 0) throw timedOut;
124 return "";
125 },
126 },
127 advanceMs: 10_000,
128 }),
129 ).toMatchObject({ detail: { timeoutMs: 10_000, pendingStages: ["page state"] } });
130 });
131​
132 it.each(["elementHandle", "contentFrame"] as const)(
133 "identifies stalled iframe %s lookup",
134 async (stage) => {
135 const main = {};
136 const child = { evaluate: never, parentFrame: () => main };
137 const captured = await stalledSnapshot({
138 page: {
139 mainFrame: () => main,
140 frames: () => [main, child],
141 context: () => ({
142 newCDPSession: () =>
143 Promise.reject(new Error("Only this preview tab's page can be attached")),
144 }),
145 ariaSnapshot: async () => "- iframe [ref=f1]:\n - text: inside",
146 locator: () => ({
147 elementHandle:
148 stage === "elementHandle" ? never : async () => ({ contentFrame: never }),
149 }),
150 },
151 advanceMs: 10_000,
152 });
153 expect(captured).toMatchObject({
154 detail: { timeoutMs: 10_000, pendingStages: expect.arrayContaining(["frames"]) },
155 });
156 },
157 );
158​
159 it("reports a frame that didn't answer as the frame's own timeout", async () => {
160 const main = {};
161 // A desktop tab refuses frame sessions, so the frame is read in its own world.
162 const child = { evaluate: never, parentFrame: () => main };
163 const captured = await stalledSnapshot({
164 page: {
165 mainFrame: () => main,
166 frames: () => [main, child],
167 context: () => ({
168 newCDPSession: () =>
169 Promise.reject(new Error("Only this preview tab's page can be attached")),
170 }),
171 ariaSnapshot: async () => "- iframe [ref=f1]:\n - text: inside",
172 locator: () => ({
173 elementHandle: async () => ({ contentFrame: async () => child, dispose: async () => {} }),
174 }),
175 },
176 // Both attempts wait out the frame; neither reaches the capture deadline.
177 advanceMs: 2_000,
178 });
179 expect(captured).toMatchObject({
180 tag: "PreviewAutomationTimeoutError",
181 detail: { timeoutMs: 1_000, pendingStages: ["frames"] },
182 });
183 });
184});
185​
186describe("server browser capture deadlines", () => {
187 it("releases control after an unanswered capture and ignores its late reply", async () => {
188 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
189 try {
190 const captured = Promise.withResolvers<{ data: string }>();
191 const send = vi.fn(async (method: string) =>
192 method === "Page.captureScreenshot"
193 ? captured.promise
194 : { result: { value: "still responsive" } },
195 );
196 const cdp = { send } as unknown as CDPSession;
197 const control = new SessionControl("agent");
198 let outcome: unknown;
199 const capture = control
200 .agent("agent", () => ServerBrowserPage.captureViewport(cdp, { format: "png" }))
201 .catch((cause: unknown) => {
202 outcome = cause;
203 });
204 const evaluation = control.agent("agent", () =>
205 ServerBrowserPage.evaluate(cdp, { expression: "document.title" }, 1_000),
206 );
207​
208 await vi.advanceTimersByTimeAsync(3_000);
209 expect(outcome).toMatchObject({
210 tag: "PreviewAutomationExecutionError",
211 message: expect.stringContaining("not producing screenshot frames"),
212 });
213 await capture;
214 expect(await evaluation).toBe("still responsive");
215 expect(vi.getTimerCount()).toBe(0);
216​
217 captured.resolve({ data: "late-frame" });
218 await captured.promise;
219 expect(outcome).toBeInstanceOf(ServerBrowserPage.ServerBrowserOperationError);
220 expect(send.mock.calls.map(([method]) => method)).toEqual([
221 "Page.captureScreenshot",
222 "Runtime.evaluate",
223 ]);
224 } finally {
225 vi.useRealTimers();
226 }
227 });
228});
229​
230describe("server browser element refs", () => {
231 let browser: Browser;
232 let context: BrowserContext;
233 let page: Page;
234 let cdp: CDPSession;
235​
236 beforeAll(async () => {
237 browser = await chromium.launch({ headless: true });
238 });
239 afterAll(async () => {
240 await browser?.close();
241 });
242 beforeEach(async () => {
243 context = await browser.newContext();
244 page = await context.newPage();
245 cdp = await context.newCDPSession(page);
246 });
247 afterEach(async () => {
248 await context.close();
249 });
250​
251 const takeSnapshot = () =>
252 ServerBrowserPage.snapshot({
253 page,
254 cdp,
255 renderScale: 1,
256 consoleEntries: [],
257 networkEntries: [],
258 actionTimeline: [],
259 });
260 const locators = (tree: unknown) => {
261 expect(typeof tree).toBe("string");
262 return Array.from(
263 String(tree).matchAll(/\[ref=([^\]]+)\]/g),
264 (match) => `aria-ref=${match[1]}`,
265 );
266 };
267 const buttonLocator = (tree: unknown, name: string) => {
268 const line = String(tree)
269 .split("\n")
270 .find((line) => line.includes(`button "${name}"`));
271 const locator = locators(line)[0];
272 expect(locator).toBeDefined();
273 return locator!;
274 };
275 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>`;
276​
277 it("does not report an empty interactiveElements list beside a tree full of controls", async () => {
278 await page.setContent(
279 `<a href="#signin">Sign in</a><button>Open menu</button><button>Dismiss local database notice</button>`,
280 );
281 const result = await takeSnapshot();
282 expect(buttonLocator(result.accessibilityTree, "Open menu")).toBeDefined();
283 expect(String(result.accessibilityTree)).toContain('link "Sign in"');
284 const elements = (
285 result as { readonly interactiveElements?: ReadonlyArray<{ readonly name: string }> }
286 ).interactiveElements;
287 if (elements !== undefined) {
288 expect(elements.map((element) => element.name)).toEqual(
289 expect.arrayContaining(["Sign in", "Open menu", "Dismiss local database notice"]),
290 );
291 }
292 });
293​
294 it("clicks the fifth repeated delete control without touching row one", async () => {
295 await page.setContent(repeatedRows);
296 const result = await takeSnapshot();
297 const buttons = String(result.accessibilityTree)
298 .split("\n")
299 .filter((line) => line.includes('button "delete"'));
300 expect(buttons).toHaveLength(5);
301 await ServerBrowserPage.click(page, { locator: locators(buttons[4])[0]!, timeoutMs: 1_000 });
302 expect(await page.locator("li").allTextContents()).toEqual([
303 "row 1delete",
304 "row 2delete",
305 "row 3delete",
306 "row 4delete",
307 ]);
308 });
309​
310 it("returns from a click once it opens a dialog", async () => {
311 await page.setContent(
312 `<button onclick="document.body.dataset.answer = String(confirm('sure?'))">Confirm</button>`,
313 );
314 const dialog = new Promise<import("playwright-core").Dialog>((resolve) =>
315 page.once("dialog", resolve),
316 );
317 await ServerBrowserPage.click(page, {
318 locator: buttonLocator((await takeSnapshot()).accessibilityTree, "Confirm"),
319 timeoutMs: 1_000,
320 });
321 await (await dialog).accept();
322 await expect.poll(() => page.locator("body").getAttribute("data-answer")).toBe("true");
323 });
324​
325 it("rejects ambiguous CSS controls without clicking any row", async () => {
326 await page.setContent(repeatedRows);
327 await expect(
328 ServerBrowserPage.click(page, {
329 selector: 'button[data-testid="delete-row"]',
330 timeoutMs: 1_000,
331 }),
332 ).rejects.toThrow(/strict mode violation/);
333 expect(await page.locator("li").count()).toBe(5);
334 });
335​
336 it("tells a click target that matches nothing from one that never becomes clickable", async () => {
337 await page.setContent(`<button hidden>hidden</button>`);
338 const failure = (selector: string) =>
339 ServerBrowserPage.click(page, { selector, timeoutMs: 500 }).then(
340 () => expect.unreachable(),
341 ServerBrowserPage.toOperationError,
342 );
343​
344 const absent = await failure(".definitely-no-such-t3-target");
345 expect(absent.tag).toBe("PreviewAutomationTimeoutError");
346 expect(absent.message).toBe(
347 '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.',
348 );
349 expect(absent.cause).toMatchObject({ name: "TimeoutError" });
350 const longEmoji = await failure(`text=x${"🎉".repeat(150)}`);
351 expect(longEmoji.message).toContain(`${"🎉".repeat(96)}...`);
352 expect(longEmoji.message.isWellFormed()).toBe(true);
353 const hidden = await failure("button");
354 expect(hidden.tag).toBe("PreviewAutomationTimeoutError");
355 expect(hidden.message).toBe(
356 '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.',
357 );
358 });
359​
360 it("gives a late target only the click's remaining time, not a fresh timeout", async () => {
361 await page.setContent(`<script>
362 setTimeout(() => document.body.insertAdjacentHTML("beforeend",
363 '<button id="save" disabled onclick="document.body.dataset.clicked = 1">Save</button>'), 1000);
364 setTimeout(() => document.querySelector("#save").disabled = false, 2500);
365 </script>`);
366 await expect(
367 ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 2_000 }),
368 ).rejects.toThrow();
369 expect(await page.locator("body").getAttribute("data-clicked")).toBeNull();
370 });
371​
372 it("does not retarget a removed ref to a replacement node", async () => {
373 await page.setContent("<button onclick=\"this.textContent='clicked'\">original</button>");
374 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original");
375 await page.setContent("<button onclick=\"this.textContent='clicked'\">replacement</button>");
376 await expect(ServerBrowserPage.click(page, { locator, timeoutMs: 100 })).rejects.toThrow();
377 expect(await page.locator("button").textContent()).toBe("replacement");
378 });
379​
380 it("targets iframe input refs and preserves the parent form", async () => {
381 await page.setContent(
382 '<input aria-label="parent"><iframe srcdoc="<input aria-label=child>"></iframe>',
383 );
384 await page.frameLocator("iframe").getByRole("textbox").waitFor();
385 const result = await takeSnapshot();
386 const line = String(result.accessibilityTree)
387 .split("\n")
388 .find((line) => line.includes('textbox "child"'));
389 const locator = locators(line)[0]!;
390 await ServerBrowserPage.type(page, { locator, text: "inside iframe", clear: true });
391 expect(await page.frameLocator("iframe").getByRole("textbox").inputValue()).toBe(
392 "inside iframe",
393 );
394 expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
395 });
396​
397 it("types after a click by coordinates into a shadow-root field, and refuses a field inside an editable frame", async () => {
398 await page.setContent(
399 `<div id="host"></div><div contenteditable="true"><iframe srcdoc="<input id=inner>"></iframe></div><script>document.getElementById("host").attachShadow({mode:"open"}).innerHTML = "<input id=field>";</script>`,
400 );
401 const field = page.locator("#host #field");
402 const box = (await field.boundingBox())!;
403 await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
404 await ServerBrowserPage.type(page, { text: "shadow" });
405 expect(await field.inputValue()).toBe("shadow");
406​
407 // Refused for now: focus inside a frame cannot be checked from the top document.
408 const inner = page.frameLocator("iframe").locator("#inner");
409 await inner.click();
410 await expect(ServerBrowserPage.type(page, { text: "frame" })).rejects.toMatchObject({
411 tag: "PreviewAutomationTargetNotEditableError",
412 });
413 expect(await inner.inputValue()).toBe("");
414 });
415​
416 it("types into a field that builds its value from keydown, with and without clear", async () => {
417 await page.setContent(
418 `<input id=a><input id=b><script>for(const f of[a,b]){f.keys="";f.onkeydown=e=>{if(e.key.length===1){e.preventDefault();f.keys+=e.key}}}</script>`,
419 );
420 const keys = (selector: string) =>
421 page.locator(selector).evaluate((field) => (field as unknown as { keys: string }).keys);
422 await ServerBrowserPage.type(page, { locator: "#a", text: "girona42" });
423 expect(await keys("#a")).toBe("girona42");
424 await ServerBrowserPage.type(page, { locator: "#b", text: "girona42", clear: true });
425 expect(await keys("#b")).toBe("girona42");
426 await ServerBrowserPage.type(page, { locator: "#b", text: "a".repeat(501), clear: true });
427 expect(await keys("#b")).toBe(`girona42${"a".repeat(501)}`);
428​
429 await page.setContent(
430 `<form onsubmit="event.preventDefault();sent.value='sent'"><label for=e>Email</label><input id=e value=old><input id=d type=date value=2020-02-02><label>Tint <input id=c type=color></label><input id=r type=range><textarea id=t></textarea><input id=sent></form>`,
431 );
432 await ServerBrowserPage.type(page, { locator: "text=Email", text: "a@b.c", clear: true });
433 expect(await page.locator("#e").inputValue()).toBe("a@b.c");
434 await ServerBrowserPage.type(page, { locator: "#d", text: "2026-01-31", clear: true });
435 expect(await page.locator("#d").inputValue()).toBe("2026-01-31");
436 await ServerBrowserPage.type(page, { locator: "text=Tint", text: "#ff0000", clear: true });
437 expect(await page.locator("#c").inputValue()).toBe("#ff0000");
438 await ServerBrowserPage.type(page, { locator: "#r", text: "70", clear: true });
439 expect(await page.locator("#r").inputValue()).toBe("70");
440 await ServerBrowserPage.type(page, { locator: "#e", text: "x\ny" });
441 await ServerBrowserPage.type(page, { locator: "#t", text: "one\r\ntwo" });
442 expect(await page.locator("#t").inputValue()).toBe("one\ntwo");
443 expect(await page.locator("#sent").inputValue()).toBe("");
444 });
445​
446 it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
447 await page.setContent(`
448 <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
449 <input aria-label="Username" value="maria">
450 <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
451 <input type="password" role="combobox" aria-label="Code" value="role-pass">
452 <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
453 <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
454 <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
455 <iframe id="blank" src="javascript:false"></iframe>
456 <p>Order styled-pass-2</p>
457 <script>
458 // A frame that never commits a document, filled by its parent.
459 blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
460 // Page script can't change the value the snapshot sees.
461 Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
462 </script>`);
463 await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
464 await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
465 const result = await takeSnapshot();
466 const tree = String(result.accessibilityTree);
467 expect(tree).toContain('textbox "blank"');
468 expect(tree).not.toMatch(
469 /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
470 );
471 expect(result.visibleText).not.toContain("editable-pass");
472 expect(result.visibleText).toContain("Order ••••••••-2");
473 expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
474 const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
475 expect(line).toMatch(/: •+$/);
476 await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
477 expect(await page.locator("#pw").inputValue()).toBe("next");
478 });
479​
480 it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
481 await page.setContent(`
482 <input type="password" aria-label="PIN" value="123">
483 <input type="password" aria-label="Phrase" value="open&nbsp;sesame">
484 <p>PIN: 123. Code (123) id 1234</p>
485 <p>open&nbsp;sesame</p>`);
486 const text = (await takeSnapshot()).visibleText;
487 expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
488 expect(text).not.toMatch(/open|sesame/);
489 await page.setContent(`
490 <p>${"x".repeat(19_995)}long-secret</p>
491 <input type="password" aria-label="Long" value="long-secret">`);
492 const cut = (await takeSnapshot()).visibleText;
493 expect(cut.length).toBe(20_000);
494 expect(cut.slice(-8)).toBe("xxx•••••");
495 });
496​
497 it("shows a data: link or blocked data: navigation by media type only", async () => {
498 // Chromium keeps raw spaces and quotes in both, so a payload can't be cut at either.
499 await page.setContent(`
500 <a download href="data:text/plain;charset=&quot;a,b&quot;,head PAYLOAD'tail">Key</a>
501 <a href="https://example.com/data:report,2026">Report</a>
502 <a href="#">data:text/plain,label</a>
503 <a href='"data:text/plain,relative'>Relative</a>
504 <a href=" data:text/plain,PAYLOAD">Spaced</a>
505 <a href="da&#9;ta:text/plain,PAYLOAD">Tabbed</a>
506 <a href="data:text/plain,head&#x2028;PAYLOAD">Separated</a>
507 <a href="data:PAYLOAD,x">Typeless</a>
508 <a href="&#11;data:text/plain,PAYLOAD">Vertical tab</a>
509 <a href="&#8;data:text/plain,PAYLOAD">Backspace</a>
510 <a id="controlled">Controlled</a>
511 <a id="escaped">Escaped</a>
512 <script>
513 controlled.href = "\\x01data:text/plain,PAYLOAD";
514 escaped.href = "\\x02da\\tta:text/plain,PAYLOAD";
515 </script>`);
516 const tree = String((await takeSnapshot()).accessibilityTree);
517 expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8);
518 expect(tree).toContain("/url: data:,…");
519 expect(tree).toContain("/url: https://example.com/data:report,2026");
520 expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/);
521 expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/);
522 expect(tree).toContain('/url: "\\"data:text/plain,relative"');
523 });
524​
525 it("redacts a data: link whose scheme a password value would mask", async () => {
526 await page.setContent(`
527 <input type="password" aria-label="Scheme" value="data">
528 <a download href="data:text/plain,PAYLOAD">Key</a>`);
529 const tree = String((await takeSnapshot()).accessibilityTree);
530 expect(tree).toContain("/url: ••••••••:text/plain,…");
531 expect(tree).not.toContain("PAYLOAD");
532 });
533​
534 it("shows a data: page's own URL by media type only", async () => {
535 await page.goto("data:text/html,<title>Key</title>PAYLOAD");
536 expect((await takeSnapshot()).url).toBe("data:text/html,…");
537 });
538​
539 it("rejects refs from another tab", async () => {
540 await page.setContent("<button>same label</button>");
541 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
542 const other = await context.newPage();
543 await other.setContent("<button>same label</button>");
544 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
545 });
546​
547 it("revokes refs after navigation even when labels are identical", async () => {
548 await page.goto("data:text/html,<button>continue</button>");
549 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
550 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
551 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
552 });
553​
554 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
555 "does not allow native refs to bypass generation validation (%s)",
556 async (locator) => {
557 await page.setContent("<button>continue</button>");
558 await takeSnapshot();
559 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
560 },
561 );
562​
563 it("preserves quoted attribute values containing ref engine text", async () => {
564 await page.setContent(
565 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
566 );
567 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
568 expect(await page.locator("button").textContent()).toBe("saved");
569 });
570​
571 it("evaluates top-level await and returns the last expression's value", async () => {
572 await page.setContent("<title>Ready</title>");
573 const result = await ServerBrowserPage.evaluate(
574 cdp,
575 { expression: "await Promise.resolve(); document.title" },
576 5_000,
577 );
578 expect(result).toBe("Ready");
579 });
580​
581 it("returns object contents even when a legacy caller asks for a remote reference", async () => {
582 const input = decodeEvaluateInput({
583 expression: "({ answer: 42, nested: { ready: true } })",
584 returnByValue: false,
585 });
586 const result = await ServerBrowserPage.evaluate(cdp, input, 5_000);
587 expect(result).toEqual({ answer: 42, nested: { ready: true } });
588 });
589​
590 it("still awaits the promise an async function returns", async () => {
591 const result = await ServerBrowserPage.evaluate(
592 cdp,
593 { expression: "(async () => { await 0; return 1 })()" },
594 5_000,
595 );
596 expect(result).toBe(1);
597 });
598​
599 it("does not rerun an expression whose SyntaxError is thrown at runtime", async () => {
600 const evaluation = ServerBrowserPage.evaluate(
601 cdp,
602 { expression: "window.runs = (window.runs ?? 0) + 1; new Function('await 0')" },
603 5_000,
604 );
605 await expect(evaluation).rejects.toThrow("await is only valid");
606 expect(await page.evaluate("window.runs")).toBe(1);
607 });
608​
609 it("does not rerun an expression whose awaited browser call rejects with a SyntaxError", async () => {
610 let posts = 0;
611 await page.route("http://preview.test/**", (route) => {
612 if (route.request().method() === "POST") posts++;
613 return route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" });
614 });
615 await page.goto("http://preview.test/");
616 const evaluation = ServerBrowserPage.evaluate(
617 cdp,
618 {
619 expression:
620 "(async () => { const r = await fetch('/api', { method: 'POST' }); return r.json() })()",
621 },
622 5_000,
623 );
624 await expect(evaluation).rejects.toThrow("is not valid JSON");
625 expect(posts).toBe(1);
626 });
627​
628 it("returns the result of a top-level await expression that reloads the page", async () => {
629 await page.route("http://preview.test/", (route) =>
630 route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" }),
631 );
632 await page.goto("http://preview.test/");
633 const result = await ServerBrowserPage.evaluate(
634 cdp,
635 { expression: "await 0; location.reload(); ({ clicked: true })" },
636 5_000,
637 );
638 expect(result).toEqual({ clicked: true });
639 });
640});
641​
642describe("server browser snapshot screenshot", () => {
643 let browser: Browser;
644 let context: BrowserContext;
645​
646 beforeAll(async () => {
647 // ServerBrowserContexts launches with these, and the capture scale depends on them.
648 browser = await chromium.launch({
649 headless: true,
650 args: ["--disable-gpu", "--force-device-scale-factor=2"],
651 });
652 });
653 afterAll(async () => {
654 await browser?.close();
655 });
656 beforeEach(async () => {
657 context = await browser.newContext({
658 viewport: { width: 1280, height: 800 },
659 deviceScaleFactor: 2,
660 });
661 });
662 afterEach(async () => {
663 await context.close();
664 });
665​
666 // Blue on the left half and red on the right, so a mirrored left half shows up on the right.
667 const halves = (overlay: string) => `
668 <style>
669 body { margin: 0; background: white; }
670 .half { position: absolute; top: 0; width: 640px; height: 800px; }
671 .overlay { position: fixed; inset: 0; ${overlay} }
672 </style>
673 <div class="half" style="left: 0; background: #2563eb"></div>
674 <div class="half" style="left: 640px; background: #ef4444"></div>
675 <div class="overlay"></div>`;
676​
677 const screenshotOf = async (html: string) => {
678 const page = await context.newPage();
679 await page.setContent(html);
680 const input = {
681 page,
682 cdp: await context.newCDPSession(page),
683 renderScale: 2,
684 fullScreenshot: true,
685 consoleEntries: [],
686 networkEntries: [],
687 actionTimeline: [],
688 };
689 const { screenshot, fullScreenshot } = await ServerBrowserPage.snapshot(input);
690 // The server has no DOM types, so the decoder runs as page source.
691 const points = [
692 [0.15, 0.75],
693 [0.85, 0.25],
694 [0.85, 0.75],
695 ];
696 const pixels = (await page.evaluate(`(async () => {
697 const bytes = Uint8Array.from(atob(${JSON.stringify(screenshot.data)}), (char) => char.charCodeAt(0));
698 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
699 const canvas = document.createElement("canvas");
700 canvas.width = bitmap.width;
701 canvas.height = bitmap.height;
702 const context = canvas.getContext("2d");
703 context.drawImage(bitmap, 0, 0);
704 return ${JSON.stringify(points)}.map(([x, y]) =>
705 Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data),
706 );
707 })()`)) as Array<[number, number, number, number]>;
708 return { screenshot, fullScreenshot, pixels, input };
709 };
710 const colorOf = ([red, green, blue]: readonly [number, number, number, number]) =>
711 blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`;
712​
713 it("captures a blurred backdrop-filter page as rendered, not mirrored", async () => {
714 const { screenshot, pixels } = await screenshotOf(halves("backdrop-filter: blur(4px);"));
715​
716 expect({
717 size: [screenshot.width, screenshot.height],
718 colors: pixels.map(colorOf),
719 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
720 });
721​
722 it("captures a plain page at the shrunk size with its content in place", async () => {
723 const { screenshot, fullScreenshot, pixels, input } = await screenshotOf(halves(""));
724 const metadata = await ServerBrowserPage.snapshotMetadata(input);
725​
726 expect({
727 size: [screenshot.width, screenshot.height],
728 fullSize: [fullScreenshot?.width, fullScreenshot?.height],
729 metadataSize: metadata.screenshot,
730 colors: pixels.map(colorOf),
731 }).toEqual({
732 size: [1280, 800],
733 fullSize: [2560, 1600],
734 metadataSize: { width: 1280, height: 800 },
735 colors: ["blue", "red", "red"],
736 });
737 });
738​
739 it("records the destination of a finite entrance animation without waiting on infinite ones", async () => {
740 const page = await context.newPage();
741 await page.setContent(`
742 <style>
743 body { margin: 0; background: #2563eb; }
744 @keyframes enter { from { opacity: 0; } to { opacity: 1; } }
745 @keyframes pulse { from { opacity: 0.5; } to { opacity: 1; } }
746 button { animation: pulse 2s infinite; }
747 #paused { animation: enter 2s paused; }
748 #overlay { display: none; position: fixed; inset: 0; background: #ef4444; }
749 #overlay.open { display: block; animation: enter 200ms both; }
750 </style>
751 <button onclick="document.querySelector('#overlay').classList.add('open')">Open</button>
752 <div id="paused"></div>
753 <div id="overlay"></div>
754 `);
755 await page.getByRole("button", { name: "Open" }).click();
756 const frame = await ServerBrowserPage.captureFinalRecordingFrame(
757 await context.newCDPSession(page),
758 80,
759 );
760 expect(frame).toBeDefined();
761 const pixel = (await page.evaluate(`(async () => {
762 const bytes = Uint8Array.from(atob(${JSON.stringify(frame)}), char => char.charCodeAt(0));
763 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" }));
764 const canvas = document.createElement("canvas");
765 canvas.width = bitmap.width;
766 canvas.height = bitmap.height;
767 const context = canvas.getContext("2d");
768 context.drawImage(bitmap, 0, 0);
769 return Array.from(context.getImageData(bitmap.width / 2, bitmap.height / 2, 1, 1).data);
770 })()`)) as [number, number, number, number];
771 expect(colorOf(pixel)).toBe("red");
772 });
773​
774 it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => {
775 const page = await context.newPage();
776 await page.goto("data:text/xml,<a/>");
777 const { screenshot } = await ServerBrowserPage.snapshot({
778 page,
779 cdp: await context.newCDPSession(page),
780 renderScale: 2,
781 consoleEntries: [],
782 networkEntries: [],
783 actionTimeline: [],
784 });
785​
786 expect([screenshot.width, screenshot.height]).toEqual([1280, 800]);
787 });
788});
789​
790describe("server browser drag", () => {
791 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
792 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
793 const box = { x: 0, y: 0, width: 20, height: 20 };
794 const targetBox = Promise.withResolvers<typeof box>();
795 const page = {
796 locator: (selector: string) =>
797 selector === "#card"
798 ? {
799 scrollIntoViewIfNeeded: async () => {},
800 boundingBox: async () => box,
801 dragTo: () => Promise.reject(timedOut),
802 }
803 : { boundingBox: () => targetBox.promise },
804 } as unknown as Page;
805 const unobserved: Array<unknown> = [];
806 const onUnhandled = (reason: unknown) => unobserved.push(reason);
807 process.on("unhandledRejection", onUnhandled);
808 try {
809 let finished = false;
810 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
811 () => null,
812 (error: unknown) => error,
813 );
814 void settled.then(() => (finished = true));
815 // Two macrotask turns: Node reports a rejection nobody observed after the first.
816 for (let turn = 0; turn < 2; turn++) {
817 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
818 await new Promise((resolve) => setImmediate(resolve));
819 }
820 expect(finished).toBe(false);
821 targetBox.resolve(box);
822​
823 expect(await settled).toBe(timedOut);
824 expect(unobserved).toEqual([]);
825 } finally {
826 process.off("unhandledRejection", onUnhandled);
827 }
828 });
829​
830 it("moves the mouse after dragstart, so pages that track a drag with mousemove see it", async () => {
831 const browser = await chromium.launch({ headless: true });
832 try {
833 const page = await browser.newPage();
834 await page.setContent(`
835 <div style="display:flex;gap:40px">
836 <div id="source" draggable="true" style="width:200px;height:120px">source</div>
837 <div id="target" style="width:200px;height:120px">target</div>
838 </div>
839 <script>
840 window.events = [];
841 let dragging = false;
842 source.addEventListener("dragstart", (event) => {
843 event.preventDefault();
844 dragging = true;
845 events.push("dragstart");
846 });
847 addEventListener("mousemove", () => dragging && events.push("mousemove"));
848 addEventListener("mouseup", () => events.push("mouseup"));
849 </script>`);
850​
851 await ServerBrowserPage.drag(page, { source: "#source", target: "#target" });
852​
853 const events = (await page.evaluate("window.events")) as Array<string>;
854 expect(events.slice(0, 2)).toEqual(["dragstart", "mousemove"]);
855 expect(events.at(-1)).toBe("mouseup");
856 } finally {
857 await browser.close();
858 }
859 });
860});
861​
862describe("server browser action timeout", () => {
863 type StepOptions = { readonly timeout?: number };
864 it.each([
865 {
866 action: "hover",
867 act: (page: Page) => ServerBrowserPage.hover(page, { selector: "#a", timeoutMs: 9_000 }),
868 last: ["#a.hover 1"],
869 },
870 {
871 action: "drag",
872 act: (page: Page) =>
873 ServerBrowserPage.drag(page, { source: "#a", target: "#b", timeoutMs: 9_000 }),
874 last: ["#a.dragTo 1", "#b.boundingBox 1"],
875 },
876 ])("gives the $action's steps one shared timeout", async ({ act, last }) => {
877 let now = 0;
878 using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
879 const steps: Array<string> = [];
880 const box = { x: 0, y: 0, width: 20, height: 20 };
881 const page = {
882 locator: (selector: string) => {
883 const record = (step: string, options: StepOptions) =>
884 steps.push(`${selector}.${step} ${options.timeout}`);
885 return {
886 // Each step that finds the target takes 5 of the 9 seconds.
887 scrollIntoViewIfNeeded: async (options: StepOptions) => {
888 record("scrollIntoViewIfNeeded", options);
889 now += 5_000;
890 },
891 boundingBox: async (options: StepOptions) => {
892 record("boundingBox", options);
893 now += 5_000;
894 return box;
895 },
896 hover: async (options: StepOptions) => record("hover", options),
897 dragTo: async (_target: unknown, options: StepOptions) => record("dragTo", options),
898 };
899 },
900 } as unknown as Page;
901​
902 await act(page);
903​
904 expect(steps).toEqual(["#a.scrollIntoViewIfNeeded 9000", "#a.boundingBox 4000", ...last]);
905 });
906});
907​
908describe("server browser click", () => {
909 it("clicks a target the page replaced while it was being scrolled into view", async () => {
910 let scrolls = 0;
911 const clicks: Array<unknown> = [];
912 const page = {
913 locator: () => ({
914 // Playwright resolves the node once; a page re-rendering it detaches that node.
915 scrollIntoViewIfNeeded: async () => {
916 if (scrolls++ === 0) {
917 throw new Error("locator.scrollIntoViewIfNeeded: Element is not attached to the DOM");
918 }
919 },
920 boundingBox: async () => ({ x: 0, y: 0, width: 20, height: 20 }),
921 click: async (options: unknown) => {
922 clicks.push(options);
923 },
924 count: async () => 1,
925 }),
926 once: () => {},
927 off: () => {},
928 } as unknown as Page;
929​
930 await expect(ServerBrowserPage.click(page, { selector: "#save" })).resolves.toEqual({
931 x: 10,
932 y: 10,
933 });
934 expect(clicks).toHaveLength(1);
935 });
936​
937 it("retries a replaced target only within the action's timeout", async () => {
938 vi.useFakeTimers();
939 try {
940 const timeouts: Array<number | undefined> = [];
941 const clicks: Array<unknown> = [];
942 const detached = new Error(
943 "locator.scrollIntoViewIfNeeded: Element is not attached to the DOM",
944 );
945 const page = {
946 locator: () => ({
947 scrollIntoViewIfNeeded: async (options?: { timeout?: number }) => {
948 timeouts.push(options?.timeout);
949 vi.advanceTimersByTime(60);
950 throw detached;
951 },
952 click: async (options: unknown) => {
953 clicks.push(options);
954 },
955 }),
956 } as unknown as Page;
957​
958 await expect(
959 ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 100 }),
960 ).rejects.toBe(detached);
961 expect(timeouts).toEqual([100, 40]);
962 expect(clicks).toHaveLength(0);
963 } finally {
964 vi.useRealTimers();
965 }
966 });
967});
968​
969describe("server browser evaluate", () => {
970 it("does not retry a parse error that arrives after the timeout", async () => {
971 vi.useFakeTimers();
972 try {
973 const classic = Promise.withResolvers<unknown>();
974 const send = vi.fn((method: string) =>
975 method === "Runtime.evaluate" ? classic.promise : Promise.resolve({}),
976 );
977 const cdp = { send } as unknown as CDPSession;
978 const evaluation = ServerBrowserPage.evaluate(cdp, { expression: "await 0; 1" }, 10);
979 const rejected = expect(evaluation).rejects.toMatchObject({
980 tag: "PreviewAutomationTimeoutError",
981 });
982 await vi.advanceTimersByTimeAsync(10);
983 await rejected;
984 classic.resolve({
985 result: { type: "object" },
986 exceptionDetails: {
987 text: "Uncaught",
988 scriptId: "4",
989 exception: { type: "object", className: "SyntaxError" },
990 },
991 });
992 await classic.promise;
993 expect(send.mock.calls.map(([method]) => method)).toEqual([
994 "Runtime.evaluate",
995 "Runtime.terminateExecution",
996 ]);
997 } finally {
998 vi.useRealTimers();
999 }
1000 });
1001});
1002​
1003describe("server browser type", () => {
1004 // As on a desktop tab whose Playwright utility world never answers.
1005 const stalledPage = (focusAnswer: () => Promise<unknown>, typed: string[]) =>
1006 ({
1007 locator: () => ({ last: () => ({ count: () => new Promise<number>(() => {}) }) }),
1008 evaluate: focusAnswer,
1009 keyboard: { type: async (text: string) => void typed.push(text) },
1010 }) as unknown as Page;
1011​
1012 it("types into the focused field when Playwright's utility world never answers", async () => {
1013 vi.useFakeTimers();
1014 try {
1015 const typed: string[] = [];
1016 let outcome: unknown = "pending";
1017 const page = stalledPage(async () => true, typed);
1018 void ServerBrowserPage.type(page, { text: "hello", timeoutMs: 300 }).then(
1019 () => (outcome = "typed"),
1020 (error: unknown) => (outcome = error),
1021 );
1022 await vi.advanceTimersByTimeAsync(300);
1023 expect(outcome).toBe("typed");
1024 expect(typed).toEqual(["hello"]);
1025 } finally {
1026 vi.useRealTimers();
1028 });
1029​
1030 it("stops at its timeout without typing when the page never answers", async () => {
1031 vi.useFakeTimers();
1032 try {
1033 const typed: string[] = [];
1034 let outcome: unknown = "pending";
1035 const page = stalledPage(() => new Promise(() => {}), typed);
1036 void ServerBrowserPage.type(page, { text: "hello", timeoutMs: 300 }).then(
1037 () => (outcome = "typed"),
1038 (error: unknown) => (outcome = error),
1039 );
1040 await vi.advanceTimersByTimeAsync(300);
1041 expect(outcome).toMatchObject({
1042 tag: "PreviewAutomationTimeoutError",
1043 detail: { timeoutMs: 300 },
1044 });
1045 expect(typed).toEqual([]);
1046​
1047 // A target whose element is found but whose page then stops answering.
1048 const fill = vi.fn(async () => {});
1049 const hung = {
1050 locator: () => ({ evaluate: () => new Promise(() => {}), fill }),
1051 keyboard: { type: async (text: string) => void typed.push(text) },
1052 } as unknown as Page;
1053 void ServerBrowserPage.type(hung, {
1054 locator: "#field",
1055 text: "hello",
1056 clear: true,
1057 timeoutMs: 300,
1058 }).then(
1059 () => (outcome = "typed"),
1060 (error: unknown) => (outcome = error),
1061 );
1062 outcome = "pending";
1063 await vi.advanceTimersByTimeAsync(300);
1064 expect(outcome).toMatchObject({
1065 tag: "PreviewAutomationTimeoutError",
1066 detail: { timeoutMs: 300 },
1067 });
1068 expect(fill).not.toHaveBeenCalled();
1069 expect(typed).toEqual([]);
1070 } finally {
1071 vi.useRealTimers();
1073 });
1074});
1075​
1076describe("server browser unresponsive script", () => {
1077 it("leaves a page that answers alone", async () => {
1078 const send = vi.fn(async (_method: string) => ({}));
1079 await ServerBrowserPage.stopUnresponsiveScript({ send } as unknown as CDPSession);
1080 expect(send.mock.calls.map(([method]) => method)).toEqual(["Runtime.evaluate"]);
1081 });
1082});
1083​
1084describe("server browser wait", () => {
1085 it("ends at its timeout when a check never answers", async () => {
1086 // As on a desktop tab whose Playwright utility world never answers.
1087 const page = {
1088 locator: () => ({ count: () => new Promise<number>(() => {}) }),
1089 } as unknown as Page;
1090 vi.useFakeTimers();
1091 try {
1092 let failure: unknown;
1093 void ServerBrowserPage.waitFor(page, { selector: "button", timeoutMs: 300 }).catch(
1094 (error: unknown) => (failure = error),
1095 );
1096 await vi.advanceTimersByTimeAsync(300);
1097 expect(failure).toMatchObject({ tag: "PreviewAutomationTimeoutError" });
1098 } finally {
1099 vi.useRealTimers();
1101 });
1102});
1103​
1104describe("server browser net errors", () => {
1105 it.each([
1106 ["net::ERR_CONNECTION_REFUSED", "ERR_CONNECTION_REFUSED", -102],
1108 "page.goto: net::ERR_HTTP2_PROTOCOL_ERROR at https://localhost:5173/",
1109 "ERR_HTTP2_PROTOCOL_ERROR",
1110 -2,
1111 ],
1112 ["net::ERR_TLS13_DOWNGRADE_DETECTED", "ERR_TLS13_DOWNGRADE_DETECTED", -2],
1113 ])("reads the whole error name from %j", (errorText, description, code) => {
1114 expect(ServerBrowserPage.parseNetError(errorText)).toEqual({ description, code });
1115 });
1116});
1117​
1118describe("server browser recording encoder", () => {
1119 it("keeps the chunks under the attachment limit when a recording outgrows it", async () => {
1120 const browser = await chromium.launch({ headless: true });
1121 try {
1122 const page = await browser.newPage();
1123 await page.evaluate(() => {
1124 type Handler = ((event: { data: { size: number } }) => void) | null;
1125 class StubRecorder {
1126 static isTypeSupported = () => true;
1127 state = "inactive";
1128 mimeType = "video/webm";
1129 onstart: (() => void) | null = null;
1130 onstop: (() => void) | null = null;
1131 ondataavailable: Handler = null;
1132 readonly stream: unknown;
1133 constructor(stream: unknown) {
1134 this.stream = stream;
1135 (globalThis as unknown as { stub: StubRecorder }).stub = this;
1137 start() {
1138 this.state = "recording";
1139 queueMicrotask(() => this.onstart?.());
1141 stop() {
1142 this.state = "inactive";
1143 this.ondataavailable?.({ data: { size: 1 } });
1144 queueMicrotask(() => this.onstop?.());
1147 (globalThis as unknown as { MediaRecorder: unknown }).MediaRecorder = StubRecorder;
1148 });
1149 await page.evaluate(ServerBrowserPage.recordingEncoderScript(30));
1150 await page.evaluate(`(() => {
1151 const canvas = document.createElement("canvas");
1152 canvas.width = 8;
1153 canvas.height = 8;
1154 return __t3Recorder.frame(canvas.toDataURL("image/jpeg").split(",")[1], 8);
1155 })()`);
1156​
1157 const result = await page.evaluate(async () => {
1158 const MiB = 1024 * 1024;
1159 const { stub, __t3Recorder } = globalThis as unknown as {
1160 stub: { ondataavailable: (event: { data: { size: number } }) => void };
1161 __t3Recorder: { stop: () => Promise<unknown> };
1162 };
1163 for (const size of [20 * MiB, 20 * MiB, 20 * MiB]) stub.ondataavailable({ data: { size } });
1164 return __t3Recorder.stop();
1165 });
1166​
1167 expect(result).toEqual({ mimeType: "video/webm", count: 2, bytes: 40 * 1024 * 1024 });
1168 } finally {
1169 await browser.close();
1171 });
1172});