Skip to content

Commit 68d221c

Browse files
steipetegaoanze
andcommitted
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]>
1 parent 135ff63 commit 68d221c

5 files changed

Lines changed: 84 additions & 30 deletions

File tree

‎docs/tools/browser-control.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ 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 `(empty)` immediately instead of waiting for the snapshot timeout. Use `openclaw browser wait "<selector>"` when the page is expected to add the element later.
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.
314314
- `--selector` does not change the behavior of page-wide or frame-scoped transport failures; those still use the configured snapshot timeout and diagnostics.
315315
- With Playwright, `--labels` adds a screenshot with overlayed ref labels
316316
(prints `MEDIA:<path>`) plus an `annotations` array with each ref's bounding

‎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: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,61 @@ describe("pw-tools-core aria snapshot storage", () => {
280280
expect(page.evaluate).toHaveBeenCalledOnce();
281281
});
282282

283+
it("times out a stalled selector probe without publishing late refs", async () => {
284+
const mod = await import("./pw-tools-core.snapshot.js");
285+
const pendingCount = Promise.withResolvers<number>();
286+
const ariaSnapshot = vi.fn(async () => '- button "Late"');
287+
const page = {
288+
...makeAriaSnapshotPage(ariaSnapshot),
289+
locator: vi.fn(() => ({ count: () => pendingCount.promise, ariaSnapshot })),
290+
};
291+
getPageForTargetId.mockResolvedValue(page);
292+
vi.useFakeTimers();
293+
try {
294+
const promise = mod.snapshotRoleViaPlaywright({
295+
cdpUrl: "http://127.0.0.1:9222",
296+
targetId: "tab-1",
297+
selector: "#present",
298+
timeoutMs: 750,
299+
});
300+
const rejected = expect(promise).rejects.toThrow(/timed out/);
301+
await vi.advanceTimersByTimeAsync(750);
302+
await rejected;
303+
pendingCount.resolve(1);
304+
await vi.advanceTimersByTimeAsync(0);
305+
expect(ariaSnapshot).not.toHaveBeenCalled();
306+
expect(storeRoleRefsForTarget).not.toHaveBeenCalled();
307+
expect(page.off).toHaveBeenCalledTimes(2);
308+
} finally {
309+
vi.useRealTimers();
310+
}
311+
});
312+
313+
it("shares the capture timeout between selector lookup and snapshot", async () => {
314+
const mod = await import("./pw-tools-core.snapshot.js");
315+
const pendingCount = Promise.withResolvers<number>();
316+
const ariaSnapshot = vi.fn(async () => '- button "Present"');
317+
getPageForTargetId.mockResolvedValue({
318+
...makeAriaSnapshotPage(ariaSnapshot),
319+
locator: () => ({ count: () => pendingCount.promise, ariaSnapshot }),
320+
});
321+
vi.useFakeTimers();
322+
try {
323+
const promise = mod.snapshotRoleViaPlaywright({
324+
cdpUrl: "http://127.0.0.1:9222",
325+
targetId: "tab-1",
326+
selector: "#present",
327+
timeoutMs: 750,
328+
});
329+
await vi.advanceTimersByTimeAsync(500);
330+
pendingCount.resolve(1);
331+
await promise;
332+
expect(ariaSnapshot).toHaveBeenCalledWith({ timeout: 250 });
333+
} finally {
334+
vi.useRealTimers();
335+
}
336+
});
337+
283338
it("stores frame-scoped refs with the exact captured frame", async () => {
284339
const ariaSnapshot = vi.fn(async () => '- button "Save"');
285340
const frame = { id: "frame-1", locator: vi.fn(() => ({ ariaSnapshot })) };

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

Lines changed: 17 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,16 +429,20 @@ 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 selectorMatched = !selector || (await locator.count()) > 0;
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;
455439
const ariaSnapshot = selectorMatched
456-
? await locator.ariaSnapshot({ timeout: ariaSnapshotTimeout })
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+
})
457446
: "";
458447
const built = buildRoleSnapshotFromAriaSnapshot(ariaSnapshot ?? "", opts.options);
459448
return await finalizeRoleSnapshotViaPlaywright({

0 commit comments

Comments
 (0)