-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathindex.test.ts
More file actions
336 lines (292 loc) · 11.8 KB
/
Copy pathindex.test.ts
File metadata and controls
336 lines (292 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Browser tests cover index plugin behavior.
import fs from "node:fs";
import path from "node:path";
import { createTestPluginApi } from "openclaw/plugin-sdk/plugin-test-api";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import {
browserPluginNodeHostCommands,
browserPluginReload,
browserSecurityAuditCollectors,
registerBrowserPlugin,
} from "./plugin-registration.js";
import type { OpenClawPluginApi } from "./runtime-api.js";
import setupPlugin from "./setup-api.js";
type BrowserAutoEnableProbe = Parameters<OpenClawPluginApi["registerAutoEnableProbe"]>[0];
const runtimeApiMocks = vi.hoisted(() => ({
createBrowserPluginService: vi.fn(() => ({ id: "browser-control", start: vi.fn() })),
createBrowserTool: vi.fn(() => ({
name: "browser",
description: "browser",
parameters: { type: "object", properties: {} },
execute: vi.fn(async () => ({ type: "json", value: { ok: true } })),
})),
collectBrowserSecurityAuditFindings: vi.fn(() => []),
handleBrowserGatewayRequest: vi.fn(),
registerBrowserCli: vi.fn(),
runBrowserProxyCommand: vi.fn(async () => "ok"),
stopBrowserControlService: vi.fn(async () => undefined),
}));
vi.mock("./register.runtime.js", async () => {
const actual =
await vi.importActual<typeof import("./register.runtime.js")>("./register.runtime.js");
return {
...actual,
collectBrowserSecurityAuditFindings: runtimeApiMocks.collectBrowserSecurityAuditFindings,
createBrowserPluginService: runtimeApiMocks.createBrowserPluginService,
createBrowserTool: runtimeApiMocks.createBrowserTool,
handleBrowserGatewayRequest: runtimeApiMocks.handleBrowserGatewayRequest,
runBrowserProxyCommand: runtimeApiMocks.runBrowserProxyCommand,
};
});
vi.mock("./src/cli/browser-cli.js", () => ({
registerBrowserCli: runtimeApiMocks.registerBrowserCli,
}));
vi.mock("./src/control-service.js", () => ({
stopBrowserControlService: runtimeApiMocks.stopBrowserControlService,
}));
beforeAll(async () => {
await import("./register.runtime.js");
});
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.unstubAllEnvs();
});
function createApi() {
const registerCli = vi.fn();
const registerGatewayMethod = vi.fn();
const registerService = vi.fn();
const registerTool = vi.fn();
const api = createTestPluginApi({
id: "browser",
name: "Browser",
source: "test",
config: {},
runtime: {} as OpenClawPluginApi["runtime"],
registerCli,
registerGatewayMethod,
registerService,
registerTool,
});
return { api, registerCli, registerGatewayMethod, registerService, registerTool };
}
function mockCallArg(mock: { mock: { calls: unknown[][] } }, index = 0, argIndex = 0): unknown {
const call = mock.mock.calls.at(index);
if (!call) {
throw new Error(`expected mock call ${index}`);
}
return call[argIndex];
}
function registerBrowserAutoEnableProbe(): BrowserAutoEnableProbe {
const probes: BrowserAutoEnableProbe[] = [];
setupPlugin.register(
createTestPluginApi({
registerAutoEnableProbe(probe) {
probes.push(probe);
},
}),
);
const probe = probes[0];
if (!probe) {
throw new Error("expected browser setup plugin to register an auto-enable probe");
}
return probe;
}
describe("browser plugin", () => {
it("exposes static browser metadata on the plugin definition", () => {
expect(browserPluginReload).toEqual({ restartPrefixes: ["browser"] });
expect(browserPluginNodeHostCommands).toHaveLength(1);
expect(browserPluginNodeHostCommands[0]?.command).toBe("browser.proxy");
expect(browserPluginNodeHostCommands[0]?.cap).toBe("browser");
expect(typeof browserPluginNodeHostCommands[0]?.handle).toBe("function");
expect(browserSecurityAuditCollectors).toHaveLength(1);
});
it("bundles the browser automation skill with the plugin", () => {
const manifest = JSON.parse(
fs.readFileSync(path.join(__dirname, "openclaw.plugin.json"), "utf8"),
) as { skills?: string[] };
const skillPath = path.join(__dirname, "skills", "browser-automation", "SKILL.md");
expect(manifest.skills).toEqual(["./skills"]);
expect(fs.readFileSync(skillPath, "utf8")).toContain("name: browser-automation");
});
it("keeps browser tool registration synchronous while loading runtime on execute", async () => {
const { api, registerTool } = createApi();
registerBrowserPlugin(api);
const factory = mockCallArg(registerTool);
if (typeof factory !== "function") {
throw new Error("expected browser plugin to register a tool factory");
}
const tool = factory({
sessionKey: "agent:main:webchat:direct:123",
browser: {
sandboxBridgeUrl: "http://127.0.0.1:9999",
allowHostControl: true,
},
});
if (!tool || Array.isArray(tool)) {
throw new Error("expected browser plugin to return a single tool");
}
expect(tool.name).toBe("browser");
expect(runtimeApiMocks.createBrowserTool).not.toHaveBeenCalled();
await tool.execute("call-1", { action: "status" });
expect(runtimeApiMocks.createBrowserTool).toHaveBeenCalledWith({
sandboxBridgeUrl: "http://127.0.0.1:9999",
allowHostControl: true,
agentSessionKey: "agent:main:webchat:direct:123",
mediaScope: {
sessionKey: "agent:main:webchat:direct:123",
chatType: "direct",
},
});
});
it("passes runtime context needed for screenshot image understanding", async () => {
const { api, registerTool } = createApi();
registerBrowserPlugin(api);
const factory = mockCallArg(registerTool);
if (typeof factory !== "function") {
throw new Error("expected browser plugin to register a tool factory");
}
const tool = factory({
sessionKey: "agent:main:webchat:direct:123",
agentDir: "/tmp/agent",
workspaceDir: "/tmp/workspace",
activeModel: { provider: "openai", modelId: "gpt-5.5" },
deliveryContext: { channel: "telegram" },
});
if (!tool || Array.isArray(tool)) {
throw new Error("expected browser plugin to return a single tool");
}
await tool.execute("call-1", { action: "status" });
expect(runtimeApiMocks.createBrowserTool).toHaveBeenCalledWith({
agentSessionKey: "agent:main:webchat:direct:123",
agentDir: "/tmp/agent",
workspaceDir: "/tmp/workspace",
activeModel: { provider: "openai", model: "gpt-5.5" },
mediaScope: {
sessionKey: "agent:main:webchat:direct:123",
channel: "telegram",
chatType: "direct",
},
});
});
it("derives group chat type for browser media scope", async () => {
const { api, registerTool } = createApi();
registerBrowserPlugin(api);
const factory = mockCallArg(registerTool);
if (typeof factory !== "function") {
throw new Error("expected browser plugin to register a tool factory");
}
const tool = factory({
sessionKey: "agent:main:telegram:group:chat-123",
messageChannel: "telegram",
});
if (!tool || Array.isArray(tool)) {
throw new Error("expected browser plugin to return a single tool");
}
await tool.execute("call-1", { action: "status" });
expect(runtimeApiMocks.createBrowserTool).toHaveBeenCalledWith({
agentSessionKey: "agent:main:telegram:group:chat-123",
mediaScope: {
sessionKey: "agent:main:telegram:group:chat-123",
channel: "telegram",
chatType: "group",
},
});
});
it("registers CLI descriptors and lazy-loads the lightweight browser CLI", async () => {
const { api, registerCli } = createApi();
registerBrowserPlugin(api);
expect(registerCli).toHaveBeenCalledTimes(1);
const registrar = mockCallArg(registerCli) as (params: { program: never }) => unknown;
expect(typeof registrar).toBe("function");
expect(mockCallArg(registerCli, 0, 1)).toEqual({
commands: ["browser"],
descriptors: [
{
name: "browser",
description: "Manage OpenClaw's dedicated browser (Chrome/Chromium)",
hasSubcommands: true,
},
],
});
await registrar({ program: {} as never });
expect(runtimeApiMocks.registerBrowserCli).toHaveBeenCalledWith({});
});
it("registers browser.request as an admin gateway method and lazy-loads handler", async () => {
const { api, registerGatewayMethod } = createApi();
registerBrowserPlugin(api);
expect(registerGatewayMethod).toHaveBeenCalledTimes(1);
expect(mockCallArg(registerGatewayMethod)).toBe("browser.request");
const handler = mockCallArg(registerGatewayMethod, 0, 1) as (request: {
method: string;
}) => unknown;
expect(typeof handler).toBe("function");
expect(mockCallArg(registerGatewayMethod, 0, 2)).toEqual({
scope: "operator.admin",
});
await handler({ method: "browser.request" });
expect(runtimeApiMocks.handleBrowserGatewayRequest).toHaveBeenCalledWith({
method: "browser.request",
});
});
it("lazy-loads node host and audit runtime handlers", async () => {
await expect(browserPluginNodeHostCommands[0]?.handle("{}")).resolves.toBe("ok");
expect(runtimeApiMocks.runBrowserProxyCommand).toHaveBeenCalledWith("{}");
await expect(browserSecurityAuditCollectors[0]?.({} as never)).resolves.toStrictEqual([]);
expect(runtimeApiMocks.collectBrowserSecurityAuditFindings).toHaveBeenCalled();
});
it("registers a lazy browser control service", async () => {
const { api, registerService } = createApi();
registerBrowserPlugin(api);
const service = mockCallArg(registerService) as {
id: string;
start: (...args: unknown[]) => unknown;
stop: (...args: unknown[]) => unknown;
};
expect(service?.id).toBe("browser-control");
expect(typeof service?.start).toBe("function");
expect(typeof service?.stop).toBe("function");
expect(runtimeApiMocks.createBrowserPluginService).not.toHaveBeenCalled();
await service.start({ config: {}, stateDir: "/tmp/openclaw", logger: { warn: vi.fn() } });
expect(runtimeApiMocks.createBrowserPluginService).not.toHaveBeenCalled();
await service.stop({ config: {}, stateDir: "/tmp/openclaw", logger: { warn: vi.fn() } });
expect(runtimeApiMocks.stopBrowserControlService).toHaveBeenCalledOnce();
});
it("eager-loads the browser control service when explicitly requested", async () => {
vi.stubEnv("OPENCLAW_EAGER_BROWSER_CONTROL_SERVER", "1");
const { api, registerService } = createApi();
registerBrowserPlugin(api);
const service = mockCallArg(registerService) as {
id: string;
start: (...args: unknown[]) => unknown;
};
await service.start({ config: {}, stateDir: "/tmp/openclaw", logger: { warn: vi.fn() } });
expect(runtimeApiMocks.createBrowserPluginService).toHaveBeenCalledOnce();
});
for (const value of ["false", "", "disabled"]) {
it(`keeps browser control service env value ${JSON.stringify(value)} lazy`, async () => {
vi.stubEnv("OPENCLAW_EAGER_BROWSER_CONTROL_SERVER", value);
const { api, registerService } = createApi();
registerBrowserPlugin(api);
const service = mockCallArg(registerService) as {
id: string;
start: (...args: unknown[]) => unknown;
};
await service.start({ config: {}, stateDir: "/tmp/openclaw", logger: { warn: vi.fn() } });
expect(runtimeApiMocks.createBrowserPluginService).not.toHaveBeenCalled();
});
}
it("declares setup auto-enable reasons for browser config surfaces", () => {
const probe = registerBrowserAutoEnableProbe();
expect(probe({ config: { browser: { defaultProfile: "openclaw" } }, env: {} })).toBe(
"browser configured",
);
expect(probe({ config: { tools: { alsoAllow: ["browser"] } }, env: {} })).toBe(
"browser tool referenced",
);
expect(
probe({ config: { browser: { defaultProfile: "openclaw", enabled: false } }, env: {} }),
).toBeNull();
});
});