Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(browser): 支持切换浏览器模式并放行内网导航 (#4062)

Dashc7c64e99e013
diff --git a/apps/desktop/src/main/__tests__/browser-backend-settings-store.test.ts b/apps/desktop/src/main/__tests__/browser-backend-settings-store.test.ts
index 0900610f03..7c5e1bf734 100644
--- a/apps/desktop/src/main/__tests__/browser-backend-settings-store.test.ts
+++ b/apps/desktop/src/main/__tests__/browser-backend-settings-store.test.ts
@@ -1,6 +1,36 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
-import { __testing } from '../browser-backend-settings-store.js';
+const paths = vi.hoisted(() => ({ userData: '' }));
+vi.mock('electron', () => ({ app: { getPath: () => paths.userData } }));
+
+import {
+ __testing, readBrowserBackendSettingsState, resetBrowserBackendSettings,
+ writeBrowserBackendKind, writeBrowserUseRealProfile,
+} from '../browser-backend-settings-store.js';
+
+describe('browser-backend explicit preferences', () => {
+ beforeEach(() => { paths.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'browser-settings-')); });
+ afterEach(() => { fs.rmSync(paths.userData, { recursive: true, force: true }); });
+
+ it('preserves an explicit default and other preferences until reset', () => {
+ writeBrowserUseRealProfile(true);
+ writeBrowserBackendKind('rsb-webview');
+ writeBrowserBackendKind('external');
+ expect(readBrowserBackendSettingsState().customizedKeys).toContain('kind');
+ expect(JSON.parse(fs.readFileSync(path.join(paths.userData, 'browser-backend-settings.json'), 'utf8')))
+ .toEqual({ kind: 'external', useRealProfile: true });
+ resetBrowserBackendSettings();
+ expect(readBrowserBackendSettingsState()).toMatchObject({
+ value: { kind: 'external', useRealProfile: false }, isCustomized: false, customizedKeys: [],
+ });
+ expect(fs.existsSync(path.join(paths.userData, 'browser-backend-settings.json'))).toBe(false);
+ writeBrowserBackendKind('external');
+ expect(readBrowserBackendSettingsState().customizedKeys).toEqual(['kind']);
+ });
+});
describe('browser-backend-settings-store normalize', () => {
it('defaults useRealProfile to false', () => {
diff --git a/apps/desktop/src/main/browser-backend-settings-store.ts b/apps/desktop/src/main/browser-backend-settings-store.ts
index da7347fa0b..9a09413974 100644
--- a/apps/desktop/src/main/browser-backend-settings-store.ts
+++ b/apps/desktop/src/main/browser-backend-settings-store.ts
@@ -38,21 +38,20 @@
* ignored: no override exists to honor. Two mechanisms collapse
* "deliberately chose the then-default" into "never customized":
* (a) `override-settings-file.writePatch` DELETES a key whose new value
- * equals the current default (`writeBrowserBackendKind` passes no
+ * equals the current default (the old writer did not pass
* `preserveDefaults`), and an empty override map unlinks the file —
* so toggling external→rsb-webview under the old default erased the
* file it had just written;
- * (b) `setActiveBrowserBackendKind` short-circuits on same-kind, so
- * re-clicking the already-active backend never writes at all.
+ * (b) the old `setActiveBrowserBackendKind` short-circuited on same-kind,
+ * so re-clicking the already-active backend never wrote at all.
* `isCustomized` is `Object.keys(overrides).length > 0`, hence false for
* all of them.
* Consequence worth stating plainly: a user who chose the sidebar browser *for
* its tighter isolation* (no loopback CDP port, uploads confined to the session
* dir) is silently moved onto the backend that has neither. Protecting that
- * user would need a customization flag independent of value-equality; §3
- * forbids reconstructing intent from the old stored value, so we do NOT try to
- * infer it retroactively. If that user class matters, the fix is a real flag
- * plus a one-time notice — not a heuristic here.
+ * user requires customization independent of value-equality. Explicit choices
+ * now preserve the kind override even at the default; reset clears it. §3
+ * forbids reconstructing erased intent, so we do not infer it retroactively.
* No migration step is needed either way: `createOverrideSettingsFile` persists
* only the override, so "has an override" is directly observable. Note the two
* backends do NOT share login state — a user moved to `'external'` by this
@@ -126,7 +125,7 @@ export function readBrowserBackendSettingsState(): OverrideSettingsState<Browser
}
export function writeBrowserBackendKind(kind: BackendKind): void {
- store.writePatch({ kind });
+ store.writePatch({ kind }, { preserveDefaults: true });
log.info('browser-backend kind written', { kind });
}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts
index 383b5cb849..60e7302852 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts
@@ -3,10 +3,9 @@ import { describe, expect, it } from 'vitest';
import { buildManagedConfig } from '../browser-managed-config.js';
describe('managed browser runtime config', () => {
- it('allows only proxy fake-IP ranges without disabling private-network protection', () => {
- expect(buildManagedConfig().browser?.ssrfPolicy).toEqual({
- allowRfc2544BenchmarkRange: true,
- allowIpv6UniqueLocalRange: true,
+ it.each([false, true])('allows private-network browsing with useRealProfile=%s', (useRealProfile) => {
+ expect(buildManagedConfig({ useRealProfile }).browser?.ssrfPolicy).toEqual({
+ dangerouslyAllowPrivateNetwork: true,
});
});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/controller.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/controller.test.ts
index 1c8a93b3b2..4dcdf169cc 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/controller.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { BrowserControlRequest, BrowserControlResult } from '@cindy/browser-control-runtime';
import { BrowserBackendController } from '../controller.js';
+import { createBrowserProfileLifecycleQueue } from '../../browser-real-profile/runtime-stop.js';
import type { BackendKind, BrowserBackend } from '../types.js';
function fakeLogger() {
@@ -31,6 +32,98 @@ function fakeBackend(kind: BackendKind): BrowserBackend & {
}
describe('BrowserBackendController', () => {
+ it('serializes reset cleanup after outgoing profile disposal without deadlocking', async () => {
+ const queue = createBrowserProfileLifecycleQueue();
+ const external = fakeBackend('external');
+ const events: string[] = [];
+ let release!: () => void;
+ const busy = queue.run(() => new Promise<void>((resolve) => { release = resolve; }));
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ external.dispose.mockImplementation(() => queue.run(async () => { events.push('dispose'); }));
+ const controller = new BrowserBackendController({
+ initialKind: 'external', externalBackend: external,
+ createRsbBackend: () => fakeBackend('rsb-webview'), logger: fakeLogger(),
+ });
+ const change = controller.setKind('rsb-webview');
+ await vi.waitFor(() => expect(external.dispose).toHaveBeenCalledOnce());
+ const reset = controller.setKind('external', () => queue.run(async () => { events.push('reset'); }));
+ release();
+ await Promise.all([busy, change, reset]);
+ expect(events).toEqual(['dispose', 'reset']);
+ expect(controller.kind).toBe('external');
+ await expect(controller.setKind('rsb-webview', async () => { throw new Error('cleanup failed'); }))
+ .rejects.toThrow('cleanup failed');
+ expect(controller.kind).toBe('external');
+ });
+
+ it('does not save a selection when its backend factory fails', async () => {
+ const persistKind = vi.fn();
+ const controller = new BrowserBackendController({
+ initialKind: 'external', externalBackend: fakeBackend('external'),
+ createRsbBackend: () => { throw new Error('factory failed'); }, persistKind, logger: fakeLogger(),
+ });
+ await expect(controller.setKind('rsb-webview')).rejects.toThrow('factory failed');
+ expect(persistKind).not.toHaveBeenCalled();
+ expect(controller.kind).toBe('external');
+ });
+
+ it('clears an override on reset without losing a later same-kind explicit choice', async () => {
+ let override: BackendKind | undefined = 'external';
+ const persistKind = vi.fn((kind: BackendKind) => { override = kind; });
+ const clearOverride = vi.fn(() => { override = undefined; });
+ const controller = new BrowserBackendController({
+ initialKind: 'external', externalBackend: fakeBackend('external'),
+ createRsbBackend: () => fakeBackend('rsb-webview'), persistKind, logger: fakeLogger(),
+ });
+ await controller.setKind('external', clearOverride);
+ expect(override).toBeUndefined();
+ expect(persistKind).not.toHaveBeenCalled();
+ await Promise.all([
+ controller.setKind('external', clearOverride),
+ controller.setKind('external'),
+ ]);
+ expect(override).toBe('external');
+ expect(persistKind).toHaveBeenCalledOnce();
+ });
+
+ it('keeps the active backend usable when saving fails, then retries the selection', async () => {
+ const external = fakeBackend('external');
+ const embedded = fakeBackend('rsb-webview');
+ const createRsbBackend = vi.fn(() => embedded);
+ const persistKind = vi.fn().mockImplementationOnce(() => { throw new Error('disk full'); });
+ const controller = new BrowserBackendController({
+ initialKind: 'external', externalBackend: external, createRsbBackend, persistKind, logger: fakeLogger(),
+ });
+ await expect(controller.setKind('rsb-webview')).rejects.toThrow('disk full');
+ expect(controller.kind).toBe('external');
+ expect(await controller.call({ action: 'status' })).toMatchObject({ data: { kind: 'external' } });
+ expect(external.dispose).not.toHaveBeenCalled();
+ await expect(controller.setKind('rsb-webview')).resolves.toBe(true);
+ expect(persistKind.mock.calls).toEqual([['rsb-webview'], ['rsb-webview']]);
+ expect(createRsbBackend).toHaveBeenCalledTimes(2);
+ expect(external.dispose).toHaveBeenCalledOnce();
+ expect(embedded.dispose).not.toHaveBeenCalled();
+ });
+
+ it('persists overlapping selections in the same order as activation', async () => {
+ const external = fakeBackend('external');
+ let release!: () => void;
+ external.dispose.mockImplementationOnce(() => new Promise<void>((resolve) => { release = resolve; }));
+ const persistKind = vi.fn();
+ const controller = new BrowserBackendController({
+ initialKind: 'external', externalBackend: external,
+ createRsbBackend: () => fakeBackend('rsb-webview'), persistKind, logger: fakeLogger(),
+ });
+ const first = controller.setKind('rsb-webview');
+ await vi.waitFor(() => expect(external.dispose).toHaveBeenCalledOnce());
+ const second = controller.setKind('external');
+ expect(persistKind.mock.calls).toEqual([['rsb-webview']]);
+ release();
+ await Promise.all([first, second]);
+ expect(persistKind.mock.calls).toEqual([['rsb-webview'], ['external']]);
+ expect(controller.kind).toBe('external');
+ });
+
it('creates a fresh embedded backend when switching away and back', async () => {
const external = fakeBackend('external');
const embedded: ReturnType<typeof fakeBackend>[] = [];
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts
index 7ac3591c4e..672cfe3634 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts
@@ -1,5 +1,5 @@
-// Verifies the external backend wraps `BrowserControlRuntime` 1:1: every call
-// reaches the runtime verbatim, every result comes back verbatim, and dispose
+// Verifies requests reach the runtime verbatim, status identifies the backend,
+// other results pass through unchanged, and dispose
// goes through the same `stopRuntimeForQuit` contract (logs-and-swallows).
import { describe, expect, it, vi } from 'vitest';
@@ -19,7 +19,7 @@ describe('ExternalChromeBackend', () => {
expect(backend.kind).toBe('external');
});
- it('delegates call() to the underlying runtime verbatim', async () => {
+ it('identifies the external backend while preserving runtime status fields', async () => {
const result: BrowserControlResult = { ok: true, action: 'status', status: 200, data: { ready: true } };
const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(async () => result);
const backend = new ExternalChromeBackend({ call }, fakeLogger());
@@ -28,7 +28,8 @@ describe('ExternalChromeBackend', () => {
expect(call).toHaveBeenCalledTimes(1);
expect(call.mock.calls[0][0]).toEqual({ action: 'status' });
- expect(got).toBe(result);
+ expect(got).toEqual({ ...result, data: { ready: true, backend: 'external' } });
+ expect(result.data).toEqual({ ready: true });
});
it('passes complex requests through unchanged', async () => {
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/controller.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/controller.ts
index f86b3b7edf..ee6e642126 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/controller.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/controller.ts
@@ -10,6 +10,8 @@ export interface BrowserBackendControllerOptions {
initialKind: BackendKind;
externalBackend: BrowserBackend;
createRsbBackend: () => BrowserBackend;
+ /** Save explicit selections inside the existing transition queue. */
+ persistKind?: (kind: BackendKind) => void;
logger: ControllerLogger;
}
@@ -47,11 +49,19 @@ export class BrowserBackendController implements BrowserBackend {
return this.router.probeActiveControl(options);
}
- setKind(kind: BackendKind): Promise<boolean> {
+ setKind(
+ kind: BackendKind,
+ persistKind: ((kind: BackendKind) => void | Promise<void>) | undefined = this.opts.persistKind,
+ ): Promise<boolean> {
return this.enqueue(async () => {
- if (this.router.getCurrentBackendKind() === kind) return false;
- await this.router.setBackend(this.createBackend(kind));
- return true;
+ const changed = this.router.getCurrentBackendKind() !== kind;
+ const next = changed ? this.createBackend(kind) : undefined;
+ // Save before activation: a disk failure must leave the old backend live.
+ // Factories are lazy; router swaps cannot fail on outgoing disposal.
+ // Reset supplies its clear-override operation in this same queue.
+ await persistKind?.(kind);
+ if (next) await this.router.setBackend(next);
+ return changed;
});
}
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts
index c843371b19..1c0197fa2d 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts
@@ -1,9 +1,9 @@
-// External Chrome backend — wraps the vendored `BrowserControlRuntime` 1:1.
+// External Chrome backend — delegates to the vendored `BrowserControlRuntime`.
//
// This is the existing (and, in Phase 1, only) backend. It exists so the host
// can talk to *any* control target through the same `BrowserBackend` contract,
-// not because the wrapping changes anything: every `call` is a direct
-// delegation, and `dispose` reuses the existing electron-free
+// with an explicit backend identity added to status results. Other calls are
+// passed through, and `dispose` reuses the existing electron-free
// `stopRuntimeForQuit` (which already swallows errors per the quit-path
// contract — see browser-dispose.ts).
@@ -28,8 +28,13 @@ export class ExternalChromeBackend implements BrowserBackend {
private readonly logger: BackendLogger,
) {}
- call(request: BackendRequest): Promise<BackendResult> {
- return this.runtime.call(request);
+ async call(request: BackendRequest): Promise<BackendResult> {
+ const result = await this.runtime.call(request);
+ if (request.action !== 'status') return result;
+ // Both backends identify themselves explicitly; the agent must not confuse
+ // the Cindy Chrome profile with the sidebar's embedded browser.
+ const data = result.data && typeof result.data === 'object' ? result.data : {};
+ return { ...result, data: { ...data, backend: this.kind } };
}
/**
diff --git a/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts b/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts
index 94e4ecf2a0..81204fb4db 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts
@@ -63,16 +63,14 @@ export const MANAGED_CDP_PORT = 18800;
* so this config is what a user who never touched the toggle gets.)
*
* SECURITY POSTURE:
- * - Only the fake-IP ranges used by system proxies are exempted from the SSRF
- * guard. This prevents Surge/Clash/sing-box DNS answers (198.18.0.0/15 or
- * IPv6 ULA) from making ordinary public sites look like SSRF attempts while
- * localhost, RFC1918, metadata, link-local, and other special-use addresses
- * remain blocked.
- * - Page-context `evaluate` (and recipe `evaluate` steps) run author/agent JS in
- * Chromium, whose network stack is NOT subject to the Node SSRF guard — a
- * same-origin `fetch` there can reach any host the browser can. This residual
- * surface is accepted as inherent to browser automation (it's the same
- * capability the `act:evaluate` tool already exposes), not a regression.
+ * - The desktop agent may navigate to every host reachable from this machine,
+ * including private, loopback, link-local and metadata addresses. A browser-
+ * only network restriction is not an agent-wide boundary: terminal tools and
+ * page-context JS do not share this Node guard. This is a deliberate product
+ * policy for browser automation, not the default for other network consumers.
+ * - Navigation protocol validation, Chromium sandboxing and website permissions
+ * remain in force. The dedicated profile and consented login-copy rules stay
+ * independent of network reachability.
*/
export function buildManagedConfig(options?: {
useRealProfile?: boolean;
@@ -90,8 +88,7 @@ export function buildManagedConfig(options?: {
headless: false, // headed so the user can see + log into sites
...(executablePath ? { executablePath } : {}),
ssrfPolicy: {
- allowRfc2544BenchmarkRange: true,
- allowIpv6UniqueLocalRange: true,
+ dangerouslyAllowPrivateNetwork: true,
},
profiles: {
[defaultProfile]: {
diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.ts
index a5e233258c..5476c1a434 100644
--- a/apps/desktop/src/main/mcp-integrations/browser.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser.ts
@@ -217,6 +217,7 @@ const backendController = new BrowserBackendController({
initialKind,
externalBackend,
createRsbBackend,
+ persistKind: writeBrowserBackendKind,
logger,
});
const browserBackendHealthService = new BrowserBackendHealthService(backendController, logger);
@@ -273,7 +274,7 @@ export function setIsDetachedForBackend(impl: () => boolean): void {
}
/**
- * Switch the active backend. Called from the Phase 5 toggle IPC handler.
+ * Switch the active backend. Shared by Settings and browser MCP mode changes.
* Persists the new kind to disk and disposes the outgoing backend (per
* lifecycle controller contract).
*/
@@ -282,9 +283,7 @@ export async function setActiveBrowserBackendKind(kind: BackendKind): Promise<vo
// Doing it here would race two Settings actions: a request for the current
// kind could return early while an earlier queued request is about to switch
// away from it.
- const changed = await backendController.setKind(kind);
- if (!changed) return;
- writeBrowserBackendKind(kind);
+ await backendController.setKind(kind);
}
async function stopExternalRuntimeIfUsed(): Promise<void> {
@@ -331,6 +330,7 @@ export function setBrowserUseRealProfile(enabled: boolean): Promise<boolean> {
*/
export function getBrowserMcpDeps(): {
getRuntime(): BrowserControlRuntime;
+ setBackend(kind: BackendKind): Promise<BackendKind>;
supportsResourceDownloads(): boolean;
supportsSemanticQueries(): boolean;
logger: typeof logger;
@@ -338,6 +338,10 @@ export function getBrowserMcpDeps(): {
saveUserRecipe(input: Parameters<typeof writeUserRecipe>[0]): Promise<WriteUserRecipeResult>;
} {
return {
+ setBackend: async (kind) => {
+ await setActiveBrowserBackendKind(kind);
+ return backendController.getCurrentBackendKind();
+ },
// L2 user-recipe layer (userData/browser-recipes); merged over the bundled
// L1 catalog inside the MCP. Empty/missing dir → bundled-only (== before).
getUserRecipes: () => loadUserBrowserRecipes(),
@@ -430,13 +434,16 @@ export function registerBrowserBackendIpc(): void {
return setBrowserUseRealProfile(enabled);
},
reset: async () => {
- const next = await browserProfileLifecycleQueue.run(async () => {
- if (readBrowserBackendSettings().useRealProfile) {
- await applyBrowserUseRealProfile(false);
- }
- return resetBrowserBackendSettings();
- });
- await setActiveBrowserBackendKind(next.kind);
+ // Keep controller -> profile queue ordering, matching external disposal.
+ await backendController.setKind(
+ readBrowserBackendSettingsState().defaults.kind,
+ () => browserProfileLifecycleQueue.run(async () => {
+ if (readBrowserBackendSettings().useRealProfile) {
+ await applyBrowserUseRealProfile(false);
+ }
+ resetBrowserBackendSettings();
+ }),
+ );
return backendController.getCurrentBackendKind();
},
getHealth: getBrowserBackendHealth,
diff --git a/packages/browser-control-runtime/src/__tests__/runtime-config-application.test.ts b/packages/browser-control-runtime/src/__tests__/runtime-config-application.test.ts
index 0a23ab861f..0085bf7201 100644
--- a/packages/browser-control-runtime/src/__tests__/runtime-config-application.test.ts
+++ b/packages/browser-control-runtime/src/__tests__/runtime-config-application.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest';
import { resolveBrowserConfig } from '../_generated/extension/src/browser/config.js';
import { createBrowserControlRuntime } from '../index.js';
+import { assertBrowserNavigationAllowed, assertBrowserNavigationResultAllowed } from '../_generated/extension/src/browser/navigation-guard.js';
+import type { LookupFn } from '../_generated/leaf/src/infra/net/ssrf.js';
// Regression: the host-injected config must actually reach the vendored dispatcher.
// A shim bug (getRuntimeConfigSourceSnapshot returning a {config,source} wrapper
@@ -9,6 +11,34 @@ import { createBrowserControlRuntime } from '../index.js';
// fell back to the vendored DEFAULT profiles ("openclaw"/"user") and every
// host-set profile (name, color, ports) was ignored. This locks the fix in.
describe('host config application', () => {
+ it.each([
+ ['http://172.20.0.2:8010/form', '172.20.0.2'],
+ ['http://intranet.internal/form', '10.0.0.2'],
+ ['http://localhost/form', '127.0.0.1'],
+ ['http://169.254.169.254/', '169.254.169.254'],
+ ['http://[fd00::1]/', 'fd00::1'],
+ ['http://[fe80::1]/', 'fe80::1'],
+ ['http://proxy.example/form', '198.18.0.1'],
+ ])('honors explicit private-network access for navigation and resulting URL: %s', async (url, address) => {
+ const { ssrfPolicy } = resolveBrowserConfig({ ssrfPolicy: { dangerouslyAllowPrivateNetwork: true } });
+ const options = {
+ url, ssrfPolicy,
+ // The guard always uses lookup({ all: true }); the other DNS overloads
+ // are not exercised by this in-memory resolver.
+ lookupFn: (async () => [{ address, family: address.includes(':') ? 6 : 4 }]) as unknown as LookupFn,
+ };
+ await expect(assertBrowserNavigationAllowed(options)).resolves.toBeUndefined();
+ await expect(assertBrowserNavigationResultAllowed(options)).resolves.toBeUndefined();
+ });
+
+ it('retains scheme validation and the restrictive default for other hosts', async () => {
+ const allowed = resolveBrowserConfig({ ssrfPolicy: { dangerouslyAllowPrivateNetwork: true } });
+ await expect(assertBrowserNavigationAllowed({ url: 'file:///private/example', ssrfPolicy: allowed.ssrfPolicy }))
+ .rejects.toThrow(/unsupported protocol/);
+ await expect(assertBrowserNavigationAllowed({ url: 'http://172.20.0.2/', ssrfPolicy: resolveBrowserConfig(undefined).ssrfPolicy }))
+ .rejects.toThrow(/Blocked/);
+ });
+
it('preserves narrow fake-IP SSRF allowances through vendored config resolution', () => {
const resolved = resolveBrowserConfig({
ssrfPolicy: {
diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.md
index 09379a2eff..f8b6337228 100644
--- a/packages/browser-control-runtime/upstream/MAINTAINING.md
+++ b/packages/browser-control-runtime/upstream/MAINTAINING.md
@@ -9,6 +9,8 @@
默认行为:启动**一个专属、持久、headed 的自动化浏览器**(profile 名 "Cindy"),登录态长期保留,与用户日常 Chrome 互不影响。
+工具支持 `browser({action:"setBackend", backend:"rsb-webview"|"external"})`,由 MCP 层调用宿主注入的 `setBackend`,复用设置页的 `setActiveBrowserBackendKind`。这是全局持久选择,影响其他任务,可能中断旧浏览器操作;不迁移 Cookie、标签页或元素引用。`status.data.backend` 明确返回实际模式。切换后重新获取状态和标签页,不能把 `start` 当成切换。非 Desktop 宿主可以不提供此能力,工具会明确返回不支持。
+
用户可在设置 → 自动操作打开「使用我的浏览器登录态」(默认关)。打开后,host 在 `start` 前把系统 Chrome / Edge / Brave **当前 `profile.last_used`** 的 Cookies / Login Data 等 SQLite 库拷进 `browser-runtime/browser/Cindy-real/user-data/Default`(vendored `--user-data-dir` 是 `…/Cindy-real/user-data`),并把 dest `Local State` 的 `last_used` / `last_active_profiles` / `profiles_order` **改写成 Default**(原样拷贝会让 Chrome 打开空的 `Profile N`,窗口看起来已登出)。Chrome 右上角 chip **始终显示 `Cindy`**:磁盘目录必须叫 `Cindy-real`(不能叠到隔离身份 `Cindy` 上),host 通过 `displayName: "Cindy"` 传给 runtime,`launchOpenClawChrome` 用它 decorate,而不是用 map key。再用**同一只浏览器二进制**启动该目录。不 attach 日常 Chrome(Chrome 136+ 会拒绝调试默认 user-data-dir)。关掉开关即删除 `Cindy-real`,`Cindy` 隔离身份不动。失败必须 fail-closed,禁止启动一个看起来在浏览、其实全是登出的窗口。快照当凭证:不要写进日志正文、backup、device-link 或 worktree;`status` 只暴露 `{ enabled, applied, source }`,不暴露路径。快照实现在 `apps/desktop/src/main/mcp-integrations/browser-real-profile/`;chip 名例外见 `sync.mjs` 对 `chrome.ts` 的 LOCAL_PATCH。
## 2. 三层架构 + 文件清单
@@ -38,7 +40,7 @@ playwright-core → 托管 Chrome(Cindy profile, 持久 user-data-dir)
## 3. 配置流(以及那个静默 bug)
-host 在 `browser-managed-config.ts` 用 `buildManagedConfig()` 造出 `{ browser: { enabled, defaultProfile:'Cindy', headless:false, ssrfPolicy:{ allowRfc2544BenchmarkRange:true, allowIpv6UniqueLocalRange:true }, profiles:{ Cindy:{ driver:'openclaw', color, cdpPort } } } }`,`browser.ts` 在模块求值时将其传给 `createBrowserControlRuntime({ config })`。这两个窄开关只豁免 Surge/Clash/sing-box 等代理使用的 fake-IP DNS(`198.18.0.0/15` 与 IPv6 ULA),避免普通公网域名被误拦;localhost、RFC1918、cloud metadata、link-local 与其它 special-use 地址继续由 SSRF guard 阻断。上游 SSRF 层已经支持这两个字段,但 config resolver 尚未透传,所以 `sync.mjs` 用 fail-loud `LOCAL_PATCHES` 保留它们。runtime 内部把 config 存进 in-memory 配置快照;vendored dispatcher 每次请求经
+host 在 `browser-managed-config.ts` 用 `buildManagedConfig()` 造出 `{ browser: { enabled, defaultProfile:'Cindy', headless:false, ssrfPolicy:{ dangerouslyAllowPrivateNetwork:true }, profiles:{ Cindy:{ driver:'openclaw', color, cdpPort } } } }`,`browser.ts` 在模块求值时将其传给 `createBrowserControlRuntime({ config })`。Desktop 浏览器允许访问本机网络可达的所有 HTTP(S) 地址,包括 localhost、RFC1918、cloud metadata、link-local 与代理 fake-IP。这是明确的浏览器产品策略:Agent 的终端和页面内 JS 不受同一 Node guard 控制,不能把浏览器单独拦内网当成完整网络权限边界。协议校验、浏览器沙箱、网站权限和登录态隔离仍保留。该开关使用上游已有能力,不修改共享 SSRF 默认值或其它网络调用方;原有窄 fake-IP 配置及同步补丁继续为其它配置保留。runtime 内部把 config 存进 in-memory 配置快照;vendored dispatcher 每次请求经
`getRuntimeConfigSourceSnapshot() ?? getRuntimeConfig()` 再取 `.browser` 拿到它。
> ⚠️ **不变量(踩过的最大的坑):** `src/shim/runtime-config-snapshot.ts` 的 `getRuntimeConfigSourceSnapshot()` **必须返回 `OpenClawConfig | null`**(默认 `return null`)。它一旦返回 `{config, source}` 这种 wrapper,上面的 `?? getRuntimeConfig()` 永远短路、`.browser` 取到 `undefined`,**host 注入的整份 config 被静默丢弃、runtime 跑纯 vendored 默认值**(于是 profile 显示成上游默认名、颜色/目录全不对)。由 `src/__tests__/runtime-config-application.test.ts` 守护——别删那条测试。
diff --git a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
index e3739a9b13..5cfe24b849 100644
--- a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
+++ b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
@@ -43,6 +43,66 @@ async function makeHarness(
}
describe('createBrowserMcpServer', () => {
+ it('switches modes in the same MCP instance and immediately updates backend capabilities', async () => {
+ let backend: 'external' | 'rsb-webview' = 'external';
+ const switched: string[] = [];
+ const h = await makeHarness({
+ setBackend: async (next) => { switched.push(next); backend = next; return backend; },
+ supportsSemanticQueries: () => backend === 'rsb-webview',
+ supportsResourceDownloads: () => backend === 'rsb-webview',
+ });
+ const call = (args: Record<string, unknown>) => h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args } });
+ try {
+ for (const next of ['rsb-webview', 'rsb-webview', 'external'] as const) {
+ const changed = await call({ action: 'setBackend', backend: next });
+ expect(JSON.parse((changed.content as Array<{ text: string }>)[0].text)).toMatchObject({
+ ok: true, action: 'setBackend', data: { backend: next, scope: 'global', persisted: true },
+ });
+ for (const request of [
+ { kind: 'click', query: { role: 'button', name: 'Submit' } },
+ { kind: 'saveResource', url: 'https://example.test/resource.png' },
+ ]) {
+ const result = await call({ action: 'act', targetId: 'fresh-tab', request });
+ expect(Boolean(result.isError)).toBe(next === 'external');
+ }
+ }
+ expect(switched).toEqual(['rsb-webview', 'rsb-webview', 'external']);
+ expect(h.calls).toHaveLength(4);
+ expect(h.calls.every((request) => (request as { action: string }).action === 'act')).toBe(true);
+ } finally { await h.cleanup(); }
+ });
+
+ it.each([
+ { action: 'setBackend' },
+ { action: 'setBackend', backend: 'chrome' },
+ { action: 'open', backend: 'rsb-webview', url: 'https://example.test/' },
+ ])('rejects invalid mode arguments without navigation or switching: %j', async (args) => {
+ let switches = 0;
+ const h = await makeHarness({ setBackend: async (next) => { switches++; return next; } });
+ try {
+ const result = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args } });
+ expect(result.isError).toBe(true);
+ expect(switches).toBe(0);
+ expect(h.calls).toEqual([]);
+ } finally { await h.cleanup(); }
+ });
+
+ it.each([
+ {},
+ { setBackend: async () => { throw new Error('switch failed'); } },
+ { setBackend: async () => 'external' as const },
+ ])('reports unsupported, failed or superseded switches without claiming success', async (deps) => {
+ const h = await makeHarness(deps);
+ try {
+ const result = await h.client.callTool({
+ name: 'call_tool', arguments: { name: 'browser', args: { action: 'setBackend', backend: 'rsb-webview' } },
+ });
+ expect(result.isError).toBe(true);
+ expect(JSON.parse((result.content as Array<{ text: string }>)[0].text).ok).toBe(false);
+ expect(h.calls).toEqual([]);
+ } finally { await h.cleanup(); }
+ });
+
it('lists browser automation entry tools', async () => {
const h = await makeHarness();
const result = await h.client.listTools();
diff --git a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
index fa35cd2f9a..446dae3d18 100644
--- a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
+++ b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
@@ -19,6 +19,7 @@
1. **先探测状态,别盲目开始**
- `action: "status"` —— 浏览器是否可用、是否已启动;同时读结果里的 `data.backend` 认环境(见「两种浏览器模式」);不可用先看下面的「环境」。
+ - 用户明确指定内置或外置浏览器时,模式不匹配就调用 `action: "setBackend", backend: "rsb-webview"`(内置)或 `"external"`(外置),成功后重新查询 `status`。`start` 只启动当前模式,不会切换模式;工具名 `cindy_browser` 不代表内置浏览器。
- `action: "tabs"` —— 列已有标签页,**复用**已开的页而不是无脑开新页(否则一屏堆满窗口)。
- 怀疑环境异常时 `action: "doctor"` 自检。
@@ -61,7 +62,11 @@
- **`data.backend === "rsb-webview"` = Cindy 侧边栏内置浏览器**:页面活在 Cindy 的会话侧边栏里,不是一个常规浏览器窗口。侧边栏本身可能内嵌在主窗口、也可能被用户开成独立子窗口,`status` **不区分**这两种承载方式——所以请用户看页面时说"Cindy 的侧边栏(若你把侧边栏开成了独立窗口,就是那个窗口)",不要断言窗口存在或不存在。系统默认的自动化后端是独立外置浏览器,不是侧边栏。
- 仅此模式支持:`act:saveResource`(托管下载)、以及 `query` 语义元素查询(role / name / text / label / placeholder / testId / css)。在外置模式下用这两个会被 schema 或运行时门控直接拒掉,别当通用能力使。
-- **`data.backend` 不是 `"rsb-webview"`(通常没有该字段)= 独立外置浏览器**:一个专属持久自动化浏览器窗口(profile 显示为 "Cindy")。`act:saveResource` 与语义 `query` 在此模式不可用,元素定位改用 snapshot 的 `ref` 或 `selector`。
+- **`data.backend === "external"` = 独立外置浏览器**:一个专属持久自动化浏览器窗口(profile 显示为 "Cindy")。`act:saveResource` 与语义 `query` 在此模式不可用,元素定位改用 snapshot 的 `ref` 或 `selector`。旧宿主可能省略该字段,不要把缺少模式信息当成已使用内置浏览器。
+
+`setBackend` 与设置页修改同一个**全局、持久**选择,会影响其他正在使用浏览器的任务,旧模式的操作可能中断。仅按用户明确的模式要求切换,无需重复确认;不要因页面报错自行换模式。切换后重新 `tabs` / `snapshot`,不沿用旧模式的 targetId、ref 或登录态。宿主不支持切换或返回失败时如实说明,不能声称切换成功。
+
+两种模式均允许访问本机网络可达的内网 HTTP(S) 地址。遇到失败按实际连接、DNS、证书或登录错误诊断,不要仅因私有 IP 推断“禁止内网访问”,也不要让用户把内网服务暴露到公网。
**两种模式彼此隔离**。侧边栏始终是独立身份。外置浏览器默认也是独立的 `Cindy` profile;仅当用户在设置里打开「使用我的浏览器登录态」且 `status.data.realProfile.applied === true` 时,外置窗口才带着系统 Chrome / Edge / Brave 的登录拷贝(可撤销,Agent 以用户身份访问)。**不要传 `profile`**,不要试图 attach 用户日常使用的 Chrome。
@@ -85,6 +90,7 @@
| action | 用途 |
|---|---|
| `status` / `doctor` | 可用性 / 自检(读 `data.backend` 判环境,见「两种浏览器模式」) |
+| `setBackend` | 按用户要求切换并保存全局浏览器模式(`backend: rsb-webview / external`),随后重新获取状态与标签页 |
| `start` / `stop` | 启停浏览器 |
| `profiles` | 看 profile 列表(**不含**按站点登录态信号) |
| `tabs` / `open` / `focus` / `close` | 标签页:列 / 开(带 label)/ 切 / 关 |
diff --git a/packages/lizi-mcps/src/browser/tools.ts b/packages/lizi-mcps/src/browser/tools.ts
index f958155cd6..856e4e455c 100644
--- a/packages/lizi-mcps/src/browser/tools.ts
+++ b/packages/lizi-mcps/src/browser/tools.ts
@@ -67,6 +67,7 @@ async function recipeRegistry(deps: BrowserMcpDeps): Promise<Map<string, MergedR
const ACTIONS = [
'doctor',
'status',
+ 'setBackend',
'start',
'stop',
'profiles',
@@ -227,11 +228,16 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
category: 'browser',
description:
'浏览器自动化统一入口。通过 action 选择 status/start/tabs/navigate/snapshot/screenshot/act 等操作; ' +
+ 'status 返回实际浏览器模式; setBackend 切换并保存全局浏览器模式(内置 rsb-webview / 外置 external)。' +
'优先使用 snapshot 返回的 ref 执行 click/type/press,不要猜测 CSS selector。' +
'注意:直接调用本工具时,wait/evaluate/saveResource 不是顶层 action(会报 INVALID_ARGS),它们只能作为 act 的 request.kind 子操作(配方 steps 里仅 wait/evaluate 是合法 DSL action,saveResource 在配方中同样不可用)。',
rules: ['browser-workflow', 'recipe-author'],
inputShape: {
action: z.enum(ACTIONS).describe('浏览器操作类型'),
+ backend: z
+ .enum(['external', 'rsb-webview'])
+ .optional()
+ .describe('仅 action=setBackend: 切换全局自动化目标并保存设置; 会影响其他任务,两种模式的登录态与标签页不互通'),
profile: z.string().optional().describe('浏览器 profile 名;省略则使用默认隔离 profile'),
target: z.enum(['sandbox', 'host', 'node']).optional(),
node: z.string().optional(),
@@ -323,8 +329,33 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
.describe('action=act 时的具体动作请求'),
},
handler: async (args) => {
- const runtime = getRuntime(deps);
try {
+ // Host configuration is not a vendored browser action. Await the same
+ // lifecycle transition as Settings before issuing any new page actions.
+ if (args.action === 'setBackend') {
+ if (!args.backend) {
+ return errorResult(args.action, 'setBackend requires backend: external or rsb-webview');
+ }
+ if (!deps.setBackend) return errorResult(args.action, '当前宿主不支持切换浏览器模式');
+ const backend = await deps.setBackend(args.backend);
+ const ok = backend === args.backend;
+ return {
+ content: [{
+ type: 'text',
+ text: resultText({
+ ok,
+ action: args.action,
+ data: { backend, scope: 'global', ...(ok ? { persisted: true } : {}) },
+ ...(!ok ? { message: '浏览器模式已发生变化,请重新查询 status' } : {}),
+ }),
+ }],
+ isError: !ok,
+ };
+ }
+ if (args.backend !== undefined) {
+ return errorResult(args.action, 'backend 仅用于 setBackend; 请先切换模式,再操作页面');
+ }
+ const runtime = getRuntime(deps);
// Block non-web schemes at the boundary: navigate/open to file:// /
// chrome:// / data: would let the agent reach local files or browser
// internals. Only the scheme is constrained — localhost/private HTTP
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index fe19ae40c5..dc42cc6ee4 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -527,6 +527,8 @@ export type ControlWorkerAgent = 'claude-code' | 'codex' | 'pi';
/** Browser automation MCP host deps. Core browser execution is injected by host. */
export interface BrowserMcpDeps {
getRuntime(): BrowserControlRuntime;
+ /** Switch the host-wide, persisted automation target; returns the actual mode. */
+ setBackend?(backend: 'external' | 'rsb-webview'): Promise<'external' | 'rsb-webview'>;
/** Whether the active backend accepts managed resource downloads. */
supportsResourceDownloads?(): boolean;
/** Whether the active backend accepts semantic element queries. */