Skip to content

Commit 6b68a4a

Browse files
gaoanze888gaoanzesteipete
authored
fix(browser): return selector no-match snapshots promptly (#131441)
* fix(browser): return selector no-match snapshots promptly * docs(browser): define selector snapshot semantics * fix(browser): keep selector misses empty * fix(browser): preserve URLs for ref-free snapshots * test(browser): prove selector URL boundaries in Chromium * fix(browser): keep empty selector snapshots bounded and visible Return no-match snapshots promptly while retaining URLs for matched ref-free results. Share the selector lookup and capture deadline, retire stale refs through the existing snapshot owner, and preserve compact empty output. Reuse the shared raw-ARIA timeout helper and consolidate page/frame locator construction. Co-authored-by: gaoanze <[email protected]> * test(browser): align snapshot regression checks with CI Reuse the existing typed deferred helper and reduce the assertion allowance after removing the duplicate raw-ARIA cast. Co-authored-by: gaoanze <[email protected]> --------- Co-authored-by: gaoanze <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent bf58d2a commit 6b68a4a

7 files changed

Lines changed: 209 additions & 30 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ extensions/browser/src/browser/pw-tools-core.interactions.actions.ts 2
9292
extensions/browser/src/browser/pw-tools-core.interactions.content.ts 1
9393
extensions/browser/src/browser/pw-tools-core.interactions.execution.ts 4
9494
extensions/browser/src/browser/pw-tools-core.interactions.navigation.ts 3
95-
extensions/browser/src/browser/pw-tools-core.snapshot.ts 2
95+
extensions/browser/src/browser/pw-tools-core.snapshot.ts 1
9696
extensions/browser/src/browser/pw-tools-core.state.ts 3
9797
extensions/browser/src/browser/routes/agent.act.normalize.ts 2
9898
extensions/browser/src/browser/routes/agent.act.shared.ts 3

‎docs/tools/browser-control.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,8 @@ Snapshot flags at a glance:
310310
- `--format aria`: accessibility tree with `axN` refs. When Playwright is available, OpenClaw binds refs with backend DOM ids to the live page so follow-up actions can use them; otherwise treat the output as inspection-only.
311311
- `--efficient` (or `--mode efficient`): compact role snapshot preset. Set `browser.snapshotDefaults.mode: "efficient"` to make this the default (see [Gateway configuration](/gateway/configuration-reference#browser)).
312312
- `--interactive`, `--compact`, `--depth`, `--selector` force a role snapshot with `ref=e12` refs. `--frame "<iframe>"` scopes role snapshots to an iframe.
313+
- A selector-scoped snapshot is a point-in-time observation: if no element matches when the snapshot is requested, it returns an empty snapshot immediately instead of waiting for the snapshot timeout. Use `openclaw browser wait "<selector>"` when the page is expected to add the element later.
314+
- `--selector` does not change the behavior of page-wide or frame-scoped transport failures; those still use the configured snapshot timeout and diagnostics.
313315
- With Playwright, `--labels` adds a screenshot with overlayed ref labels
314316
(prints `MEDIA:<path>`) plus an `annotations` array with each ref's bounding
315317
box. On `screenshot`, Playwright-backed labels work with `--full-page`,

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

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,63 @@ const tempDirs = useAutoCleanupTempDirTracker(afterEach);
2222
describe.runIf(process.env.OPENCLAW_BROWSER_SNAPSHOT_E2E === "1")(
2323
"Chromium snapshot-to-action name fidelity",
2424
() => {
25+
it("returns selector no-match snapshots without waiting for the snapshot timeout", async () => {
26+
const rootDir = tempDirs.make("openclaw-snapshot-selector-absence-");
27+
const port = await getFreePort();
28+
const cdpUrl = `http://127.0.0.1:${port}`;
29+
const context = await getPlaywrightCore().chromium.launchPersistentContext(
30+
path.join(rootDir, "profile"),
31+
{
32+
headless: true,
33+
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
34+
args: [`--remote-debugging-port=${port}`],
35+
},
36+
);
37+
try {
38+
const page = context.pages()[0] ?? (await context.newPage());
39+
await page.setContent(
40+
'<main><button id="present">Present</button><a href="https://example.test/docs">Docs</a></main>',
41+
);
42+
const session = await context.newCDPSession(page);
43+
const { targetInfo } = await session.send("Target.getTargetInfo");
44+
await session.detach();
45+
const target = { cdpUrl, targetId: targetInfo.targetId };
46+
47+
const startedAt = performance.now();
48+
const missing = await snapshotRoleViaPlaywright({
49+
...target,
50+
selector: "#missing",
51+
timeoutMs: 30_000,
52+
urls: true,
53+
});
54+
const elapsedMs = performance.now() - startedAt;
55+
const present = await snapshotRoleViaPlaywright({
56+
...target,
57+
selector: "#present",
58+
timeoutMs: 30_000,
59+
});
60+
61+
const refFree = await snapshotRoleViaPlaywright({
62+
...target,
63+
selector: "main",
64+
options: { maxDepth: 0 },
65+
timeoutMs: 30_000,
66+
urls: true,
67+
});
68+
69+
expect(missing.snapshot).toBe("(empty)");
70+
expect(missing.snapshot).not.toContain("https://example.test/docs");
71+
expect(missing.refs).toEqual({});
72+
expect(elapsedMs).toBeLessThan(1_000);
73+
expect(present.snapshot).toContain('button "Present"');
74+
expect(refFree.refs).toEqual({});
75+
expect(refFree.snapshot).toContain("https://example.test/docs");
76+
} finally {
77+
await closePlaywrightBrowserConnection({ cdpUrl });
78+
await context.close();
79+
}
80+
}, 30_000);
81+
2582
it("resolves encoded and omitted names, raw AX names, and native frame refs", async () => {
2683
const rootDir = tempDirs.make("openclaw-snapshot-labels-");
2784
const port = await getFreePort();

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,15 @@ describe("pw-role-snapshot", () => {
104104
expect(result.refs).toEqual({ f1e1: { role: "button", name: "Real" } });
105105
});
106106

107+
it.each([
108+
["role", buildRoleSnapshotFromAriaSnapshot],
109+
["AI", buildRoleSnapshotFromAiSnapshot],
110+
] as const)("keeps an explicit empty result for compact %s snapshots", (_mode, build) => {
111+
const result = build("", { compact: true });
112+
expect(result.snapshot).toBe("(empty)");
113+
expect(result.refs).toEqual({});
114+
});
115+
107116
it("adds refs for interactive elements", () => {
108117
const aria = [
109118
'- heading "Example" [level=1]',

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -332,10 +332,11 @@ function compactTree(tree: string) {
332332
finishEntry();
333333
}
334334

335-
return entries
335+
const compacted = entries
336336
.filter((entry) => entry.keep)
337337
.map((entry) => entry.line)
338338
.join("\n");
339+
return compacted || "(empty)";
339340
}
340341

341342
function processLine(

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

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Browser tests cover pw tools core.snapshot plugin behavior.
2+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
23
import { beforeEach, describe, expect, it, vi } from "vitest";
34

45
const getPageForTargetId = vi.fn();
@@ -218,6 +219,123 @@ describe("pw-tools-core aria snapshot storage", () => {
218219
expect(storeRoleRefsForTarget).not.toHaveBeenCalled();
219220
});
220221

222+
it("returns selector no-match snapshots without collecting URLs", async () => {
223+
const ariaSnapshot = vi.fn(async () => {
224+
throw new Error("ariaSnapshot should not run for a selector with no matches");
225+
});
226+
const locator = {
227+
count: vi.fn(async () => 0),
228+
ariaSnapshot,
229+
};
230+
const page = {
231+
locator: vi.fn(() => locator),
232+
mainFrame: vi.fn(() => ({ id: "main-frame" })),
233+
on: vi.fn(),
234+
off: vi.fn(),
235+
evaluate: vi.fn(async () => [{ text: "link", url: "https://example.test" }]),
236+
};
237+
getPageForTargetId.mockResolvedValue(page);
238+
239+
const mod = await import("./pw-tools-core.snapshot.js");
240+
const result = await mod.snapshotRoleViaPlaywright({
241+
cdpUrl: "http://127.0.0.1:9222",
242+
targetId: "tab-1",
243+
selector: "#missing",
244+
urls: true,
245+
});
246+
247+
expect(result.snapshot).toBe("(empty)");
248+
expect(result.snapshot).not.toContain("Links:");
249+
expect(locator.count).toHaveBeenCalledOnce();
250+
expect(ariaSnapshot).not.toHaveBeenCalled();
251+
expect(page.evaluate).not.toHaveBeenCalled();
252+
});
253+
254+
it("keeps URLs for valid snapshots whose depth filter removes every ref", async () => {
255+
const locator = {
256+
count: vi.fn(async () => 1),
257+
ariaSnapshot: vi.fn(async () => '- main:\n - link "Docs"'),
258+
};
259+
const page = {
260+
locator: vi.fn(() => locator),
261+
mainFrame: vi.fn(() => ({ id: "main-frame" })),
262+
on: vi.fn(),
263+
off: vi.fn(),
264+
evaluate: vi.fn(async () => [{ text: "Docs", url: "https://example.test/docs" }]),
265+
};
266+
getPageForTargetId.mockResolvedValue(page);
267+
268+
const mod = await import("./pw-tools-core.snapshot.js");
269+
const result = await mod.snapshotRoleViaPlaywright({
270+
cdpUrl: "http://127.0.0.1:9222",
271+
targetId: "tab-1",
272+
selector: "main",
273+
options: { maxDepth: 0 },
274+
urls: true,
275+
});
276+
277+
expect(result.refs).toEqual({});
278+
expect(result.snapshot).toContain("- main:");
279+
expect(result.snapshot).toContain("https://example.test/docs");
280+
expect(locator.count).toHaveBeenCalledOnce();
281+
expect(page.evaluate).toHaveBeenCalledOnce();
282+
});
283+
284+
it("times out a stalled selector probe without publishing late refs", async () => {
285+
const mod = await import("./pw-tools-core.snapshot.js");
286+
const pendingCount = createDeferred<number>();
287+
const ariaSnapshot = vi.fn(async () => '- button "Late"');
288+
const page = {
289+
...makeAriaSnapshotPage(ariaSnapshot),
290+
locator: vi.fn(() => ({ count: () => pendingCount.promise, ariaSnapshot })),
291+
};
292+
getPageForTargetId.mockResolvedValue(page);
293+
vi.useFakeTimers();
294+
try {
295+
const promise = mod.snapshotRoleViaPlaywright({
296+
cdpUrl: "http://127.0.0.1:9222",
297+
targetId: "tab-1",
298+
selector: "#present",
299+
timeoutMs: 750,
300+
});
301+
const rejected = expect(promise).rejects.toThrow(/timed out/);
302+
await vi.advanceTimersByTimeAsync(750);
303+
await rejected;
304+
pendingCount.resolve(1);
305+
await vi.advanceTimersByTimeAsync(0);
306+
expect(ariaSnapshot).not.toHaveBeenCalled();
307+
expect(storeRoleRefsForTarget).not.toHaveBeenCalled();
308+
expect(page.off).toHaveBeenCalledTimes(2);
309+
} finally {
310+
vi.useRealTimers();
311+
}
312+
});
313+
314+
it("shares the capture timeout between selector lookup and snapshot", async () => {
315+
const mod = await import("./pw-tools-core.snapshot.js");
316+
const pendingCount = createDeferred<number>();
317+
const ariaSnapshot = vi.fn(async () => '- button "Present"');
318+
getPageForTargetId.mockResolvedValue({
319+
...makeAriaSnapshotPage(ariaSnapshot),
320+
locator: () => ({ count: () => pendingCount.promise, ariaSnapshot }),
321+
});
322+
vi.useFakeTimers();
323+
try {
324+
const promise = mod.snapshotRoleViaPlaywright({
325+
cdpUrl: "http://127.0.0.1:9222",
326+
targetId: "tab-1",
327+
selector: "#present",
328+
timeoutMs: 750,
329+
});
330+
await vi.advanceTimersByTimeAsync(500);
331+
pendingCount.resolve(1);
332+
await promise;
333+
expect(ariaSnapshot).toHaveBeenCalledWith({ timeout: 250 });
334+
} finally {
335+
vi.useRealTimers();
336+
}
337+
});
338+
221339
it("stores frame-scoped refs with the exact captured frame", async () => {
222340
const ariaSnapshot = vi.fn(async () => '- button "Save"');
223341
const frame = { id: "frame-1", locator: vi.fn(() => ({ ariaSnapshot })) };

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

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
normalizeLowercaseStringOrEmpty,
88
normalizeOptionalString,
99
} from "openclaw/plugin-sdk/string-coerce-runtime";
10-
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
10+
import { truncateUtf16Safe, withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
1111
import type { Frame, Page } from "playwright-core";
1212
import type { SsrFPolicy } from "../infra/net/ssrf.js";
1313
import { ACT_MAX_VIEWPORT_DIMENSION, resolveBrowserNavigationTimeoutMs } from "./act-policy.js";
@@ -218,24 +218,9 @@ export async function snapshotAriaViaPlaywright(opts: {
218218
};
219219
},
220220
});
221-
const res = (await (ariaTimeoutMs === undefined
222-
? collectAxTree
223-
: (() => {
224-
let timer: ReturnType<typeof setTimeout> | undefined;
225-
const timeout = new Promise<never>((_, reject) => {
226-
timer = setTimeout(() => {
227-
reject(new Error(`Aria snapshot via Playwright timed out after ${ariaTimeoutMs}ms.`));
228-
}, ariaTimeoutMs);
229-
timer.unref?.();
230-
});
231-
return Promise.race([collectAxTree, timeout]).finally(() => {
232-
if (timer) {
233-
clearTimeout(timer);
234-
}
235-
});
236-
})())) as {
237-
nodes?: RawAXNode[];
238-
};
221+
const res = await withTimeout(collectAxTree, ariaTimeoutMs ?? 0, {
222+
message: `Aria snapshot via Playwright timed out after ${ariaTimeoutMs}ms.`,
223+
});
239224
const nodes = Array.isArray(res?.nodes) ? res.nodes : [];
240225
const formatted = formatAriaSnapshot(nodes, limit);
241226
await storeAriaSnapshotRefsViaPlaywright({
@@ -444,14 +429,21 @@ export async function snapshotRoleViaPlaywright(opts: {
444429
page,
445430
frame: frame ?? page.mainFrame(),
446431
run: async (isFrameCurrent) => {
447-
const locator = frame
448-
? selector
449-
? frame.locator(selector)
450-
: frame.locator(":root")
451-
: selector
452-
? page.locator(selector)
453-
: page.locator(":root");
454-
const ariaSnapshot = await locator.ariaSnapshot({ timeout: ariaSnapshotTimeout });
432+
const snapshotScope = frame ?? page;
433+
const locator = snapshotScope.locator(selector || ":root");
434+
const captureDeadline = performance.now() + ariaSnapshotTimeout;
435+
// Count has no timeout; both capture stages share one budget before refs are published.
436+
const selectorMatched =
437+
!selector ||
438+
(await withTimeout(locator.count(), ariaSnapshotTimeout, "Role snapshot selector")) > 0;
439+
const ariaSnapshot = selectorMatched
440+
? await locator.ariaSnapshot({
441+
// A zero Playwright timeout disables its deadline.
442+
timeout: selector
443+
? Math.max(1, captureDeadline - performance.now())
444+
: ariaSnapshotTimeout,
445+
})
446+
: "";
455447
const built = buildRoleSnapshotFromAriaSnapshot(ariaSnapshot ?? "", opts.options);
456448
return await finalizeRoleSnapshotViaPlaywright({
457449
page,
@@ -462,7 +454,7 @@ export async function snapshotRoleViaPlaywright(opts: {
462454
isFrameCurrent,
463455
built,
464456
mode: "role",
465-
urls: opts.urls,
457+
urls: opts.urls && selectorMatched,
466458
maxChars: opts.maxChars,
467459
delta: opts.delta,
468460
});

0 commit comments

Comments
 (0)