Skip to content

Commit 4dd8a2b

Browse files
authored
improve(browser): batch navigation guard, snapshot delta markers, tool output schema, code-mode recipe (#113749)
* feat(browser): guard batches and annotate snapshot deltas * docs(browser): document reliable automation loops * test(browser): align batch guard mocks * fix(browser): reset snapshot deltas after navigation * fix(browser): detect document navigation without URL equality * fix(browser): require stable identity for snapshot deltas * fix(browser): keep snapshot delta helper private
1 parent 0ff2c82 commit 4dd8a2b

34 files changed

Lines changed: 1197 additions & 68 deletions

‎docs/tools/browser-control.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,13 +328,24 @@ OpenClaw supports two "snapshot" styles:
328328
- If Playwright is unavailable, ARIA snapshots can still be useful for
329329
inspection, but refs may not be actionable. Re-snapshot with `--format ai`
330330
or `--interactive` when you need action refs.
331+
- When the driver exposes stable document identity, consecutive AI and role
332+
snapshots for the same profile, tab, document, and option family append
333+
`[new]` to ref-bearing lines absent from the previous snapshot. Navigation
334+
starts a fresh unmarked baseline; existing-session snapshots omit deltas.
335+
The first snapshot establishes the baseline without markers; later responses
336+
also expose `newElements`, and add a count footer when the value is nonzero.
337+
Structured `--format aria` snapshots with `axN` refs do not use delta markers.
331338
- Docker proof for the raw-CDP fallback path: `pnpm test:docker:browser-cdp-snapshot`
332339
starts Chromium with CDP, runs `browser doctor --deep`, and verifies role
333340
snapshots include link URLs, cursor-promoted clickables, and iframe metadata.
334341
335342
Ref behavior:
336343
337344
- Refs are **not stable across navigations**; if something fails, re-run `snapshot` and use a fresh ref.
345+
- A batch stops after a committed main-frame navigation—including a same-URL
346+
reload—or after the page closes. Its `aborted` summary reports the action
347+
number and skipped count; take a fresh snapshot before issuing dependent
348+
actions, or use separate act calls when navigation is expected.
338349
- `/act` returns the current raw `targetId` after action-triggered replacement
339350
when it can prove the replacement tab. Keep using stable tab ids/labels for
340351
follow-up commands.

‎docs/tools/browser.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,11 @@ extraction mode when a caller does not pass an explicit `snapshotFormat` or
197197
`mode`; see [Browser control API](/tools/browser-control) for per-call
198198
snapshot options.
199199

200+
On drivers with stable document identity, repeated AI or role snapshots of the
201+
same tab, document, and option family mark newly appeared ref-bearing elements
202+
with `[new]`. The first snapshot—and the first snapshot after navigation—sets
203+
an unmarked baseline. Existing-session snapshots omit deltas.
204+
200205
### Tab cleanup ownership
201206

202207
Session tab cleanup applies only to tabs created by the OpenClaw browser tool

‎extensions/browser/skills/browser-automation/SKILL.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,44 @@ Use this skill when you need the `browser` tool for anything beyond a single pag
4343
- Target id: nested actions share the request's tab; an explicit nested `targetId` that resolves to a different tab is rejected with `ACT_TARGET_ID_MISMATCH`.
4444
- Response: `{ "results": [{ "ok": true } | { "ok": false, "error": "..." }, ...] }` in order; with default `stopOnError` the array ends at the first failure. Any failed entry exits nonzero; use `--json` to preserve the full response in scripts.
4545

46+
## Code Mode Loop
47+
48+
When `tools.codeMode` is enabled, call the Browser tool from exec cells:
49+
50+
```javascript
51+
const browserTool = "openclaw:browser:browser";
52+
let previousSnapshot = "";
53+
const callBrowser = async (input) => await tools.call(browserTool, input);
54+
```
55+
56+
Keep the same labeled tab through the loop, and alternate reads with actions:
57+
58+
```javascript
59+
const snapshotCall = await callBrowser({
60+
action: "snapshot",
61+
targetId: "task",
62+
refs: "aria",
63+
interactive: true,
64+
});
65+
const details = snapshotCall?.result?.details ?? {};
66+
const snapshot = (snapshotCall?.result?.content ?? []).map((block) => block?.text ?? "").join("\n");
67+
const relevant = snapshot
68+
.split("\n")
69+
.filter((line) => /submit|dialog|error|\[new\]/i.test(line))
70+
.slice(0, 12);
71+
const changed = snapshot !== previousSnapshot;
72+
previousSnapshot = snapshot;
73+
return { targetId: details.targetId, url: details.url, relevant, changed };
74+
```
75+
76+
- Request interactive-only snapshots and filter them in code before returning.
77+
- Return only the handful of relevant elements; never return the full tree.
78+
- Keep `previousSnapshot` between cells when a local diff helps explain a change.
79+
- Interleave each act with a URL or tabs check before the next dependent act.
80+
- If a batch returns `aborted`, take a fresh snapshot before continuing.
81+
- If `[new]` markers appear, inspect those elements first, then update the saved snapshot.
82+
- Use separate act calls when navigation is expected between steps.
83+
4684
## Tab Hygiene
4785
4886
Before creating a tab for a named task, list tabs and reuse an existing matching label or URL when it is still usable.

‎extensions/browser/src/browser-tool-description.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export function describeBrowserTool(opts: {
1313
"When using refs from snapshot (e.g. e12), keep the same tab: prefer passing targetId from the snapshot response into subsequent actions (act/click/type/etc). For tab operations, targetId also accepts tabId handles (t1) and labels from action=tabs.",
1414
"For multi-step browser work, login checks, stale refs, duplicate tabs, or Google Meet flows, use the bundled browser-automation skill when it is available.",
1515
'For stable, self-resolving refs across calls, use snapshot with refs="aria" (Playwright aria-ref ids). Default refs="role" are role+name-based.',
16+
"Repeated compatible snapshots with stable document identity mark newly appeared ref-bearing elements with [new].",
1617
"Use snapshot+act for UI automation. Avoid act:wait by default; use only in exceptional cases when no reliable UI state exists.",
1718
"For file chooser uploads, pass the trigger ref with paths in the same upload call when available; use paths-only arming only when a later trigger is intentional. Use inputRef or element to set a file input directly.",
1819
`target selects browser location (sandbox|host|node). Default: ${opts.targetDefault}.`,

‎extensions/browser/src/browser-tool.actions.ts‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,7 @@ export async function executeSnapshotAction(params: {
459459
targetId: snapshot.targetId,
460460
url: snapshot.url,
461461
truncated: snapshot.truncated,
462+
newElements: snapshot.newElements,
462463
stats: snapshot.stats,
463464
refs: snapshot.refs ? Object.keys(snapshot.refs).length : undefined,
464465
labels: snapshot.labels,
@@ -646,7 +647,7 @@ export async function executeActAction(params: {
646647
readStringValue((result as { targetId?: unknown }).targetId) ??
647648
readStringValue(effectiveRequest.targetId),
648649
);
649-
return jsonResult(result);
650+
return formatActToolResult(result);
650651
} catch (err) {
651652
if (isChromeStaleTargetError(profile, err)) {
652653
const tabs = proxyRequest
@@ -688,7 +689,7 @@ export async function executeActAction(params: {
688689
readStringValue((retryResult as { targetId?: unknown }).targetId) ??
689690
readStringValue(retryRequest.targetId),
690691
);
691-
return jsonResult(retryResult);
692+
return formatActToolResult(retryResult);
692693
}
693694
if (!tabs.length) {
694695
throw new Error(
@@ -704,3 +705,37 @@ export async function executeActAction(params: {
704705
throw err;
705706
}
706707
}
708+
709+
function formatActToolResult(result: unknown): AgentToolResult<unknown> {
710+
const formatted = jsonResult(result);
711+
if (!result || typeof result !== "object") {
712+
return formatted;
713+
}
714+
const aborted = (result as { aborted?: unknown }).aborted;
715+
if (!aborted || typeof aborted !== "object") {
716+
return formatted;
717+
}
718+
const summary = aborted as {
719+
reason?: unknown;
720+
afterAction?: unknown;
721+
url?: unknown;
722+
skipped?: unknown;
723+
};
724+
if (
725+
(summary.reason !== "navigation" && summary.reason !== "closed") ||
726+
typeof summary.afterAction !== "number" ||
727+
typeof summary.url !== "string" ||
728+
typeof summary.skipped !== "number"
729+
) {
730+
return formatted;
731+
}
732+
const reason =
733+
summary.reason === "navigation"
734+
? `the page navigated to ${summary.url}`
735+
: "the page or browser context closed";
736+
const note = `Batch aborted after action ${summary.afterAction} because ${reason}; ${summary.skipped} remaining action(s) skipped. Take a new snapshot before continuing.`;
737+
return {
738+
...formatted,
739+
content: [...formatted.content, { type: "text", text: note }],
740+
};
741+
}

‎extensions/browser/src/browser-tool.runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export {
3333
normalizeOptionalString,
3434
readStringValue,
3535
} from "openclaw/plugin-sdk/string-coerce-runtime";
36-
export { BrowserToolSchema } from "./browser-tool.schema.js";
36+
export { BrowserToolOutputSchema, BrowserToolSchema } from "./browser-tool.schema.js";
3737
export {
3838
browserAct,
3939
browserArmDialog,

‎extensions/browser/src/browser-tool.schema.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,3 +177,78 @@ export const BrowserToolSchema = Type.Object({
177177
fn: Type.Optional(Type.String()),
178178
request: Type.Optional(BrowserActSchema),
179179
});
180+
181+
const BrowserSnapshotStatsSchema = Type.Object(
182+
{
183+
lines: Type.Number(),
184+
chars: Type.Number(),
185+
refs: Type.Number(),
186+
interactive: Type.Number(),
187+
},
188+
{ additionalProperties: false },
189+
);
190+
191+
const BrowserBatchAbortSchema = Type.Object(
192+
{
193+
reason: stringEnum(["navigation", "closed"] as const),
194+
afterAction: Type.Number(),
195+
url: Type.String(),
196+
skipped: Type.Number(),
197+
},
198+
{ additionalProperties: false },
199+
);
200+
201+
/** Common structured result fields returned across Browser tool actions. */
202+
export const BrowserToolOutputSchema = Type.Object(
203+
{
204+
ok: Type.Optional(Type.Boolean()),
205+
targetId: Type.Optional(Type.String()),
206+
url: Type.Optional(Type.String()),
207+
format: Type.Optional(stringEnum(BROWSER_SNAPSHOT_FORMATS)),
208+
snapshot: Type.Optional(Type.String()),
209+
refs: Type.Optional(Type.Union([Type.Number(), Type.Record(Type.String(), Type.Unknown())])),
210+
stats: Type.Optional(BrowserSnapshotStatsSchema),
211+
truncated: Type.Optional(Type.Boolean()),
212+
newElements: Type.Optional(Type.Number()),
213+
tabs: Type.Optional(
214+
Type.Array(
215+
Type.Object(
216+
{
217+
suggestedTargetId: Type.Optional(Type.String()),
218+
tabId: Type.Optional(Type.String()),
219+
label: Type.Optional(Type.String()),
220+
targetId: Type.Optional(Type.String()),
221+
title: Type.Optional(Type.String()),
222+
url: Type.Optional(Type.String()),
223+
type: Type.Optional(Type.String()),
224+
},
225+
{ additionalProperties: true },
226+
),
227+
),
228+
),
229+
tabCount: Type.Optional(Type.Number()),
230+
results: Type.Optional(
231+
Type.Array(
232+
Type.Object(
233+
{
234+
ok: Type.Boolean(),
235+
error: Type.Optional(Type.String()),
236+
navigated: Type.Optional(Type.Literal(true)),
237+
url: Type.Optional(Type.String()),
238+
},
239+
{ additionalProperties: false },
240+
),
241+
),
242+
),
243+
aborted: Type.Optional(BrowserBatchAbortSchema),
244+
enabled: Type.Optional(Type.Boolean()),
245+
running: Type.Optional(Type.Boolean()),
246+
profile: Type.Optional(Type.String()),
247+
driver: Type.Optional(Type.String()),
248+
transport: Type.Optional(Type.String()),
249+
pid: Type.Optional(Type.Union([Type.Number(), Type.Null()])),
250+
cdpPort: Type.Optional(Type.Union([Type.Number(), Type.Null()])),
251+
cdpUrl: Type.Optional(Type.Union([Type.String(), Type.Null()])),
252+
},
253+
{ additionalProperties: true },
254+
);

‎extensions/browser/src/browser-tool.test.ts‎

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Browser tests cover browser tool plugin behavior.
2+
import { Value } from "typebox/value";
23
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
34

45
const browserClientMocks = vi.hoisted(() => ({
@@ -55,7 +56,7 @@ const browserClientMocks = vi.hoisted(() => ({
5556
vi.mock("./browser/client.js", () => browserClientMocks);
5657

5758
const browserActionsMocks = vi.hoisted(() => ({
58-
browserAct: vi.fn(async () => ({ ok: true })),
59+
browserAct: vi.fn(async (): Promise<Record<string, unknown>> => ({ ok: true })),
5960
browserArmDialog: vi.fn(async () => ({ ok: true })),
6061
browserArmFileChooser: vi.fn(async () => ({ ok: true })),
6162
browserConsoleMessages: vi.fn(async () => ({
@@ -213,7 +214,10 @@ vi.mock("./sdk-setup-tools.js", async () => {
213214
};
214215
});
215216

216-
vi.mock("./browser-tool.runtime.js", () => {
217+
vi.mock("./browser-tool.runtime.js", async () => {
218+
const { BrowserToolOutputSchema } = await vi.importActual<
219+
typeof import("./browser-tool.schema.js")
220+
>("./browser-tool.schema.js");
217221
const readStringValue = (value: unknown) => (typeof value === "string" ? value : undefined);
218222
const readStringParam = (
219223
params: Record<string, unknown>,
@@ -233,6 +237,7 @@ vi.mock("./browser-tool.runtime.js", () => {
233237
return {
234238
DEFAULT_AI_SNAPSHOT_MAX_CHARS: 40_000,
235239
DEFAULT_UPLOAD_DIR: "/tmp/openclaw-browser-uploads",
240+
BrowserToolOutputSchema,
236241
BrowserToolSchema: {},
237242
...browserActionsMocks,
238243
...browserClientMocks,
@@ -487,6 +492,20 @@ function lastNodeInvokeCall(): ReturnType<typeof nodeInvokeCall> {
487492
return nodeInvokeCall(-1);
488493
}
489494

495+
describe("browser tool output schema", () => {
496+
it("accepts snapshot details", async () => {
497+
const tool = createBrowserTool();
498+
const result = await tool.execute?.("call-1", {
499+
action: "snapshot",
500+
target: "host",
501+
snapshotFormat: "ai",
502+
});
503+
504+
expect(tool.outputSchema).toBeDefined();
505+
expect(Value.Check(tool.outputSchema!, result?.details)).toBe(true);
506+
});
507+
});
508+
490509
describe("browser tool description", () => {
491510
it("warns agents about existing-session act timeout limits", () => {
492511
const tool = createBrowserTool();
@@ -2257,6 +2276,39 @@ describe("browser tool url alias support", () => {
22572276
describe("browser tool act compatibility", () => {
22582277
registerBrowserToolAfterEachReset();
22592278

2279+
it("adds a clear note when a batch aborts after navigation", async () => {
2280+
browserActionsMocks.browserAct.mockResolvedValueOnce({
2281+
ok: true,
2282+
results: [{ ok: true, navigated: true, url: "https://example.com/next" }],
2283+
aborted: {
2284+
reason: "navigation",
2285+
afterAction: 1,
2286+
url: "https://example.com/next",
2287+
skipped: 2,
2288+
},
2289+
});
2290+
const tool = createBrowserTool();
2291+
2292+
const result = await tool.execute?.("call-1", {
2293+
action: "act",
2294+
request: {
2295+
kind: "batch",
2296+
actions: [
2297+
{ kind: "click", ref: "1" },
2298+
{ kind: "click", ref: "2" },
2299+
],
2300+
},
2301+
});
2302+
2303+
expect(result?.details).toMatchObject({ aborted: { reason: "navigation", skipped: 2 } });
2304+
expect(result?.content.at(-1)).toMatchObject({
2305+
type: "text",
2306+
text: expect.stringContaining(
2307+
"Batch aborted after action 1 because the page navigated to https://example.com/next",
2308+
),
2309+
});
2310+
});
2311+
22602312
it("accepts flattened act params for backward compatibility", async () => {
22612313
const tool = createBrowserTool();
22622314
await tool.execute?.("call-1", {

‎extensions/browser/src/browser-tool.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
import {
2222
type AnyAgentTool,
2323
type NodeListNode,
24+
BrowserToolOutputSchema,
2425
BrowserToolSchema,
2526
browserAct,
2627
browserArmDialog,
@@ -418,6 +419,7 @@ export function createBrowserTool(opts?: {
418419
name: "browser",
419420
description: describeBrowserTool({ targetDefault, hostHint }),
420421
parameters: BrowserToolSchema,
422+
outputSchema: BrowserToolOutputSchema,
421423
execute: async (_toolCallId, args) => {
422424
const bindingResult =
423425
opts?.runToolBinding === undefined

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
// Browser tests cover CDP committed page-session URL observation.
22
import { describe, expect, it } from "vitest";
3-
import { prepareCdpTargetSession } from "./cdp-page-session.js";
3+
import { prepareCdpTargetSession, readCdpMainFrameDocumentIdentity } from "./cdp-page-session.js";
44
import type { CdpSendFn } from "./cdp.helpers.js";
55

66
describe("prepareCdpTargetSession", () => {
7+
it("reads the main-frame loader identity", async () => {
8+
const send: CdpSendFn = async (method) =>
9+
method === "Page.getFrameTree"
10+
? { frameTree: { frame: { loaderId: "LOADER_SAME_URL" } } }
11+
: {};
12+
13+
await expect(readCdpMainFrameDocumentIdentity(send)).resolves.toBe("cdp:LOADER_SAME_URL");
14+
});
15+
716
it("ignores Chrome's transient colon URL while navigation is settling", async () => {
817
let frameReadCount = 0;
918
const send: CdpSendFn = async (method) => {

0 commit comments

Comments
 (0)