Skip to content

Commit 90969ff

Browse files
authored
fix: keep browser and Canvas tool results bounded and actionable (#125126)
* fix: bound browser and Canvas tool results * fix: type host profile availability result * fix: reuse Canvas snapshot format normalizer * fix: preserve large Canvas snapshots * fix(browser): bound captured network text * fix: close tool result limit gaps * fix: finalize tool result lifecycle bounds * fix(canvas): narrow snapshot cleanup errors * fix(canvas): bound final eval output * fix: cap sanitized tool results
1 parent 0bc877e commit 90969ff

16 files changed

Lines changed: 754 additions & 182 deletions

‎extensions/browser/src/browser-node-proxy.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,20 @@ describe("Browser node proxy nested watchdogs", () => {
161161
);
162162
});
163163

164+
it("names the selected node and host-status recovery for an invalid proxy envelope", async () => {
165+
runtimeMocks.callGatewayTool.mockResolvedValueOnce({
166+
payload: {},
167+
} as unknown as BrowserNodeResponse);
168+
const proxy = createBrowserNodeProxyRequest({
169+
nodeTarget: { nodeId: "node-1", label: "Studio Node" },
170+
allowAutomaticHostFallback: false,
171+
});
172+
173+
await expect(proxy({ method: "GET", path: "/snapshot" })).rejects.toThrow(
174+
/Studio Node.*action=status.*target="host"/i,
175+
);
176+
});
177+
164178
it("sends Gateway-owned upload bytes without node-facing source paths", async () => {
165179
const originalBody = {
166180
paths: ["/tmp/openclaw/uploads/report.txt"],

‎extensions/browser/src/browser-node-proxy.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
resolveTimerTimeoutMs,
66
} from "openclaw/plugin-sdk/number-runtime";
77
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
8+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
89
import {
910
BROWSER_PROXY_COMMAND,
1011
BROWSER_PROXY_UPLOAD_COMMAND,
@@ -70,6 +71,7 @@ function unwrapBrowserProxyPayload(
7071

7172
async function callBrowserProxy(params: {
7273
nodeId: string;
74+
nodeLabel?: string;
7375
declaredCommands: readonly string[];
7476
pendingDeclaredCommands: readonly string[];
7577
allowAutomaticHostFallback: boolean;
@@ -149,7 +151,10 @@ async function callBrowserProxy(params: {
149151
throw new BrowserServiceError(body.error, "reason" in body ? body : undefined, status);
150152
}
151153
if (!parsed || typeof parsed !== "object" || !("result" in parsed)) {
152-
throw new Error("browser proxy failed");
154+
const selectedNode = truncateUtf16Safe(params.nodeLabel?.trim() || params.nodeId, 256);
155+
throw new Error(
156+
`Browser proxy returned an invalid response from node ${JSON.stringify(selectedNode)}. Retry with action=status target="host" to check Gateway host browser control.`,
157+
);
153158
}
154159
return parsed;
155160
}
@@ -196,6 +201,7 @@ export function createBrowserNodeProxyRequest(params: {
196201
try {
197202
const proxy = await callBrowserProxy({
198203
nodeId: params.nodeTarget.nodeId,
204+
nodeLabel: params.nodeTarget.label,
199205
declaredCommands: params.nodeTarget.commands ?? [],
200206
pendingDeclaredCommands: params.nodeTarget.pendingDeclaredCommands ?? [],
201207
allowAutomaticHostFallback: params.allowAutomaticHostFallback,

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

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
DEFAULT_BROWSER_ACTION_TIMEOUT_MS,
3939
DEFAULT_BROWSER_DOWNLOAD_TIMEOUT_MS,
4040
} from "./browser/constants.js";
41+
import { formatErrorMessage } from "./infra/errors.js";
4142

4243
const browserToolActionDeps = {
4344
browserAct,
@@ -496,18 +497,20 @@ export async function executeActAction(params: {
496497
);
497498
} catch (err) {
498499
if (isChromeStaleTargetError(profile, err)) {
500+
let tabRefreshError: unknown;
499501
const tabs = proxyRequest
500-
? ((
501-
(await proxyRequest({
502-
method: "GET",
503-
path: "/tabs",
504-
profile,
505-
})) as { tabs?: unknown[] }
506-
).tabs ?? [])
502+
? await proxyRequest({ method: "GET", path: "/tabs", profile })
503+
.then((result) => (result as { tabs?: unknown[] }).tabs ?? [])
504+
.catch((refreshError: unknown) => {
505+
params.signal?.throwIfAborted();
506+
tabRefreshError = refreshError;
507+
return [];
508+
})
507509
: await browserToolActionDeps
508510
.browserTabs(baseUrl, { profile, signal: params.signal })
509-
.catch(() => {
511+
.catch((refreshError: unknown) => {
510512
params.signal?.throwIfAborted();
513+
tabRefreshError = refreshError;
511514
return [];
512515
});
513516
const freshTargetId =
@@ -543,6 +546,12 @@ export async function executeActAction(params: {
543546
readStringValue(retryRequest.targetId),
544547
);
545548
}
549+
if (tabRefreshError) {
550+
throw new Error(
551+
`Chrome tab not found for profile="${profile}", and refreshing tabs failed: ${formatErrorMessage(tabRefreshError)}. Run action=tabs profile="${profile}" and retry with a returned targetId.`,
552+
{ cause: err },
553+
);
554+
}
546555
if (!tabs.length) {
547556
throw new Error(
548557
`No browser tabs found for profile="${profile}". Make sure the configured Chromium-based browser (v144+) is running and has open tabs, then retry.`,

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

Lines changed: 68 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import {
1010
readNonNegativeIntegerParam,
1111
readPositiveIntegerParam,
1212
} from "openclaw/plugin-sdk/param-readers";
13+
import { truncateSanitizedExternalContent } from "openclaw/plugin-sdk/security-runtime";
14+
import { DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS } from "openclaw/plugin-sdk/text-utility-runtime";
1315
import {
1416
DEFAULT_AI_SNAPSHOT_MAX_CHARS,
1517
browserSnapshot,
@@ -24,6 +26,53 @@ import { DEFAULT_BROWSER_SNAPSHOT_TIMEOUT_MS } from "./browser/constants.js";
2426
import { neutralizeMediaDirectives } from "./browser/vision.js";
2527
import { formatErrorMessage } from "./infra/errors.js";
2628

29+
type BrowserExternalJsonKind = "snapshot" | "console" | "tabs" | "act" | "download";
30+
31+
const BROWSER_EXTERNAL_JSON_TRUNCATION_MARKERS = {
32+
snapshot: "\n[truncated — retry with a smaller maxChars or limit]",
33+
console: "\n[truncated — retry with a stricter level or targetId]",
34+
tabs: "\n[truncated — retry with action=snapshot and a specific targetId]",
35+
act: "\n[truncated — inspect the affected targetId with action=snapshot]",
36+
download: "\n[truncated — retry with a specific targetId and download ref]",
37+
} satisfies Record<BrowserExternalJsonKind, string>;
38+
39+
function truncateBrowserToolText(value: string, marker: string, maxChars: number) {
40+
const bounded = truncateSanitizedExternalContent(value, maxChars);
41+
if (!bounded.truncated) {
42+
return bounded;
43+
}
44+
const marked = truncateSanitizedExternalContent(value, Math.max(0, maxChars - marker.length));
45+
return {
46+
text: `${marked.text}${marker}`,
47+
truncated: true,
48+
};
49+
}
50+
51+
function wrapBoundedBrowserToolText(params: {
52+
value: string;
53+
marker: string;
54+
includeWarning: boolean;
55+
}) {
56+
const wrap = (value: string) =>
57+
wrapExternalContent(value, {
58+
source: "browser",
59+
includeWarning: params.includeWarning,
60+
});
61+
const wrapperOverhead = wrap("").length;
62+
let maxInnerChars = Math.max(0, DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS - wrapperOverhead);
63+
let bounded = truncateBrowserToolText(params.value, params.marker, maxInnerChars);
64+
let wrappedText = wrap(bounded.text);
65+
if (wrappedText.length > DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS) {
66+
maxInnerChars = Math.max(
67+
0,
68+
maxInnerChars - (wrappedText.length - DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS),
69+
);
70+
bounded = truncateBrowserToolText(params.value, params.marker, maxInnerChars);
71+
wrappedText = wrap(bounded.text);
72+
}
73+
return { text: wrappedText, truncated: bounded.truncated };
74+
}
75+
2776
export type BrowserProxyRequest = ((opts: {
2877
method: string;
2978
path: string;
@@ -40,22 +89,24 @@ export type BrowserProxyRequest = ((opts: {
4089

4190
/** Wrap page-controlled JSON payloads as untrusted browser content. */
4291
export function wrapBrowserExternalJson(params: {
43-
kind: "snapshot" | "console" | "tabs" | "act" | "download";
92+
kind: BrowserExternalJsonKind;
4493
payload: unknown;
4594
includeWarning?: boolean;
4695
}): { wrappedText: string; safeDetails: Record<string, unknown> } {
47-
const extractedText = JSON.stringify(
48-
params.payload,
49-
(_key: string, value: unknown) =>
50-
typeof value === "string" ? neutralizeMediaDirectives(value) : value,
51-
2,
52-
);
96+
const serialized =
97+
JSON.stringify(
98+
params.payload,
99+
(_key: string, value: unknown) =>
100+
typeof value === "string" ? neutralizeMediaDirectives(value) : value,
101+
2,
102+
) ?? "null";
53103
// Browser tabs, snapshots, and console output are page-controlled data. Keep
54104
// text wrapped even when details carry the structured fields for callers.
55-
const wrappedText = wrapExternalContent(extractedText, {
56-
source: "browser",
105+
const wrappedText = wrapBoundedBrowserToolText({
106+
value: serialized,
107+
marker: BROWSER_EXTERNAL_JSON_TRUNCATION_MARKERS[params.kind],
57108
includeWarning: params.includeWarning ?? true,
58-
});
109+
}).text;
59110
return {
60111
wrappedText,
61112
safeDetails: {
@@ -208,17 +259,18 @@ export async function executeSnapshotAction(params: {
208259
},
209260
};
210261
}
211-
const extractedText = snapshot.snapshot ?? "";
212-
const wrappedSnapshot = wrapExternalContent(neutralizeMediaDirectives(extractedText), {
213-
source: "browser",
262+
const extractedText = neutralizeMediaDirectives(snapshot.snapshot ?? "");
263+
const boundedSnapshot = wrapBoundedBrowserToolText({
264+
value: extractedText,
265+
marker: BROWSER_EXTERNAL_JSON_TRUNCATION_MARKERS.snapshot,
214266
includeWarning: true,
215267
});
216268
const safeDetails = {
217269
ok: true,
218270
format: snapshot.format,
219271
targetId: snapshot.targetId,
220272
url: snapshot.url,
221-
truncated: snapshot.truncated,
273+
truncated: snapshot.truncated || boundedSnapshot.truncated ? true : undefined,
222274
newElements: snapshot.newElements,
223275
stats: snapshot.stats,
224276
refs: snapshot.refs ? Object.keys(snapshot.refs).length : undefined,
@@ -242,14 +294,14 @@ export async function executeSnapshotAction(params: {
242294
return await imageResultFromFile({
243295
label: "browser:snapshot",
244296
path: snapshot.imagePath,
245-
extraText: wrappedSnapshot,
297+
extraText: boundedSnapshot.text,
246298
// Keep model-only screenshots out of automatic channel delivery.
247299
details: { ...safeDetails, media: { outbound: false } },
248300
imageSanitization: resolveRuntimeImageSanitization(),
249301
});
250302
}
251303
return {
252-
content: [{ type: "text" as const, text: wrappedSnapshot }],
304+
content: [{ type: "text" as const, text: boundedSnapshot.text }],
253305
details: safeDetails,
254306
};
255307
}

0 commit comments

Comments
 (0)