Open History to see the last commit
1import {
2 chromium,
3 type Browser,
4 type BrowserContext,
5 type CDPSession,
6 type Page,
7} from "playwright-core";
8import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vite-plus/test";
9
10import { presentAsChrome } from "./ServerBrowserContexts.ts";
11import * as ServerBrowserPage from "./ServerBrowserPage.ts";
12
13describe("server browser element refs", () => {
14 let browser: Browser;
15 let context: BrowserContext;
16 let page: Page;
17 let cdp: CDPSession;
18
19 beforeAll(async () => {
20 browser = await chromium.launch({ headless: true });
21 });
22 afterAll(async () => {
23 await browser?.close();
24 });
25 beforeEach(async () => {
26 context = await browser.newContext();
27 page = await context.newPage();
28 cdp = await context.newCDPSession(page);
29 });
30 afterEach(async () => {
31 await context.close();
32 });
33
34 const takeSnapshot = () =>
35 ServerBrowserPage.snapshot({
36 page,
37 cdp,
38 renderScale: 1,
39 consoleEntries: [],
40 networkEntries: [],
41 actionTimeline: [],
42 });
43 const locators = (tree: unknown) => {
44 expect(typeof tree).toBe("string");
45 return Array.from(
46 String(tree).matchAll(/\[ref=([^\]]+)\]/g),
47 (match) => `aria-ref=${match[1]}`,
48 );
49 };
50 const buttonLocator = (tree: unknown, name: string) => {
51 const line = String(tree)
52 .split("\n")
53 .find((line) => line.includes(`button "${name}"`));
54 const locator = locators(line)[0];
55 expect(locator).toBeDefined();
56 return locator!;
57 };
58 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>`;
59
60 it("clicks the fifth repeated delete control without touching row one", async () => {
61 await page.setContent(repeatedRows);
62 const result = await takeSnapshot();
63 const buttons = String(result.accessibilityTree)
64 .split("\n")
65 .filter((line) => line.includes('button "delete"'));
66 expect(buttons).toHaveLength(5);
67 await ServerBrowserPage.click(page, { locator: locators(buttons[4])[0]!, timeoutMs: 1_000 });
68 expect(await page.locator("li").allTextContents()).toEqual([
69 "row 1delete",
70 "row 2delete",
71 "row 3delete",
72 "row 4delete",
73 ]);
74 });
75
76 it("returns from a click once it opens a dialog", async () => {
77 await page.setContent(
78 `<button onclick="document.body.dataset.answer = String(confirm('sure?'))">Confirm</button>`,
79 );
80 const dialog = new Promise<import("playwright-core").Dialog>((resolve) =>
81 page.once("dialog", resolve),
82 );
83 await ServerBrowserPage.click(page, {
84 locator: buttonLocator((await takeSnapshot()).accessibilityTree, "Confirm"),
85 timeoutMs: 1_000,
86 });
87 await (await dialog).accept();
88 await expect.poll(() => page.locator("body").getAttribute("data-answer")).toBe("true");
89 });
90
91 it("rejects ambiguous CSS controls without clicking any row", async () => {
92 await page.setContent(repeatedRows);
93 await expect(
94 ServerBrowserPage.click(page, {
95 selector: 'button[data-testid="delete-row"]',
96 timeoutMs: 1_000,
97 }),
98 ).rejects.toThrow(/strict mode violation/);
99 expect(await page.locator("li").count()).toBe(5);
100 });
101
102 it("does not retarget a removed ref to a replacement node", async () => {
103 await page.setContent("<button onclick=\"this.textContent='clicked'\">original</button>");
104 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original");
105 await page.setContent("<button onclick=\"this.textContent='clicked'\">replacement</button>");
106 await expect(ServerBrowserPage.click(page, { locator, timeoutMs: 100 })).rejects.toThrow();
107 expect(await page.locator("button").textContent()).toBe("replacement");
108 });
109
110 it("targets iframe input refs and preserves the parent form", async () => {
111 await page.setContent(
112 '<input aria-label="parent"><iframe srcdoc="<input aria-label=child>"></iframe>',
113 );
114 await page.frameLocator("iframe").getByRole("textbox").waitFor();
115 const result = await takeSnapshot();
116 const line = String(result.accessibilityTree)
117 .split("\n")
118 .find((line) => line.includes('textbox "child"'));
119 const locator = locators(line)[0]!;
120 await ServerBrowserPage.type(page, { locator, text: "inside iframe", clear: true });
121 expect(await page.frameLocator("iframe").getByRole("textbox").inputValue()).toBe(
122 "inside iframe",
123 );
124 expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
125 });
126
127 it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
128 await page.setContent(`
129 <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
130 <input aria-label="Username" value="maria">
131 <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
132 <input type="password" role="combobox" aria-label="Code" value="role-pass">
133 <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
134 <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
135 <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
136 <iframe id="blank" src="javascript:false"></iframe>
137 <p>Order styled-pass-2</p>
138 <script>
139 // A frame that never commits a document, filled by its parent.
140 blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
141 // Page script can't change the value the snapshot sees.
142 Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
143 </script>`);
144 await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
145 await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
146 const result = await takeSnapshot();
147 const tree = String(result.accessibilityTree);
148 expect(tree).toContain('textbox "blank"');
149 expect(tree).not.toMatch(
150 /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
151 );
152 expect(result.visibleText).not.toContain("editable-pass");
153 // Page text masks the same values, so it can't be compared against the tree.
154 expect(result.visibleText).toContain("Order ••••••••-2");
155 expect(tree).toMatch(/row "password: •+"/);
156 expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
157 const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
158 expect(line).toMatch(/: •+$/);
159 await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
160 expect(await page.locator("#pw").inputValue()).toBe("next");
161 });
162
163 it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
164 await page.setContent(`
165 <input type="password" aria-label="PIN" value="123">
166 <input type="password" aria-label="Phrase" value="open sesame">
167 <p>PIN: 123. Code (123) id 1234</p>
168 <p>open sesame</p>`);
169 const text = (await takeSnapshot()).visibleText;
170 expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
171 expect(text).not.toMatch(/open|sesame/);
172 await page.setContent(`
173 <p>${"x".repeat(19_995)}long-secret</p>
174 <input type="password" aria-label="Long" value="long-secret">`);
175 const cut = (await takeSnapshot()).visibleText;
176 expect(cut.length).toBe(20_000);
177 // Masked before the cut, so no prefix of the value is left.
178 expect(cut.slice(-8)).toBe("xxx•••••");
179 });
180
181 it("shows a data: link or blocked data: navigation by media type only", async () => {
182 // Chromium keeps raw spaces and quotes in both, so a payload can't be cut at either.
183 await page.setContent(`
184 <a download href="data:text/plain;charset="a,b",head PAYLOAD'tail">Key</a>
185 <a href="https://example.com/data:report,2026">Report</a>
186 <a href="#">data:text/plain,label</a>
187 <a href='"data:text/plain,relative'>Relative</a>
188 <a href=" data:text/plain,PAYLOAD">Spaced</a>
189 <a href="da	ta:text/plain,PAYLOAD">Tabbed</a>
190 <a href="data:text/plain,head
PAYLOAD">Separated</a>
191 <a href="data:PAYLOAD,x">Typeless</a>
192 <a href="data:text/plain,PAYLOAD">Vertical tab</a>
193 <a href="data:text/plain,PAYLOAD">Backspace</a>
194 <a id="controlled">Controlled</a>
195 <a id="escaped">Escaped</a>
196 <script>
197 controlled.href = "\\x01data:text/plain,PAYLOAD";
198 escaped.href = "\\x02da\\tta:text/plain,PAYLOAD";
199 </script>`);
200 const tree = String((await takeSnapshot()).accessibilityTree);
201 expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8);
202 expect(tree).toContain("/url: data:,…");
203 expect(tree).toContain("/url: https://example.com/data:report,2026");
204 expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/);
205 expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/);
206 expect(tree).toContain('/url: "\\"data:text/plain,relative"');
207 });
208
209 it("redacts a data: link whose scheme a password value would mask", async () => {
210 await page.setContent(`
211 <input type="password" aria-label="Scheme" value="data">
212 <a download href="data:text/plain,PAYLOAD">Key</a>`);
213 const tree = String((await takeSnapshot()).accessibilityTree);
214 expect(tree).toContain("/url: ••••••••:text/plain,…");
215 expect(tree).not.toContain("PAYLOAD");
216 });
217
218 it("shows data: URLs in Chromium's console messages by media type, and page logs as written", async () => {
219 const logged: Array<string> = [];
220 page.on("console", (message) => logged.push(ServerBrowserPage.consoleText(message)));
221 await page.setContent(`
222 <meta http-equiv="Content-Security-Policy" content="img-src 'self'">
223 <script>console.log("Downloaded data:text/plain,example")</script>
224 <img src="data:image/png;base64,S0VZ">`);
225 // Chromium opens a data: URL whose type is malformed too, and quotes it unchanged.
226 for (const url of ["data:text/plain,head PAYLOAD'tail x", "data:text/plain charset,PAYLOAD"]) {
227 const blocked = page.waitForEvent("console");
228 await page.evaluate(`location.href = ${JSON.stringify(url)}`);
229 await blocked;
230 }
231 expect(logged).toEqual([
232 "Downloaded data:text/plain,example",
233 "Loading the image 'data:image/png,…",
234 "Not allowed to navigate top frame to data URL: data:text/plain,…",
235 "Not allowed to navigate top frame to data URL: data:,…",
236 ]);
237 });
238
239 it("rejects refs from another tab", async () => {
240 await page.setContent("<button>same label</button>");
241 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
242 const other = await context.newPage();
243 await other.setContent("<button>same label</button>");
244 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
245 });
246
247 it("revokes refs on takeover and issues usable refs in the next snapshot", async () => {
248 await page.setContent("<button onclick=\"this.textContent='clicked'\">continue</button>");
249 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
250 ServerBrowserPage.invalidateRefs(page);
251 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
252 const fresh = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
253 await ServerBrowserPage.click(page, { locator: fresh });
254 expect(await page.locator("button").textContent()).toBe("clicked");
255 });
256
257 it("revokes refs after navigation even when labels are identical", async () => {
258 await page.goto("data:text/html,<button>continue</button>");
259 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
260 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
261 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
262 });
263
264 it("only accepts refs from the most recent snapshot", async () => {
265 await page.setContent("<button>continue</button>");
266 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
267 await takeSnapshot();
268 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
269 });
270
271 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
272 "does not allow native refs to bypass generation validation (%s)",
273 async (locator) => {
274 await page.setContent("<button>continue</button>");
275 await takeSnapshot();
276 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
277 },
278 );
279
280 it("preserves CSS selectors containing an aria-ref attribute", async () => {
281 await page.setContent(
282 '<button aria-ref="save" onclick="this.textContent=\'saved\'">save</button>',
283 );
284 await ServerBrowserPage.click(page, { selector: 'button[aria-ref="save"]' });
285 expect(await page.locator("button").textContent()).toBe("saved");
286 });
287
288 it("preserves quoted attribute values containing ref engine text", async () => {
289 await page.setContent(
290 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
291 );
292 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
293 expect(await page.locator("button").textContent()).toBe("saved");
294 });
295
296 it("right-clicks, double-clicks, hovers, selects, and drags like a pointer user", async () => {
297 await page.setContent(`
298 <style>#menu { position: absolute; display: none } #hover:hover + #menu { display: block }</style>
299 <button id="target">target</button>
300 <div id="hover">hover me</div><div id="menu">menu item</div>
301 <select id="size"><option value="s">Small</option><option value="l">Large</option></select>
302 <div id="card" draggable="true">card</div><div id="lane" style="height:40px">lane</div>
303 <p id="log"></p>
304 <script>
305 const log = (text) => (document.getElementById("log").textContent += text + ";");
306 const target = document.getElementById("target");
307 target.addEventListener("contextmenu", (event) => { event.preventDefault(); log("context"); });
308 target.addEventListener("dblclick", () => log("dblclick"));
309 document.getElementById("card").addEventListener("dragstart", (event) =>
310 event.dataTransfer.setData("text/plain", "card"),
311 );
312 for (const type of ["dragenter", "dragover"])
313 document.getElementById("lane").addEventListener(type, (event) => event.preventDefault());
314 document.getElementById("lane").addEventListener("drop", () => log("drop"));
315 </script>`);
316 await ServerBrowserPage.click(page, { locator: "#target", button: "right" });
317 await ServerBrowserPage.click(page, { locator: "#target", clickCount: 2 });
318 await ServerBrowserPage.hover(page, { locator: "#hover" });
319 expect(await page.isVisible("#menu")).toBe(true);
320 expect(await ServerBrowserPage.select(page, { locator: "#size", values: ["Large"] })).toEqual({
321 selected: ["l"],
322 });
323 await ServerBrowserPage.drag(page, { source: "#card", target: "#lane" });
324 expect(await page.textContent("#log")).toBe("context;dblclick;drop;");
325 await expect(
326 ServerBrowserPage.select(page, { locator: "#target", values: ["s"] }),
327 ).rejects.toMatchObject({ tag: "PreviewAutomationTargetNotEditableError" });
328 });
329
330 it("shows the agent's pointer at each target before the action reaches the page", async () => {
331 await page.setContent(`
332 <button id="go" style="position:absolute;left:100px;top:40px;width:80px;height:20px">go</button>
333 <div id="tip" style="position:absolute;left:300px;top:40px;width:60px;height:20px">tip</div>
334 <div id="card" draggable="true" style="position:absolute;left:20px;top:120px;width:40px;height:40px">card</div>
335 <div id="lane" style="position:absolute;left:220px;top:120px;width:100px;height:40px">lane</div>
336 <script>
337 window.seen = [];
338 go.onclick = () => seen.push("click");
339 tip.onmouseenter = () => seen.push("hover");
340 card.ondragstart = (event) => event.dataTransfer.setData("text/plain", "card");
341 lane.ondragover = (event) => event.preventDefault();
342 lane.ondrop = () => seen.push("drop");
343 </script>`);
344 const shown: Array<string> = [];
345 const pointer: ServerBrowserPage.PointerReporter = async ({ x, y }, phase) => {
346 const seen = await page.evaluate("window.seen.length");
347 shown.push(`${phase}@${Math.round(x)},${Math.round(y)} after ${seen}`);
348 };
349 await ServerBrowserPage.click(page, { locator: "#go" }, pointer);
350 await ServerBrowserPage.hover(page, { locator: "#tip" }, pointer);
351 await ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }, pointer);
352 expect(shown).toEqual([
353 "click@140,50 after 0",
354 "move@330,50 after 1",
355 "move@40,140 after 2",
356 "move@270,140 after 2",
357 ]);
358 expect(await page.evaluate("window.seen")).toEqual(["click", "hover", "drop"]);
359 });
360
361 it("presents a headless page as Chrome, with client hints that agree", async () => {
362 await presentAsChrome(cdp, { platform: "linux", arch: "x64" });
363 // userAgentData exists only in secure contexts; https comes from a route.
364 let secChUa: string | undefined;
365 await page.route("https://example.test/", (route) => {
366 secChUa = route.request().headers()["sec-ch-ua"];
367 return route.fulfill({ contentType: "text/html", body: "<p>hi</p>" });
368 });
369 await page.goto("https://example.test/");
370 const identity = (await page.evaluate(`(async () => ({
371 userAgent: navigator.userAgent,
372 brands: navigator.userAgentData.brands.map((brand) => brand.brand),
373 full: (await navigator.userAgentData.getHighEntropyValues(["fullVersionList"]))
374 .fullVersionList.map((brand) => brand.brand),
375 }))()`)) as { userAgent: string; brands: string[]; full: string[] };
376 expect(identity.userAgent).not.toContain("Headless");
377 expect(identity.userAgent).toMatch(/ Chrome\/\d+\.0\.0\.0 /);
378 expect(identity.brands).toContain("Google Chrome");
379 expect([...identity.brands, ...identity.full].join()).not.toContain("Headless");
380 expect(secChUa).toContain('"Google Chrome"');
381 expect(secChUa).not.toContain("Headless");
382 });
383
384 it("stops an evaluation at its deadline so the page answers the next one", async () => {
385 await expect(
386 ServerBrowserPage.evaluate(cdp, { expression: "for (;;) {}" }, 200),
387 ).rejects.toMatchObject({ tag: "PreviewAutomationTimeoutError" });
388 expect(await ServerBrowserPage.evaluate(cdp, { expression: "1 + 1" }, 2_000)).toBe(2);
389 });
390});
391
392describe("server browser drag", () => {
393 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
394 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
395 const box = { x: 0, y: 0, width: 20, height: 20 };
396 const targetBox = Promise.withResolvers<typeof box>();
397 const page = {
398 locator: (selector: string) =>
399 selector === "#card"
400 ? {
401 scrollIntoViewIfNeeded: async () => {},
402 boundingBox: async () => box,
403 dragTo: () => Promise.reject(timedOut),
404 }
405 : { boundingBox: () => targetBox.promise },
406 } as unknown as Page;
407 const unobserved: Array<unknown> = [];
408 const onUnhandled = (reason: unknown) => unobserved.push(reason);
409 process.on("unhandledRejection", onUnhandled);
410 try {
411 let finished = false;
412 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
413 () => null,
414 (error: unknown) => error,
415 );
416 void settled.then(() => (finished = true));
417 // Two macrotask turns: Node reports a rejection nobody observed after the first.
418 await new Promise((resolve) => setImmediate(resolve));
419 await new Promise((resolve) => setImmediate(resolve));
420 expect(finished).toBe(false);
421 targetBox.resolve(box);
422
423 expect(await settled).toBe(timedOut);
424 expect(unobserved).toEqual([]);
425 } finally {
426 process.off("unhandledRejection", onUnhandled);
427 }
428 });
429});
430
431it("captures the native display viewport after page script reassigns the globals", async () => {
432 // Context deviceScaleFactor changes DPR but does not scale raw CDP captures.
433 const browser = await chromium.launch({
434 headless: true,
435 args: ["--force-device-scale-factor=1.5", "--window-size=1280,800"],
436 });
437 try {
438 const context = await browser.newContext({ viewport: null });
439 const page = await context.newPage();
440 const cdp = await context.newCDPSession(page);
441 await page.setContent(
442 "<script>devicePixelRatio = -1.5; innerWidth = 99999; innerHeight = 1e7;</script>",
443 );
444 expect(await page.evaluate("[devicePixelRatio, innerWidth, innerHeight]")).toEqual([
445 -1.5, 99999, 1e7,
446 ]);
447 const snapshotSize = async () => {
448 const { screenshot } = await ServerBrowserPage.snapshot({
449 page,
450 cdp,
451 renderScale: "display",
452 consoleEntries: [],
453 networkEntries: [],
454 actionTimeline: [],
455 });
456 const png = Buffer.from(screenshot.data, "base64");
457 const size = { width: png.readUInt32BE(16), height: png.readUInt32BE(20) };
458 expect(screenshot).toMatchObject(size);
459 return size;
460 };
461 expect(await snapshotSize()).toEqual({ width: 1280, height: 800 });
462 expect(await ServerBrowserPage.readPageMetrics(cdp)).toEqual({
463 ratio: 1.5,
464 width: 1280,
465 height: 800,
466 zoom: 1,
467 offset: { x: 0, y: 0 },
468 });
469 // Window bounds are ignored by headless Chromium on some hosts; a metrics override resizes
470 // the page everywhere, and Playwright's viewportSize() stays stale as it would on desktop.
471 await cdp.send("Emulation.setDeviceMetricsOverride", {
472 width: 390,
473 height: 844,
474 deviceScaleFactor: 0,
475 mobile: false,
476 });
477 expect(await ServerBrowserPage.readPageMetrics(cdp)).toMatchObject({
478 ratio: 1.5,
479 width: 390,
480 height: 844,
481 });
482 expect(await snapshotSize()).toEqual({ width: 585, height: 1266 });
483 } finally {
484 await browser.close();
485 }
486});