Skip to content

Commit bb51e90

Browse files
authored
refactor(browser): split tool routing lifecycle and screenshots (#132049)
Move existing browser tool behavior into internal concept modules and remove the grandfathered max-lines suppression and baseline entry.
1 parent 944cff7 commit bb51e90

6 files changed

Lines changed: 602 additions & 498 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ extensions/browser/src/browser-tool-binding.ts 3
5454
extensions/browser/src/browser-tool-session-tabs.ts 3
5555
extensions/browser/src/browser-tool.actions.ts 14
5656
extensions/browser/src/browser-tool.snapshot.ts 2
57-
extensions/browser/src/browser-tool.ts 18
57+
extensions/browser/src/browser-tool.ts 14
5858
extensions/browser/src/browser/bridge-server.ts 3
5959
extensions/browser/src/browser/cdp-page-session.ts 3
6060
extensions/browser/src/browser/cdp-proxy-bypass.ts 1

‎config/max-lines-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ extensions/anthropic/index.test.ts
1111
extensions/anthropic/register.runtime.ts
1212
extensions/anthropic/session-catalog.test.ts
1313
extensions/browser/src/browser-tool.test.ts
14-
extensions/browser/src/browser-tool.ts
1514
extensions/browser/src/browser/cdp.ts
1615
extensions/browser/src/browser/chrome-mcp.test.ts
1716
extensions/browser/src/browser/chrome.executables.ts
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
/** Browser tool lifecycle and host-local profile discovery/import actions. */
2+
import type { AgentToolResult } from "openclaw/plugin-sdk/agent-core";
3+
import type { BrowserProxyRequest } from "./browser-node-proxy.js";
4+
import { resolveBrowserBaseUrl } from "./browser-tool.routing.js";
5+
import {
6+
browserDoctor,
7+
browserImportProfile,
8+
browserProfiles,
9+
browserSystemProfiles,
10+
browserStart,
11+
browserStatus,
12+
browserStop,
13+
jsonResult,
14+
normalizeOptionalString,
15+
} from "./browser-tool.runtime.js";
16+
import { parseSystemProfileDomains } from "./browser/system-profile-domains.js";
17+
18+
const unavailableSystemProfiles = (unavailableReason: string) => ({
19+
profiles: [],
20+
unavailableReason,
21+
});
22+
23+
/**
24+
* Read importable system profiles from the host control server. Discovery must
25+
* match where import runs (host-local), so it never uses a node proxy or the
26+
* sandbox base URL. Other profile sources remain useful when host discovery
27+
* is unavailable, so failures become an explicit degradation fact.
28+
*/
29+
async function readHostSystemProfiles(params: {
30+
allowHostControl?: boolean;
31+
sandboxBridgeUrl?: string;
32+
timeoutMs?: number;
33+
signal?: AbortSignal;
34+
}) {
35+
if (params.allowHostControl === false) {
36+
return unavailableSystemProfiles(
37+
"Host system profile discovery is disabled by sandbox policy; enable host control to discover importable system profiles.",
38+
);
39+
}
40+
let hostBaseUrl: string | undefined;
41+
try {
42+
hostBaseUrl = resolveBrowserBaseUrl({
43+
target: "host",
44+
sandboxBridgeUrl: params.sandboxBridgeUrl,
45+
allowHostControl: params.allowHostControl,
46+
});
47+
} catch {
48+
return unavailableSystemProfiles(
49+
'Host browser control is unavailable; enable it and retry action=profiles target="host".',
50+
);
51+
}
52+
try {
53+
return {
54+
profiles: await browserSystemProfiles(hostBaseUrl, {
55+
timeoutMs: params.timeoutMs,
56+
signal: params.signal,
57+
}),
58+
unavailableReason: undefined,
59+
};
60+
} catch {
61+
params.signal?.throwIfAborted();
62+
return unavailableSystemProfiles(
63+
'Host system profile discovery failed; retry action=profiles target="host" after host browser control is available.',
64+
);
65+
}
66+
}
67+
68+
export async function executeBrowserLifecycleAction({
69+
action,
70+
input: params,
71+
baseUrl,
72+
profile,
73+
timeoutMs: toolTimeoutMs,
74+
proxyRequest,
75+
allowHostControl,
76+
sandboxBridgeUrl,
77+
signal,
78+
}: {
79+
action: "doctor" | "status" | "start" | "stop" | "profiles" | "importprofile";
80+
input: Record<string, unknown>;
81+
baseUrl?: string;
82+
profile?: string;
83+
timeoutMs?: number;
84+
proxyRequest: BrowserProxyRequest | null;
85+
allowHostControl?: boolean;
86+
sandboxBridgeUrl?: string;
87+
signal?: AbortSignal;
88+
}): Promise<AgentToolResult<unknown>> {
89+
const readBrowserStatus = async () =>
90+
proxyRequest
91+
? await proxyRequest({
92+
method: "GET",
93+
path: "/",
94+
profile,
95+
timeoutMs: toolTimeoutMs,
96+
})
97+
: await browserStatus(baseUrl, {
98+
profile,
99+
timeoutMs: toolTimeoutMs,
100+
signal,
101+
});
102+
switch (action) {
103+
case "doctor":
104+
return jsonResult(
105+
proxyRequest
106+
? await proxyRequest({ method: "GET", path: "/doctor", profile })
107+
: await browserDoctor(baseUrl, { profile, signal }),
108+
);
109+
case "status":
110+
return jsonResult(await readBrowserStatus());
111+
case "start":
112+
case "stop": {
113+
if (proxyRequest) {
114+
await proxyRequest({
115+
method: "POST",
116+
path: `/${action}`,
117+
profile,
118+
timeoutMs: toolTimeoutMs,
119+
});
120+
} else {
121+
const updateBrowser = action === "start" ? browserStart : browserStop;
122+
await updateBrowser(baseUrl, { profile, timeoutMs: toolTimeoutMs, signal });
123+
}
124+
return jsonResult(await readBrowserStatus());
125+
}
126+
case "profiles": {
127+
// Importable system profiles are host-local (import runs on the host),
128+
// so read them from the host regardless of the profiles action target;
129+
// never let a node proxy or sandbox describe the wrong Chrome profiles.
130+
const { profiles: systemProfiles, unavailableReason: systemProfilesUnavailable } =
131+
await readHostSystemProfiles({
132+
allowHostControl,
133+
sandboxBridgeUrl,
134+
timeoutMs: toolTimeoutMs,
135+
signal,
136+
});
137+
if (proxyRequest) {
138+
const result = await proxyRequest({
139+
method: "GET",
140+
path: "/profiles",
141+
timeoutMs: toolTimeoutMs,
142+
});
143+
return jsonResult({
144+
...(result && typeof result === "object" ? result : { profiles: result }),
145+
systemProfiles,
146+
...(systemProfilesUnavailable ? { systemProfilesUnavailable } : {}),
147+
});
148+
}
149+
return jsonResult({
150+
profiles: await browserProfiles(baseUrl, {
151+
timeoutMs: toolTimeoutMs,
152+
signal,
153+
}),
154+
systemProfiles,
155+
...(systemProfilesUnavailable ? { systemProfilesUnavailable } : {}),
156+
});
157+
}
158+
case "importprofile": {
159+
if (proxyRequest) {
160+
throw new Error("system profile import must run on the browser host");
161+
}
162+
const domains = parseSystemProfileDomains(params.domains);
163+
return jsonResult(
164+
await browserImportProfile(baseUrl, {
165+
browser: normalizeOptionalString(params.browser) ?? "chrome",
166+
systemProfile: normalizeOptionalString(params.systemProfile) ?? "Default",
167+
into: normalizeOptionalString(params.into) ?? "imported",
168+
domains,
169+
signal,
170+
}),
171+
);
172+
}
173+
default:
174+
throw new Error(`Unknown action: ${String(action)}`);
175+
}
176+
}
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
/** Browser tool host, sandbox, and node target resolution. */
2+
import { resolveBrowserNodeTarget } from "./browser-node-routing.js";
3+
import {
4+
getRuntimeConfig,
5+
listNodes,
6+
resolveBrowserConfig,
7+
resolveProfile,
8+
getBrowserProfileCapabilities,
9+
} from "./browser-tool.runtime.js";
10+
11+
export type BrowserNodeTarget = {
12+
nodeId: string;
13+
label?: string;
14+
commands: string[];
15+
pendingDeclaredCommands: string[];
16+
};
17+
18+
export async function resolveBrowserToolNodeTarget(params: {
19+
requestedNode?: string;
20+
target?: "sandbox" | "host" | "node";
21+
sandboxBridgeUrl?: string;
22+
allowHostControl?: boolean;
23+
signal?: AbortSignal;
24+
}): Promise<BrowserNodeTarget | null> {
25+
if (params.allowHostControl === false) {
26+
if (params.target === "node" || params.requestedNode) {
27+
throw new Error("Node browser control is disabled by sandbox policy.");
28+
}
29+
return null;
30+
}
31+
32+
const cfg = getRuntimeConfig();
33+
const policy = cfg.gateway?.nodes?.browser;
34+
const explicitTarget = params.target === "node";
35+
const requestedNode = params.requestedNode?.trim();
36+
if (policy?.mode === "off") {
37+
resolveBrowserNodeTarget({ nodes: [], policy, requestedNode, explicitTarget });
38+
return null;
39+
}
40+
if (params.sandboxBridgeUrl?.trim() && !explicitTarget && !requestedNode) {
41+
return null;
42+
}
43+
if (params.target && !explicitTarget) {
44+
return null;
45+
}
46+
if (policy?.mode === "manual" && !explicitTarget && !requestedNode && !policy.node?.trim()) {
47+
return null;
48+
}
49+
const node = resolveBrowserNodeTarget({
50+
nodes: await listNodes({}, params.signal),
51+
policy,
52+
requestedNode,
53+
explicitTarget,
54+
requireConnected: true,
55+
});
56+
return node
57+
? {
58+
nodeId: node.nodeId,
59+
label: node.displayName ?? node.remoteIp ?? node.nodeId,
60+
commands: node.commands ?? [],
61+
pendingDeclaredCommands: node.pendingDeclaredCommands ?? [],
62+
}
63+
: null;
64+
}
65+
66+
export function resolveBrowserBaseUrl(params: {
67+
target?: "sandbox" | "host";
68+
sandboxBridgeUrl?: string;
69+
allowHostControl?: boolean;
70+
}): string | undefined {
71+
const cfg = getRuntimeConfig();
72+
const resolved = resolveBrowserConfig(cfg.browser, cfg);
73+
const normalizedSandbox = params.sandboxBridgeUrl?.trim() ?? "";
74+
const target = params.target ?? (normalizedSandbox ? "sandbox" : "host");
75+
76+
if (target === "sandbox") {
77+
if (!normalizedSandbox) {
78+
throw new Error(
79+
'Sandbox browser is unavailable. Enable agents.defaults.sandbox.browser.enabled or use target="host" if allowed.',
80+
);
81+
}
82+
return normalizedSandbox.replace(/\/$/, "");
83+
}
84+
85+
if (params.allowHostControl === false) {
86+
throw new Error("Host browser control is disabled by sandbox policy.");
87+
}
88+
if (!resolved.enabled) {
89+
throw new Error(
90+
"Browser control is disabled. Set browser.enabled=true in ~/.openclaw/openclaw.json.",
91+
);
92+
}
93+
return undefined;
94+
}
95+
96+
const DEFAULT_EXISTING_SESSION_MANAGE_TIMEOUT_MS = 45_000;
97+
const EXISTING_SESSION_MANAGE_ACTIONS = new Set([
98+
"status",
99+
"start",
100+
"stop",
101+
"profiles",
102+
"tabs",
103+
"open",
104+
"focus",
105+
"close",
106+
]);
107+
108+
function hasExistingSessionProfile(resolved: ReturnType<typeof resolveBrowserConfig>) {
109+
return Object.keys(resolved.profiles).some((name) => {
110+
const candidate = resolveProfile(resolved, name);
111+
return candidate ? getBrowserProfileCapabilities(candidate).usesChromeMcp : false;
112+
});
113+
}
114+
115+
export function resolveBrowserToolTimeoutMs({
116+
requestedTimeoutMs,
117+
action,
118+
isUserBrowserProfile,
119+
resolvedBrowser,
120+
}: {
121+
requestedTimeoutMs?: number;
122+
action: string;
123+
isUserBrowserProfile: boolean;
124+
resolvedBrowser: ReturnType<typeof resolveBrowserConfig>;
125+
}) {
126+
return (
127+
requestedTimeoutMs ??
128+
(EXISTING_SESSION_MANAGE_ACTIONS.has(action) &&
129+
(isUserBrowserProfile || (action === "profiles" && hasExistingSessionProfile(resolvedBrowser)))
130+
? DEFAULT_EXISTING_SESSION_MANAGE_TIMEOUT_MS
131+
: undefined)
132+
);
133+
}

0 commit comments

Comments
 (0)