Skip to content

Commit f04a622

Browse files
authored
fix(browser): resolve unnamed role refs and initialize AX markers (#130881)
* fix(browser): resolve unnamed role refs and initialize AX markers Keep explicit raw ARIA empty names distinct from omitted serializer names and share one dependency-faithful role lookup. Bind the DOM document in the marker-owning CDP session without adding a round trip. Related: #130879. The separate snapshot membership and ordering failures remain open. * chore(browser): shrink ref assertion safety baseline Record the five type assertions removed by the ref-name repair. Tighten the canonical per-file allowance from seven to two; runtime and browser-test bytes are unchanged.
1 parent 879ab82 commit f04a622

10 files changed

Lines changed: 125 additions & 70 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ Docs: https://docs.openclaw.ai
340340
- **Remote browser reliability:** bound persistent Playwright tab enumeration by the existing remote CDP timeout budget and retire timed-out connection attempts so late completions cannot restore a stuck connection. (#80147, #58968) Thanks @HemantSudarshan and @KeaneYan.
341341
- **Browser tab adoption:** preserve the prior implicit tab and stable aliases when new MCP, Playwright, or CDP targets fail final safety validation, abort after creation, or cannot be rediscovered; validate labels before creating tabs and limit managed cleanup to adopted targets. (#105301) Thanks @hugenshen.
342342
- **Browser snapshots:** preserve slash-only control names and keep ref-looking page text from retaining truncated refs or misplacing child frames. Fixes #130571.
343+
- **Browser refs:** keep unnamed and overlong-named controls distinct from ordinary named controls to prevent wrong-target actions, and initialize raw ARIA DOM markers in their owning CDP session.
343344
- **Browser attachment downloads:** return managed URL, filename, and path metadata when direct Playwright navigation starts an attachment download, while validating final URLs before saving bytes and preserving single-owner explicit downloads. (#48045, #89416) Thanks @zhangguiping-xydt.
344345
- **Browser action downloads:** return managed URL, filename, and path metadata when agent actions trigger downloads, while preserving explicit ownership, validating final URLs before saving bytes, and quarantining policy-denied tabs without closing them. (#93250, #93307) Thanks @sunlit-deng.
345346
- **Managed browser cookie persistence:** initialize new isolated macOS headless profiles with a non-interactive encryption key while preserving existing profile keys, and close Chromium through CDP before bounded signal fallback so persistent logins survive graceful browser and Gateway restarts. (#96704, #98284) Thanks @TurboTheTurtle.

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ extensions/browser/src/browser/paths.ts 1
8585
extensions/browser/src/browser/playwright-core.runtime.ts 2
8686
extensions/browser/src/browser/pw-download-capture.ts 1
8787
extensions/browser/src/browser/pw-role-snapshot.ts 1
88-
extensions/browser/src/browser/pw-session-actions.ts 7
88+
extensions/browser/src/browser/pw-session-actions.ts 2
8989
extensions/browser/src/browser/pw-session-cdp-transport.ts 1
9090
extensions/browser/src/browser/pw-session-navigation.ts 1
9191
extensions/browser/src/browser/pw-session.page-cdp.ts 4

‎docs/tools/browser-control.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,7 @@ OpenClaw supports three "snapshot" styles:
310310
- Actions: `openclaw browser click e12`, `openclaw browser highlight e12`.
311311
- Internally, the ref is resolved via `getByRole(...)` (plus `nth()` for duplicates).
312312
- Names containing quotes, backslashes, or YAML punctuation remain actionable; use the ref rather than reconstructing a locator from the displayed name.
313+
- A missing displayed name can mean an empty accessible name or one above Playwright's 900 UTF-16-unit limit; keep using the returned ref.
313314
- Add `--labels` to include a screenshot with overlayed `e12` labels. On
314315
Playwright-backed profiles this also returns per-ref bounding-box metadata
315316
(`annotations[]`).

‎extensions/browser/src/browser/pw-role-snapshot.chromium.test.ts‎

Lines changed: 85 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,27 @@ import path from "node:path";
22
import { afterEach, describe, expect, it } from "vitest";
33
import { useAutoCleanupTempDirTracker } from "../../test-support.js";
44
import { getPlaywrightCore } from "./playwright-core.runtime.js";
5-
import { closePlaywrightBrowserConnection } from "./pw-session.js";
5+
import {
6+
closePlaywrightBrowserConnection,
7+
refLocator,
8+
restoreRoleRefsForTarget,
9+
} from "./pw-session.js";
10+
import { BROWSER_REF_MARKER_ATTRIBUTE } from "./pw-session.page-cdp.js";
611
import { clickViaPlaywright, typeViaPlaywright } from "./pw-tools-core.interactions.actions.js";
7-
import { snapshotAiViaPlaywright, snapshotRoleViaPlaywright } from "./pw-tools-core.snapshot.js";
12+
import {
13+
snapshotAiViaPlaywright,
14+
snapshotAriaViaPlaywright,
15+
snapshotRoleViaPlaywright,
16+
storeAriaSnapshotRefsViaPlaywright,
17+
} from "./pw-tools-core.snapshot.js";
818
import { getFreePort } from "./test-port.js";
919

1020
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
1121

1222
describe.runIf(process.env.OPENCLAW_BROWSER_SNAPSHOT_E2E === "1")(
1323
"Chromium snapshot-to-action name fidelity",
1424
() => {
15-
it("resolves encoded duplicate names, textboxes, and frame-qualified AI refs", async () => {
25+
it("resolves encoded and omitted names, raw AX names, and native frame refs", async () => {
1626
const rootDir = tempDirs.make("openclaw-snapshot-labels-");
1727
const port = await getFreePort();
1828
const cdpUrl = `http://127.0.0.1:${port}`;
@@ -26,11 +36,25 @@ describe.runIf(process.env.OPENCLAW_BROWSER_SNAPSHOT_E2E === "1")(
2636
);
2737
try {
2838
const page = context.pages()[0] ?? (await context.newPage());
29-
await page.setContent('<main></main><output></output><iframe title="Nested"></iframe>');
39+
await page.setContent(
40+
'<style>button{min-width:30px;min-height:25px}</style><main></main><output></output><iframe title="Nested"></iframe>',
41+
);
3042
const buttonName = 'Save: "owner\'s" C:\\draft 🦞';
3143
const inputName = 'Project "path"';
44+
const nameControls = [
45+
{ id: "short", name: "Named control" },
46+
{ id: "empty", name: "" },
47+
{ id: "empty-again", name: "" },
48+
{ id: "name-900", name: "x".repeat(900) },
49+
{ id: "name-901", name: "x".repeat(901) },
50+
{ id: "surrogates-900", name: "😀".repeat(450) },
51+
{ id: "surrogates-901", name: "😀".repeat(450) + "x" },
52+
{ id: "normalized-empty", name: "\u200b\u00ad" },
53+
{ id: "normalized-899", name: " x \n".repeat(450) },
54+
{ id: "normalized-901", name: " x \n".repeat(451) },
55+
];
3256
await page.evaluate(
33-
({ buttonName: label, inputName: inputLabel }) => {
57+
({ buttonName: label, inputName: inputLabel, nameControls: controls }) => {
3458
for (const id of ["first", "second"]) {
3559
const button = document.createElement("button");
3660
button.textContent = label;
@@ -48,10 +72,19 @@ describe.runIf(process.env.OPENCLAW_BROWSER_SNAPSHOT_E2E === "1")(
4872
document.querySelector("output")!.textContent = "/";
4973
});
5074
document.querySelector("main")!.append(slash);
75+
for (const { id, name } of controls) {
76+
const button = document.createElement("button");
77+
button.setAttribute("aria-label", name);
78+
button.textContent = name ? "control" : "";
79+
button.addEventListener("click", () => {
80+
document.querySelector("output")!.textContent = id;
81+
});
82+
document.querySelector("main")!.append(button);
83+
}
5184
document.querySelector("iframe")!.srcdoc =
5285
"<button onclick=\"this.textContent='Frame clicked'\">Frame: action</button>";
5386
},
54-
{ buttonName, inputName },
87+
{ buttonName, inputName, nameControls },
5588
);
5689
await page.frameLocator("iframe").getByRole("button").waitFor();
5790
const session = await context.newCDPSession(page);
@@ -68,25 +101,20 @@ describe.runIf(process.env.OPENCLAW_BROWSER_SNAPSHOT_E2E === "1")(
68101
options: { interactive: mode !== "role" },
69102
});
70103
const buttons = Object.entries(snapshot.refs).filter(
71-
([, value]) => value.role === "button" && value.name === buttonName,
104+
([, value]) => value.role === "button" && value.name !== "Frame: action",
72105
);
73-
expect(buttons, mode).toHaveLength(2);
106+
const expectedButtons = ["first", "second", "/", ...nameControls.map(({ id }) => id)];
107+
expect(buttons, mode).toHaveLength(expectedButtons.length);
74108
for (const [index, [ref]] of buttons.entries()) {
75109
await clickViaPlaywright({ ...target, ref, timeoutMs: 1_000 });
76-
expect(await page.locator("output").textContent(), mode).toBe(
77-
index ? "second" : "first",
78-
);
110+
expect(await page.locator("output").textContent(), mode).toBe(expectedButtons[index]);
79111
}
80112
const input = Object.entries(snapshot.refs).find(
81113
([, value]) => value.role === "textbox" && value.name === inputName,
82114
);
83115
expect(input, mode).toBeDefined();
84116
await typeViaPlaywright({ ...target, ref: input![0], text: mode, timeoutMs: 1_000 });
85117
expect(await page.getByRole("textbox").inputValue()).toBe(mode);
86-
const slash = Object.entries(snapshot.refs).find(([, value]) => value.name === "/");
87-
expect(slash, mode).toBeDefined();
88-
await clickViaPlaywright({ ...target, ref: slash![0], timeoutMs: 1_000 });
89-
expect(await page.locator("output").textContent(), mode).toBe("/");
90118
}
91119
const snapshot = await snapshotAiViaPlaywright(target);
92120
const nested = Object.entries(snapshot.refs).find(
@@ -97,6 +125,48 @@ describe.runIf(process.env.OPENCLAW_BROWSER_SNAPSHOT_E2E === "1")(
97125
expect(await page.frameLocator("iframe").getByRole("button").textContent()).toBe(
98126
"Frame clicked",
99127
);
128+
129+
await page.setContent(
130+
"<style>button{min-width:30px;min-height:25px}</style><main></main><output></output>",
131+
);
132+
const rawControls = [
133+
{ id: "raw-short", name: "Raw named control" },
134+
{ id: "raw-empty", name: "" },
135+
{ id: "raw-long", name: "x".repeat(901) },
136+
];
137+
await page.evaluate((controls) => {
138+
for (const { id, name } of controls) {
139+
const button = document.createElement("button");
140+
button.setAttribute("aria-label", name);
141+
button.textContent = name ? "control" : "";
142+
button.addEventListener("click", () => {
143+
document.querySelector("output")!.textContent = id;
144+
});
145+
document.querySelector("main")!.append(button);
146+
}
147+
}, rawControls);
148+
const aria = await snapshotAriaViaPlaywright(target);
149+
const rawButtons = aria.nodes.filter((node) => node.role.toLowerCase() === "button");
150+
expect(rawButtons).toHaveLength(rawControls.length);
151+
expect(
152+
await page
153+
.getByRole("button", { name: "", exact: true })
154+
.getAttribute(BROWSER_REF_MARKER_ATTRIBUTE),
155+
).toBe(rawButtons[1]!.ref);
156+
await clickViaPlaywright({ ...target, ref: rawButtons[1]!.ref, timeoutMs: 1_000 });
157+
expect(await page.locator("output").textContent()).toBe("raw-empty");
158+
// Real AX names with unavailable DOM ids exercise the existing role fallback.
159+
// Restore onto the launcher's distinct Page wrapper to cross the target cache.
160+
await storeAriaSnapshotRefsViaPlaywright({
161+
...target,
162+
nodes: aria.nodes.map(({ backendDOMNodeId: _backendId, ...node }) => node),
163+
});
164+
expect(await page.locator(`[${BROWSER_REF_MARKER_ATTRIBUTE}]`).count()).toBe(0);
165+
restoreRoleRefsForTarget({ ...target, page });
166+
for (const [index, node] of rawButtons.entries()) {
167+
await refLocator(page, node.ref).click({ timeout: 1_000 });
168+
expect(await page.locator("output").textContent()).toBe(rawControls[index]!.id);
169+
}
100170
} finally {
101171
await closePlaywrightBrowserConnection({ cdpUrl });
102172
await context.close();

‎extensions/browser/src/browser/pw-session-actions.ts‎

Lines changed: 10 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,10 @@ export function refLocator(page: Page, ref: string) {
8282
? ref.slice(4)
8383
: ref;
8484

85-
if (/^e\d+$/.test(normalized)) {
85+
const isRoleRef = /^e\d+$/.test(normalized);
86+
if (isRoleRef || AX_REF_PATTERN.test(normalized)) {
8687
const state = pageStates.get(page);
87-
if (state?.roleRefsMode === "aria") {
88+
if (isRoleRef && state?.roleRefsMode === "aria") {
8889
const scope = state.roleRefsFrame ?? page;
8990
return scope.locator(`aria-ref=${normalized}`);
9091
}
@@ -95,39 +96,15 @@ export function refLocator(page: Page, ref: string) {
9596
);
9697
}
9798
const scope = state?.roleRefsFrame ?? page;
98-
const locAny = scope as unknown as {
99-
getByRole: (
100-
role: never,
101-
opts?: { name?: string; exact?: boolean },
102-
) => ReturnType<Page["getByRole"]>;
103-
};
104-
const locator = info.name
105-
? locAny.getByRole(info.role as never, { name: info.name, exact: true })
106-
: locAny.getByRole(info.role as never);
107-
return info.nth !== undefined ? locator.nth(info.nth) : locator;
108-
}
109-
110-
if (AX_REF_PATTERN.test(normalized)) {
111-
const state = pageStates.get(page);
112-
const info = state?.roleRefs?.[normalized];
113-
if (!info) {
114-
throw new Error(
115-
`Unknown ref "${normalized}". Run a new snapshot and use a ref from that snapshot.`,
116-
);
117-
}
118-
const scope = state.roleRefsFrame ?? page;
119-
if (info.domMarker) {
99+
if (!isRoleRef && info.domMarker) {
120100
return scope.locator(`[${BROWSER_REF_MARKER_ATTRIBUTE}="${normalized}"]`);
121101
}
122-
const locAny = scope as unknown as {
123-
getByRole: (
124-
role: never,
125-
opts?: { name?: string; exact?: boolean },
126-
) => ReturnType<Page["getByRole"]>;
127-
};
128-
const locator = info.name
129-
? locAny.getByRole(info.role as never, { name: info.name, exact: true })
130-
: locAny.getByRole(info.role as never);
102+
// Playwright omits empty names and names over 900 UTF-16 units from ARIA text.
103+
// Match that exact bucket before nth; raw AX names (including "") stay explicit.
104+
const locator = scope.getByRole(info.role as never, {
105+
name: info.name ?? /^$|^.{901,}$/s,
106+
exact: true,
107+
});
131108
return info.nth !== undefined ? locator.nth(info.nth) : locator;
132109
}
133110

‎extensions/browser/src/browser/pw-session.page-cdp.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,16 @@ describe("pw-session page-scoped CDP client", () => {
5858
expect(sessionDetach).toHaveBeenCalledTimes(1);
5959
});
6060

61-
it("marks backend DOM refs on the page", async () => {
61+
it("requests the document before marking backend DOM refs on the page", async () => {
62+
let documentRequested = false;
6263
const sessionSend = vi.fn(async (method: string, params?: Record<string, unknown>) => {
64+
if (method === "DOM.getDocument") {
65+
documentRequested = true;
66+
}
6367
if (method === "DOM.pushNodesByBackendIdsToFrontend") {
68+
if (!documentRequested) {
69+
throw new Error("Document needs to be requested first");
70+
}
6471
expect(params).toEqual({ backendNodeIds: [42, 84] });
6572
return { nodeIds: [101, 202] };
6673
}
@@ -89,7 +96,8 @@ describe("pw-session page-scoped CDP client", () => {
8996

9097
expect(page.locator).toHaveBeenCalledWith(`[${BROWSER_REF_MARKER_ATTRIBUTE}]`);
9198
expect(evaluateAll).toHaveBeenCalledTimes(1);
92-
expect(sessionSend).toHaveBeenNthCalledWith(1, "DOM.enable", undefined);
99+
expect(marked).toEqual(new Set(["ax1", "ax2"]));
100+
expect(sessionSend).toHaveBeenNthCalledWith(1, "DOM.getDocument", { depth: 0 });
93101
expect(sessionSend).toHaveBeenNthCalledWith(2, "DOM.pushNodesByBackendIdsToFrontend", {
94102
backendNodeIds: [42, 84],
95103
});
@@ -103,7 +111,6 @@ describe("pw-session page-scoped CDP client", () => {
103111
name: BROWSER_REF_MARKER_ATTRIBUTE,
104112
value: "ax2",
105113
});
106-
expect(marked).toEqual(new Set(["ax1", "ax2"]));
107114
expect(sessionDetach).toHaveBeenCalledTimes(1);
108115
});
109116

‎extensions/browser/src/browser/pw-session.page-cdp.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,9 @@ export async function markBackendDomRefsOnPage(opts: {
9999
) => Promise<unknown>
100100
)(method, params);
101101

102-
await send("DOM.enable").catch(() => {});
102+
// Backend-id pushes require a bound document in this fresh session.
103+
// getDocument also enables DOM; depth zero avoids fetching the subtree.
104+
await send("DOM.getDocument", { depth: 0 }).catch(() => {});
103105

104106
const backendNodeIds = uniqueValues(refs.map((entry) => Math.floor(entry.backendDOMNodeId)));
105107
const pushed = (await send("DOM.pushNodesByBackendIdsToFrontend", {

‎extensions/browser/src/browser/pw-session.test.ts‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -123,14 +123,19 @@ describe("pw-session refLocator", () => {
123123
expect(mocks.frameLocator).not.toHaveBeenCalled();
124124
});
125125

126-
it("uses page getByRole for role refs by default", () => {
126+
it.each([
127+
{ ref: "e1", name: "OK" },
128+
{ ref: "e1", name: "" },
129+
{ ref: "ax12", name: "OK" },
130+
{ ref: "ax12", name: "" },
131+
])("matches the exact name for unmarked $ref with name '$name'", ({ ref, name }) => {
127132
const { page, mocks } = fakePage();
128133
const state = ensurePageState(page);
129-
state.roleRefs = { e1: { role: "button", name: "OK" } };
134+
state.roleRefs = { [ref]: { role: "button", name } };
130135

131-
refLocator(page, "e1");
136+
refLocator(page, ref);
132137

133-
expect(mocks.getByRole).toHaveBeenCalled();
138+
expect(mocks.getByRole).toHaveBeenCalledWith("button", { name, exact: true });
134139
});
135140

136141
it("uses aria-ref locators when refs mode is aria", () => {
@@ -153,16 +158,6 @@ describe("pw-session refLocator", () => {
153158
expect(mocks.locator).toHaveBeenCalledWith(`[${BROWSER_REF_MARKER_ATTRIBUTE}="ax12"]`);
154159
});
155160

156-
it("falls back to role heuristics for ax refs without backend markers", () => {
157-
const { page, mocks } = fakePage();
158-
const state = ensurePageState(page);
159-
state.roleRefs = { ax12: { role: "button", name: "OK" } };
160-
161-
refLocator(page, "ax12");
162-
163-
expect(mocks.getByRole).toHaveBeenCalledWith("button", { name: "OK", exact: true });
164-
});
165-
166161
it("rejects unknown ax refs instead of timing out on aria-ref locators", () => {
167162
const { page, mocks } = fakePage();
168163

‎extensions/browser/src/browser/pw-tools-core.snapshot.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,7 @@ describe("pw-tools-core aria snapshot storage", () => {
424424
nodes: [
425425
{ ref: "ax1", role: "Button", name: "OK", backendDOMNodeId: 42, depth: 0 },
426426
{ ref: "ax2", role: "Button", name: "OK", backendDOMNodeId: 84, depth: 0 },
427+
{ ref: "ax3", role: "Button", name: "", backendDOMNodeId: 126, depth: 0 },
427428
],
428429
});
429430

@@ -434,6 +435,7 @@ describe("pw-tools-core aria snapshot storage", () => {
434435
refs: {
435436
ax1: { role: "button", name: "OK" },
436437
ax2: { role: "button", name: "OK", nth: 1 },
438+
ax3: { role: "button", name: "" },
437439
},
438440
mode: "role",
439441
});

‎extensions/browser/src/browser/pw-tools-core.snapshot.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,8 @@ function buildStoredAriaRefs(
109109

110110
for (const node of nodes) {
111111
const role = normalizeLowercaseStringOrEmpty(node.role) || "unknown";
112-
const name = node.name.trim() || undefined;
113-
const key = `${role}:${name ?? ""}`;
112+
const name = node.name.trim();
113+
const key = `${role}:${name}`;
114114
const nth = counts.get(key) ?? 0;
115115
counts.set(key, nth + 1);
116116
const refsForKey = refsByKey.get(key);
@@ -121,7 +121,7 @@ function buildStoredAriaRefs(
121121
}
122122
refs[node.ref] = {
123123
role,
124-
...(name ? { name } : {}),
124+
name,
125125
...(nth > 0 ? { nth } : {}),
126126
...(markedRefs.has(node.ref) ? { domMarker: true } : {}),
127127
};

0 commit comments

Comments
 (0)