状态:历史规划,未实现。 本文拟议的
automationSurface/browser_use模块在当前分支不存在, 不可据此判断现行浏览器自动化能力。当前产品 CUA 权限边界见 ZCode CUA Permission Broker。For agentic workers: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: 让 zcode-cli 内模型可以在受控开关开启后,通过内置 browser_use session-injected MCP 操作 z-code 桌面内置浏览器,并为未来 iOS Simulator、Android Emulator 等可视化自动化实例复用同一套 session/instance 管理结构。
Architecture: 采用内置 session-injected MCP,而不是普通 official plugin。Host/service 层按 ZCode task/session 创建 AutomationSurfaceSession,按需注入 per-session loopback HTTP MCP;桌面 main 只承载 Electron WebContents/platform provider,UI 负责 retained/visible view 渲染。browser 是第一个 AutomationSurfaceProvider,未来 ios-simulator、android-emulator 只新增 provider 与 tool adapter,不重做 session 管理。
Tech Stack: TypeScript, Electron webview, React, Zustand, zod, ZCode Protocol, host/main postMessage bridge, zcode-cli HTTP MCP transport, Vitest, WebdriverIO/Electron e2e.
browser_use 是内置 session-injected MCP,但必须有开关:
AppSettings.automationSurface.browserUse.enabled 控制是否给新建/恢复的 ZCode session 注入内置 MCP。AppSettings.automationSurface.browserUse.autoOpenOnToolCall 控制 tool call 是否自动把对应 view 展示到 side pane。enabled=false、autoOpenOnToolCall=true;开发/测试可用 ZCODE_BROWSER_USE_MCP=1 强制开启,用 ZCODE_BROWSER_USE_MCP=0 强制关闭。browser_use tool。跨 session 管理必须通用化:
AutomationSurfaceSession。AutomationSurfaceSession 可以挂多个 AutomationSurfaceInstance,当前只挂 kind="browser",未来可以挂 kind="ios-simulator" / kind="android-emulator"。workspaceKey = workspaceIdentity?.trim() || workspacePath、taskId/sessionId、surface kind 和 instanceId,不能复用当前 human browser 的 workspace 级 side pane memory。z-ai-pc 的方向可迁移,但不能照搬:
registerBrowserRuntime 风格,改为 z-code DI;BrowserRuntime 提升为通用 AutomationSurfaceRuntime;active/visible 不能只按裸 sessionID,必须带 workspace identity、clientMode;Electron preload 例外必须限定 partition;mobile /remote 只能 attach 现有 host/runtime,不能独立启动。Main 只做平台调度:窗口聚焦、WebContents attach、webview preload 放行、截图和 provider command dispatch。它不拥有 ZCode task/session、stream、queue、snapshot 业务状态。Host/services 拥有 automation session registry、feature policy、MCP server 生命周期、权限摘要、workspace identity 隔离和 ZCode Protocol MCP 注入。UI 不直接调用 Repo,不直接接触 Electron WebContents;UI 通过 IPlatformService/preload bridge 渲染 retained view、attach webview、订阅 platform event。desktop-continuous 主链路;mobile /remote 保持 web-remote-replayable,只通过 shared-host attachment 使用桌面已有 host,不启动独立 browser/simulator runtime。packages/ui/src/logger.ts;services 用 createServiceLogger(scope);高频 command/event trace 用 debug,生命周期/开关决策用 info。DESIGN.md;所有新增 UI 文案必须走 i18n,同时兼容浅色/深色主题和桌面/手机 Web 布局。pnpm typecheck 和 pnpm lint。packages/ui/src/EmbeddedBrowserPane.tsx + packages/ui/src/EmbeddedBrowserPaneParts.tsx。packages/desktop/src/main/desktopWindowChrome.ts 当前会删除所有 webview preload 并强制 sandbox;automation webview 必须做 partition-scoped 例外。BrowserRuntime 接口每个方法带 sessionID,desktop runtime 内部 Map<string, BrowserSession>,MCP server 是 per-session loopback HTTP。packages/shared/src/automationSurface.ts
AutomationSurfaceKind、AutomationSurfaceSessionRef、AutomationSurfaceInstanceRef、event、command/result、feature policy schema。packages/shared/src/browserUse.ts
browser_use MCP server/tool 常量、browser tool input/result schema、browser-specific DOM snapshot 类型。packages/shared/src/protocol.ts
AppSettings 增加 automationSurface.browserUse.enabled 和 autoOpenOnToolCall。packages/shared/src/validationAppSettings.ts
packages/shared/src/zcode-protocol/index.ts
zcodeSessionCreateParamsSchema / zcodeSessionResumeParamsSchema 增加可选 mcpServers。packages/shared/src/mcp.ts
packages/shared/src/channels.ts
packages/shared/src/platform.ts
IPlatformService 增加 automation surface platform API。packages/shared/src/index.ts
packages/services/src/automation-surface/automationSurface.ts
IAutomationSurfaceService descriptor。packages/services/src/automation-surface/automationSurfaceService.ts
packages/services/src/automation-surface/automationSurfaceFeaturePolicy.ts
packages/services/src/automation-surface/automationSurfaceMcpServer.ts
packages/services/src/automation-surface/browserUseTool.ts
browser_use.browser tool adapter,解析参数、申请权限、调用 AutomationSurfaceService.executeBrowserCommand()。packages/services/src/automation-surface/automationSurfaceHostBridge.ts
parentPort 向 desktop main 发 platform request,并等待 requestId 对应 response。packages/services/src/node.ts
IAutomationSurfaceService,把 parentPort 注入 host bridge;remote/web unsupported 时返回 disabled policy。packages/services/src/accessor.ts
automationSurfaceService。packages/services/src/index.ts
packages/services/src/zcode-agent/zcodeTaskServiceAdapter.ts
packages/services/src/session/zcodeTaskService.ts
mcpServers?: ZCodeAgentMcpServer[] contract,并补中文注释说明内置 MCP 只能由 host 注入。apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-operations.ts
mcpServers 并合并进 runtimeConfig。apps/zcode-cli/packages/bootstrap/src/app/runtime-config.ts
plugin/config < explicit injected,保证内置 per-session server 优先。apps/zcode-cli/packages/bootstrap/tests/zcode-protocol-session-mcp.test.ts
packages/desktop/src/main/automationSurface/runtime.ts
surfaceSessionId / instanceId 管 active、visible、provider dispatch。packages/desktop/src/main/automationSurface/browser/browserProvider.ts
packages/desktop/src/main/automationSurface/browser/browserSession.ts
BrowserSession 思路。packages/desktop/src/main/automationSurface/browser/browserStore.ts
packages/desktop/src/main/automationSurface/browser/guestChannel.ts
packages/desktop/src/main/automationSurface/security.ts
packages/desktop/src/main/desktopWindowChrome.ts
packages/desktop/src/main/desktopHostProcess.ts
packages/desktop/src/main/index.ts
packages/desktop/src/preload/index.ts
window.zcode.automationSurface.* 给 renderer。packages/desktop/src/renderer/src/main.tsx
desktopPlatform 实现 automation surface API。packages/desktop/src/preload/automation-surface-browser-webview.ts
packages/desktop/src/preload/automationSurfaceBrowserDom.ts
automation-surface-browser-webview.js。packages/ui/src/lib/workspaceSidePane.ts
AutomationSurfaceSidePaneTab,不要把 automation tab 混进 human BrowserSidePaneTab。packages/ui/src/lib/taskSidePaneMemory.ts
packages/ui/src/automation-surface/AutomationSurfaceHost.tsx
packages/ui/src/automation-surface/BrowserAutomationPane.tsx
EmbeddedBrowserPane 抽 hook。packages/ui/src/EmbeddedBrowserPane.tsx
packages/ui/src/EmbeddedBrowserPaneParts.tsx
packages/ui/src/hooks/useAppPanels.ts
packages/ui/src/app-shell/AnimatedSidePanePanel.tsx
automation-surface tab。packages/web/src/main.tsx
docs/browser-use-mcp.md
docs/web-remote-control/task-realtime-sync.md
Files:
DESIGN.mddocs/web-remote-control/web-remote-control-architecture.mddocs/web-remote-control/task-realtime-sync.mddocs/web-remote-control-task-command-queue.mdpackages/shared/src/platform.tsRead: packages/desktop/src/main/desktopWindowChrome.ts
[ ] Step 1: 读取 UI / 远控 / platform 边界文档
Run:
sed -n '1,260p' DESIGN.md
sed -n '1,260p' docs/web-remote-control/web-remote-control-architecture.md
sed -n '1,260p' docs/web-remote-control/task-realtime-sync.md
sed -n '1,260p' docs/web-remote-control-task-command-queue.md
sed -n '180,260p' packages/shared/src/platform.ts
sed -n '180,230p' packages/desktop/src/main/desktopWindowChrome.ts
Expected: 确认 UI 设计规则、desktop continuous / mobile replayable 边界、IPlatformService 只放平台操作、当前 webview preload 被统一删除。
Run:
git status --short
Expected: 只看到与当前任务相关的变更;实现时不得覆盖用户未提交改动。
Files:
packages/shared/src/automationSurface.tspackages/shared/src/browserUse.tspackages/shared/src/protocol.tspackages/shared/src/validationAppSettings.tspackages/shared/src/index.tspackages/shared/test/automationSurfaceSettings.test.tsTest: packages/shared/test/automationSurfaceRefs.test.ts
[ ] Step 1: 写 settings failing test
Create packages/shared/test/automationSurfaceSettings.test.ts:
import { describe, expect, it } from "vitest";
import { appSettingsPatchSchema, appSettingsSchema } from "../src/validation.js";
describe("automation surface settings", () => {
it("defaults browser_use injection off and auto-open on", () => {
const settings = appSettingsSchema.parse({});
expect(settings.automationSurface?.browserUse?.enabled).toBe(false);
expect(settings.automationSurface?.browserUse?.autoOpenOnToolCall).toBe(true);
});
it("accepts explicit browser_use settings patches", () => {
const patch = appSettingsPatchSchema.parse({
automationSurface: {
browserUse: {
enabled: true,
autoOpenOnToolCall: false,
},
},
});
expect(patch.automationSurface?.browserUse?.enabled).toBe(true);
expect(patch.automationSurface?.browserUse?.autoOpenOnToolCall).toBe(false);
});
});
Run:
pnpm vitest run packages/shared/test/automationSurfaceSettings.test.ts --runInBand
Expected: FAIL because settings schema does not contain automationSurface.
AppSettings.automationSurfaceIn packages/shared/src/protocol.ts, add:
export interface AutomationSurfaceSettings {
browserUse?: {
/** 是否给 ZCode session 注入内置 browser_use MCP。 */
enabled?: boolean;
/** tool call 触发时是否自动展开对应可视化实例。 */
autoOpenOnToolCall?: boolean;
};
}
export interface AppSettings {
// existing fields...
/** 内置可视化自动化实例开关;关闭时不启动 per-session MCP/runtime。 */
automationSurface?: AutomationSurfaceSettings;
}
In packages/shared/src/validationAppSettings.ts, add schema:
const automationSurfaceSettingsSchema = z
.object({
browserUse: z
.object({
enabled: z.boolean().default(false),
autoOpenOnToolCall: z.boolean().default(true),
})
.default({}),
})
.default({});
Add automationSurface: automationSurfaceSettingsSchema to appSettingsObjectSchema, and optional version to appSettingsPatchSchema.
Create packages/shared/src/automationSurface.ts:
import { z } from "zod";
export const automationSurfaceKindSchema = z.enum([
"browser",
"ios-simulator",
"android-emulator",
]);
export type AutomationSurfaceKind = z.infer<typeof automationSurfaceKindSchema>;
export const automationSurfaceClientModeSchema = z.enum([
"desktop-continuous",
"web-remote-replayable",
]);
export type AutomationSurfaceClientMode = z.infer<typeof automationSurfaceClientModeSchema>;
export const automationSurfaceSessionRefSchema = z
.object({
surfaceSessionId: z.string().min(1),
zcodeSessionId: z.string().min(1),
taskId: z.string().min(1),
workspacePath: z.string().min(1),
workspaceIdentity: z.string().optional(),
clientMode: automationSurfaceClientModeSchema,
})
.strict();
export type AutomationSurfaceSessionRef = z.infer<typeof automationSurfaceSessionRefSchema>;
export const automationSurfaceInstanceRefSchema = z
.object({
instanceId: z.string().min(1),
kind: automationSurfaceKindSchema,
session: automationSurfaceSessionRefSchema,
})
.strict();
export type AutomationSurfaceInstanceRef = z.infer<typeof automationSurfaceInstanceRefSchema>;
export function getAutomationSurfaceWorkspaceKey(input: {
workspacePath: string;
workspaceIdentity?: string;
}): string {
return input.workspaceIdentity?.trim() || input.workspacePath;
}
export function buildAutomationSurfaceSessionId(input: {
workspacePath: string;
workspaceIdentity?: string;
taskId: string;
}): string {
const workspaceKey = getAutomationSurfaceWorkspaceKey(input);
return `${encodeURIComponent(workspaceKey)}:${encodeURIComponent(input.taskId)}`;
}
export function buildAutomationSurfaceInstanceId(input: {
surfaceSessionId: string;
kind: AutomationSurfaceKind;
ordinal?: number;
}): string {
return `${input.kind}:${input.surfaceSessionId}:${input.ordinal ?? 0}`;
}
export const automationSurfaceEventSchema = z.discriminatedUnion("type", [
z.object({ type: z.literal("open"), instance: automationSurfaceInstanceRefSchema }).strict(),
z.object({ type: z.literal("focus"), instance: automationSurfaceInstanceRefSchema }).strict(),
z
.object({
type: z.literal("state"),
instance: automationSurfaceInstanceRefSchema,
title: z.string().optional(),
url: z.string().optional(),
loading: z.boolean().optional(),
lastError: z.string().optional(),
})
.strict(),
z
.object({
type: z.literal("warning"),
instance: automationSurfaceInstanceRefSchema.optional(),
message: z.string(),
})
.strict(),
]);
export type AutomationSurfaceEvent = z.infer<typeof automationSurfaceEventSchema>;
Create packages/shared/src/browserUse.ts:
import { z } from "zod";
export const BROWSER_USE_MCP_SERVER_NAME = "browser_use";
export const BROWSER_USE_MCP_TOOL_NAME = "browser";
export const BROWSER_USE_MCP_TOKEN_HEADER = "X-ZCode-Browser-MCP-Token";
export const BROWSER_USE_PARTITION_HINT_PREFIX = "zcode-browser-use:";
export const browserUseActionSchema = z.enum([
"open",
"goto",
"snapshot",
"click",
"fill",
"type",
"press",
"wait",
"get",
"screenshot",
"visibility",
]);
export const browserUseToolInputSchema = z
.object({
action: browserUseActionSchema,
url: z.string().optional(),
ref: z.string().optional(),
selector: z.string().optional(),
value: z.string().optional(),
text: z.string().optional(),
key: z.string().optional(),
timeoutMs: z.number().int().positive().optional(),
visible: z.boolean().optional(),
})
.strict();
export type BrowserUseToolInput = z.infer<typeof browserUseToolInputSchema>;
Create packages/shared/test/automationSurfaceRefs.test.ts:
import { describe, expect, it } from "vitest";
import {
buildAutomationSurfaceInstanceId,
buildAutomationSurfaceSessionId,
getAutomationSurfaceWorkspaceKey,
} from "../src/automationSurface.js";
describe("automation surface refs", () => {
it("uses workspaceIdentity for isolation when present", () => {
expect(getAutomationSurfaceWorkspaceKey({
workspacePath: "/repo",
workspaceIdentity: "ssh://host/repo",
})).toBe("ssh://host/repo");
});
it("builds session and instance ids with task isolation", () => {
const surfaceSessionId = buildAutomationSurfaceSessionId({
workspacePath: "/repo",
workspaceIdentity: "ssh://host/repo",
taskId: "task-1",
});
expect(surfaceSessionId).toContain("task-1");
expect(buildAutomationSurfaceInstanceId({ surfaceSessionId, kind: "browser" })).toContain("browser");
});
});
Export from packages/shared/src/index.ts.
Run:
pnpm vitest run packages/shared/test/automationSurfaceSettings.test.ts packages/shared/test/automationSurfaceRefs.test.ts --runInBand
Expected: PASS.
[ ] Step 6: Commit Task 1
git add packages/shared/src/automationSurface.ts packages/shared/src/browserUse.ts packages/shared/src/protocol.ts packages/shared/src/validationAppSettings.ts packages/shared/src/index.ts packages/shared/test/automationSurfaceSettings.test.ts packages/shared/test/automationSurfaceRefs.test.ts
git commit -m "feat: add automation surface settings and contracts"
Files:
packages/shared/src/mcp.tspackages/shared/src/zcode-protocol/index.tsapps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-operations.tsapps/zcode-cli/packages/bootstrap/src/app/runtime-config.tsTest: apps/zcode-cli/packages/bootstrap/tests/zcode-protocol-session-mcp.test.ts
[ ] Step 1: Add failing bootstrap test
Create apps/zcode-cli/packages/bootstrap/tests/zcode-protocol-session-mcp.test.ts with a create/resume operation fixture that includes:
const mcpServers = [
{
name: "browser_use",
type: "http" as const,
url: "http://127.0.0.1:43210/mcp",
headers: [{ name: "X-ZCode-Browser-MCP-Token", value: "secret" }],
},
];
Assert runtime config contains:
expect(runtimeConfig.mcp?.servers.browser_use).toMatchObject({
type: "http",
url: "http://127.0.0.1:43210/mcp",
headers: { "X-ZCode-Browser-MCP-Token": "secret" },
});
Run:
pnpm vitest run apps/zcode-cli/packages/bootstrap/tests/zcode-protocol-session-mcp.test.ts --runInBand
Expected: FAIL because create/resume params do not accept mcpServers.
In packages/shared/src/mcp.ts, add/export a zod schema for stdio/http/sse MCP servers. For HTTP:
export const zcodeAgentMcpHeaderSchema = z.object({
name: z.string().min(1),
value: z.string(),
});
export const zcodeAgentHttpMcpServerSchema = z.object({
name: z.string().min(1),
type: z.literal("http"),
url: z.string().url(),
headers: z.array(zcodeAgentMcpHeaderSchema).optional(),
timeoutMs: z.number().int().positive().optional(),
enabled: z.boolean().optional(),
});
Include existing stdio/sse shapes if they already exist; do not duplicate type names.
In packages/shared/src/zcode-protocol/index.ts, add:
mcpServers: z.array(zcodeAgentMcpServerSchema).optional(),
to both zcodeSessionCreateParamsSchema and zcodeSessionResumeParamsSchema.
In apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-operations.ts, convert array headers to runtime config object:
function headerArrayToRecord(headers: { name: string; value: string }[] | undefined) {
return headers ? Object.fromEntries(headers.map((entry) => [entry.name, entry.value])) : undefined;
}
Then merge into runtime config.
In apps/zcode-cli/packages/bootstrap/src/app/runtime-config.ts, enforce:
// 内置 session-injected MCP 必须最后合并,避免被用户全局 MCP 配置覆盖 token/url。
const mergedMcpServers = {
...pluginMcpServers,
...configuredMcpServers,
...explicitInjectedMcpServers,
};
Run:
pnpm vitest run apps/zcode-cli/packages/bootstrap/tests/zcode-protocol-session-mcp.test.ts --runInBand
Expected: PASS.
Commit:
git add packages/shared/src/mcp.ts packages/shared/src/zcode-protocol/index.ts apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-operations.ts apps/zcode-cli/packages/bootstrap/src/app/runtime-config.ts apps/zcode-cli/packages/bootstrap/tests/zcode-protocol-session-mcp.test.ts
git commit -m "feat: support injected mcp servers in zcode protocol"
Files:
packages/services/src/automation-surface/automationSurface.tspackages/services/src/automation-surface/automationSurfaceFeaturePolicy.tspackages/services/src/automation-surface/automationSurfaceHostBridge.tspackages/services/src/automation-surface/automationSurfaceMcpServer.tspackages/services/src/automation-surface/browserUseTool.tspackages/services/src/automation-surface/automationSurfaceService.tspackages/services/src/node.tspackages/services/src/accessor.tspackages/services/src/index.tspackages/services/test/automationSurfaceFeaturePolicy.test.tsTest: packages/services/test/automationSurfaceMcpServer.test.ts
[ ] Step 1: Feature policy tests
Create packages/services/test/automationSurfaceFeaturePolicy.test.ts:
import { describe, expect, it } from "vitest";
import { resolveAutomationSurfaceFeaturePolicy } from "../src/automation-surface/automationSurfaceFeaturePolicy.js";
describe("automation surface feature policy", () => {
it("keeps browser_use disabled by default", () => {
expect(resolveAutomationSurfaceFeaturePolicy({ settings: {}, env: {} }).browserUse.enabled).toBe(false);
});
it("lets env force-enable browser_use for dev and tests", () => {
expect(resolveAutomationSurfaceFeaturePolicy({
settings: {},
env: { ZCODE_BROWSER_USE_MCP: "1" },
}).browserUse.enabled).toBe(true);
});
it("lets env force-disable browser_use", () => {
expect(resolveAutomationSurfaceFeaturePolicy({
settings: { automationSurface: { browserUse: { enabled: true } } },
env: { ZCODE_BROWSER_USE_MCP: "0" },
}).browserUse.enabled).toBe(false);
});
});
Create packages/services/src/automation-surface/automationSurfaceFeaturePolicy.ts:
import type { AppSettings } from "@zcode/shared";
export interface AutomationSurfaceFeaturePolicy {
browserUse: {
enabled: boolean;
autoOpenOnToolCall: boolean;
reason?: "setting-disabled" | "env-disabled" | "unsupported-platform";
};
}
export function resolveAutomationSurfaceFeaturePolicy(input: {
settings: Partial<AppSettings>;
env: Record<string, string | undefined>;
platformSupported?: boolean;
}): AutomationSurfaceFeaturePolicy {
const forced = input.env.ZCODE_BROWSER_USE_MCP;
const browserUse = input.settings.automationSurface?.browserUse;
const platformSupported = input.platformSupported ?? true;
if (!platformSupported) {
return { browserUse: { enabled: false, autoOpenOnToolCall: false, reason: "unsupported-platform" } };
}
if (forced === "0") {
return { browserUse: { enabled: false, autoOpenOnToolCall: false, reason: "env-disabled" } };
}
if (forced === "1") {
return { browserUse: { enabled: true, autoOpenOnToolCall: browserUse?.autoOpenOnToolCall ?? true } };
}
return {
browserUse: {
enabled: browserUse?.enabled ?? false,
autoOpenOnToolCall: browserUse?.autoOpenOnToolCall ?? true,
reason: browserUse?.enabled ? undefined : "setting-disabled",
},
};
}
Create packages/services/src/automation-surface/automationSurface.ts:
import { createServiceDescriptor } from "../collection.js";
import type { AutomationSurfaceInstanceRef, AutomationSurfaceSessionRef } from "@zcode/shared";
export interface PrepareAutomationSurfaceSessionResult {
mcpServers: Array<{
name: string;
type: "http";
url: string;
headers: { name: string; value: string }[];
}>;
instances: AutomationSurfaceInstanceRef[];
}
export interface IAutomationSurfaceService {
prepareSession(input: {
session: AutomationSurfaceSessionRef;
requestedKinds: Array<"browser">;
}): Promise<PrepareAutomationSurfaceSessionResult>;
disposeSession(session: AutomationSurfaceSessionRef): Promise<void>;
}
export const IAutomationSurfaceService =
createServiceDescriptor<IAutomationSurfaceService>("automationSurfaceService");
Create packages/services/src/automation-surface/automationSurfaceHostBridge.ts with a requestId map over parentPort.
Required request shape:
{
type: HostResponseTypes.AutomationSurfacePlatformRequest,
requestId,
command: "ensure" | "execute" | "dispose",
instance,
payload,
}
Required response shape:
{
type: HostMessageTypes.AutomationSurfacePlatformResponse,
requestId,
ok,
result,
error,
}
Add timeout default 30_000ms and debug logs only.
Create automationSurfaceMcpServer.ts modeled after z-ai-pc's per-session server:
127.0.0.1 port 0X-ZCode-Browser-MCP-Tokeninitialize, tools/list, tools/call, ping{ name: "browser", title: "Browser Use" }30_000msAdd test packages/services/test/automationSurfaceMcpServer.test.ts for token rejection, tools/list, invalid tool, and screenshot image block.
Create automationSurfaceService.ts:
ISettingServicemcpServersMap<surfaceSessionId, Handle>ensure so desktop can prepare retained viewModify packages/services/src/node.ts, accessor.ts, and index.ts to register/export service.
Run:
pnpm vitest run packages/services/test/automationSurfaceFeaturePolicy.test.ts packages/services/test/automationSurfaceMcpServer.test.ts --runInBand
pnpm typecheck
Expected: PASS.
Commit:
git add packages/services/src/automation-surface packages/services/src/node.ts packages/services/src/accessor.ts packages/services/src/index.ts packages/services/test/automationSurfaceFeaturePolicy.test.ts packages/services/test/automationSurfaceMcpServer.test.ts
git commit -m "feat: add automation surface service"
Files:
packages/shared/src/channels.tspackages/desktop/src/main/automationSurface/runtime.tspackages/desktop/src/main/automationSurface/security.tspackages/desktop/src/main/desktopHostProcess.tspackages/desktop/src/main/index.tsTest: packages/desktop/test/automationSurfaceRuntime.test.ts
[ ] Step 1: Add host/main message types
In packages/shared/src/channels.ts, add:
AutomationSurfacePlatformRequest: "automation-surface-platform-request",
AutomationSurfacePlatformEvent: "automation-surface-platform-event",
to HostResponseTypes, and:
AutomationSurfacePlatformResponse: "automation-surface-platform-response",
to HostMessageTypes.
Add comments in Chinese explaining these are host/main platform dispatch messages and do not carry ZCode stream state.
Create packages/desktop/test/automationSurfaceRuntime.test.ts:
import { describe, expect, it } from "vitest";
import {
isAllowedAutomationSurfaceUrl,
parseAutomationSurfacePartitionHint,
} from "../src/main/automationSurface/security.js";
describe("automation surface desktop security", () => {
it("only parses dedicated partition hints", () => {
expect(parseAutomationSurfacePartitionHint("zcode-browser-use:abc")).toEqual({
kind: "browser",
instanceId: "abc",
});
expect(parseAutomationSurfacePartitionHint("persist:zcode-embedded-browser")).toBeNull();
});
it("blocks local file and script navigation for browser provider", () => {
expect(isAllowedAutomationSurfaceUrl("about:blank")).toBe(true);
expect(isAllowedAutomationSurfaceUrl("https://example.com")).toBe(true);
expect(isAllowedAutomationSurfaceUrl("file:///Users/me/.ssh/id_rsa")).toBe(false);
expect(isAllowedAutomationSurfaceUrl("javascript:alert(1)")).toBe(false);
});
});
Create packages/desktop/src/main/automationSurface/security.ts:
import { BROWSER_USE_PARTITION_HINT_PREFIX } from "@zcode/shared";
export function parseAutomationSurfacePartitionHint(raw: string | undefined) {
if (!raw?.startsWith(BROWSER_USE_PARTITION_HINT_PREFIX)) {
return null;
}
const instanceId = decodeURIComponent(raw.slice(BROWSER_USE_PARTITION_HINT_PREFIX.length));
return instanceId ? { kind: "browser" as const, instanceId } : null;
}
export function isAllowedAutomationSurfaceUrl(rawUrl: string): boolean {
try {
const url = new URL(rawUrl);
return url.protocol === "about:" || url.protocol === "http:" || url.protocol === "https:";
} catch {
return false;
}
}
Create packages/desktop/src/main/automationSurface/runtime.ts:
instances = new Map<string, AutomationSurfaceInstanceRef>()activeInstanceId and visibleInstanceIdensure(instance), execute(instance, command, payload), setVisible(instanceId | null), dispose(instance)kind="browser" to browser provider once Task 5 landsAutomationSurfacePlatformEventDo not import services or ZCode session modules.
In packages/desktop/src/main/desktopHostProcess.ts, handle HostResponseTypes.AutomationSurfacePlatformRequest:
const response = await automationSurfaceRuntime.handleHostRequest(result.data);
hostProcess.postMessage({
type: HostMessageTypes.AutomationSurfacePlatformResponse,
requestId: result.data.requestId,
ok: true,
result: response,
});
On error, return { ok: false, error }. Keep logs at debug for per-command traffic.
Run:
pnpm vitest run packages/desktop/test/automationSurfaceRuntime.test.ts --runInBand
pnpm typecheck
Expected: PASS.
Commit:
git add packages/shared/src/channels.ts packages/desktop/src/main/automationSurface packages/desktop/src/main/desktopHostProcess.ts packages/desktop/src/main/index.ts packages/desktop/test/automationSurfaceRuntime.test.ts
git commit -m "feat: add desktop automation surface runtime"
Files:
packages/desktop/src/main/automationSurface/browser/browserProvider.tspackages/desktop/src/main/automationSurface/browser/browserSession.tspackages/desktop/src/main/automationSurface/browser/browserStore.tspackages/desktop/src/main/automationSurface/browser/guestChannel.tspackages/desktop/src/preload/automation-surface-browser-webview.tspackages/desktop/src/preload/automationSurfaceBrowserDom.tspackages/desktop/src/main/desktopWindowChrome.tspackages/desktop/test/browserAutomationProvider.test.tsTest: packages/desktop/test/browserAutomationPreload.test.ts
[ ] Step 1: Port z-ai-pc BrowserSession with z-code constraints
Implement browser provider with these differences from z-ai-pc:
AutomationSurfaceInstanceRef.instanceId, not bare sessionIDautomationSurface.browser.instances.${instanceId}about/http/httpswebview preload exception only when partition hint matches BROWSER_USE_PARTITION_HINT_PREFIX
[ ] Step 2: Add guest preload DOM dispatcher
Create DOM helpers in automationSurfaceBrowserDom.ts:
export function listInteractiveElements(root: ParentNode = document): Element[] {
return Array.from(
root.querySelectorAll(
'a[href],button,input,textarea,select,[role="button"],[role="link"],[tabindex],[contenteditable="true"]',
),
).filter((element) => {
const rect = element.getBoundingClientRect();
const style = window.getComputedStyle(element);
return rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden";
});
}
The preload listens for zcode:automation-surface:browser-call, executes snapshot/click/fill/type/press/wait/get, and replies with zcode:automation-surface:browser-reply.
In desktopWindowChrome.ts, before the existing preload deletion:
const automationPartition = parseAutomationSurfacePartitionHint(params.partition);
if (automationPartition?.kind === "browser") {
// 修复原因:browser_use MCP 需要受控 guest preload 执行 DOM snapshot/click/fill。
// 只对 automation partition 开放,普通内置浏览器仍删除 preload,避免扩大页面权限面。
webPreferences.preload = automationSurfaceBrowserPreloadPath;
webPreferences.contextIsolation = true;
webPreferences.nodeIntegration = false;
webPreferences.webSecurity = true;
webPreferences.sandbox = false;
params.partition = browserProvider.resolvePersistPartition(automationPartition.instanceId);
return;
}
If sandbox-compatible ESM preload works in current Electron version, prefer sandbox=true; otherwise keep sandbox=false only here and retain the Chinese reason comment.
Run:
pnpm vitest run packages/desktop/test/browserAutomationProvider.test.ts packages/desktop/test/browserAutomationPreload.test.ts --runInBand
pnpm typecheck
Expected: PASS.
[ ] Step 5: Commit Task 5
git add packages/desktop/src/main/automationSurface/browser packages/desktop/src/preload/automation-surface-browser-webview.ts packages/desktop/src/preload/automationSurfaceBrowserDom.ts packages/desktop/src/main/desktopWindowChrome.ts packages/desktop/test/browserAutomationProvider.test.ts packages/desktop/test/browserAutomationPreload.test.ts
git commit -m "feat: add browser automation surface provider"
Files:
packages/ui/src/lib/workspaceSidePane.tspackages/ui/src/lib/taskSidePaneMemory.tspackages/ui/src/automation-surface/AutomationSurfaceHost.tsxpackages/ui/src/automation-surface/BrowserAutomationPane.tsxpackages/ui/src/hooks/useAppPanels.tspackages/ui/src/app-shell/AnimatedSidePanePanel.tsxpackages/desktop/src/preload/index.tspackages/desktop/src/renderer/src/main.tsxpackages/web/src/main.tsxpackages/ui/test/automationSurfaceSidePane.test.tsxTest: packages/ui/test/automationSurfaceWebFallback.test.tsx
[ ] Step 1: Read DESIGN.md
Run:
sed -n '1,260p' DESIGN.md
Expected: Confirm spacing, radius, theme, responsive and i18n rules before UI edits.
In workspaceSidePane.ts, add:
export interface AutomationSurfaceSidePaneTab {
id: string;
type: "automation-surface";
kind: AutomationSurfaceKind;
instanceId: string;
surfaceSessionId: string;
controlledByTaskId: string;
openedAt?: number;
title?: string | null;
}
Add helper openAutomationSurfaceSidePane(current, tab) that reuses the same instanceId.
In taskSidePaneMemory.ts, filter restored automation tabs whose controlledByTaskId does not match the active task. Human browser/git/code-viewer remain workspace-level memory.
Create AutomationSurfaceHost.tsx:
platform.onAutomationSurfaceEventkind="browser" even when side pane is collapsedautoOpenOnToolCall=true, opens/focuses side pane tab on open/focus eventautoOpenOnToolCall=false, keeps instance hidden but attachedDo not use visible instructional text; use existing tooltips/icons when controls are visible.
Create BrowserAutomationPane.tsx by extracting reusable parts from EmbeddedBrowserPane:
${BROWSER_USE_PARTITION_HINT_PREFIX}${encodeURIComponent(instanceId)}dom-ready, call platform.attachAutomationSurfaceView({ instance, webContentsId })platform.detachAutomationSurfaceView(instance)all logs use logger.debug/info/warn
[ ] Step 5: Wire platform preload/web fallback
Expose window.zcode.automationSurface in desktop preload and map through desktopPlatform.
In packages/web/src/main.tsx, return unsupported:
automationSurface: {
ensureView: async () => ({ available: false, reason: "unsupported-platform" }),
onEvent: () => () => undefined,
}
Add Chinese comment:
// 手机 /remote 只 attach 桌面已有 host/runtime,不在 Web 端启动独立 automation surface。
Run:
pnpm vitest run packages/ui/test/automationSurfaceSidePane.test.tsx packages/ui/test/automationSurfaceWebFallback.test.tsx --runInBand
pnpm typecheck
Expected: PASS.
Commit:
git add packages/ui/src/lib/workspaceSidePane.ts packages/ui/src/lib/taskSidePaneMemory.ts packages/ui/src/automation-surface packages/ui/src/hooks/useAppPanels.ts packages/ui/src/app-shell/AnimatedSidePanePanel.tsx packages/desktop/src/preload/index.ts packages/desktop/src/renderer/src/main.tsx packages/web/src/main.tsx packages/ui/test/automationSurfaceSidePane.test.tsx packages/ui/test/automationSurfaceWebFallback.test.tsx
git commit -m "feat: render retained automation surface views"
Files:
packages/services/src/zcode-agent/zcodeTaskServiceAdapter.tspackages/services/src/session/zcodeTaskService.tspackages/ui/src/lib/zcodeSessionPromptControl.tspackages/services/test/zcodeTaskBrowserUseInjection.test.tsTest: packages/ui/test/zcodeSessionPromptControl.test.ts
[ ] Step 1: Add failing service test
Create packages/services/test/zcodeTaskBrowserUseInjection.test.ts by copying these existing helper functions from packages/services/test/zcodeLegacyTaskCompatTaskIndex.test.ts: useTempDataBaseDir(), makeSnapshot(), and createAgentMock(). The test constructs createZCodeTaskServiceAdapter() with a fake automationSurfaceService, calls service.createTask(), and asserts the injected MCP server reaches zcodeAgentService.createSession().
import { afterEach, describe, expect, it, vi } from "vitest";
import { setDataBaseDir } from "../src/paths.js";
import { createZCodeTaskServiceAdapter } from "../src/zcode-agent/zcodeTaskServiceAdapter.js";
import { createZCodeTaskIndexSyncer } from "../src/zcode-agent/zcodeTaskIndexSyncer.js";
import { TaskIndexRepo } from "../src/session/taskIndexRepo.js";
afterEach(() => {
setDataBaseDir(null);
});
describe("browser_use MCP injection", () => {
it("injects browser_use only when automation surface policy enables it", async () => {
useTempDataBaseDir();
const createSession = vi.fn(async () => makeSnapshot({
sessionId: "task-browser",
workspacePath: "/repo",
workspaceIdentity: "ssh://host/repo",
}));
const taskIndexRepo = new TaskIndexRepo();
const { agent: zcodeAgentService } = createAgentMock();
vi.mocked(zcodeAgentService.createSession).mockImplementation(createSession);
const taskIndexSyncer = createZCodeTaskIndexSyncer({
agentService: zcodeAgentService,
taskIndexRepo,
});
const automationSurfaceService = {
prepareSession: vi.fn(async () => ({
mcpServers: [{
name: "browser_use",
type: "http" as const,
url: "http://127.0.0.1:4567/mcp",
headers: [{ name: "X-ZCode-Browser-MCP-Token", value: "secret" }],
}],
instances: [],
})),
};
const service = createZCodeTaskServiceAdapter({
zcodeAgentService,
taskIndexRepo,
taskIndexSyncer,
automationSurfaceService,
});
await service.createTask({
workspacePath: "/repo",
workspaceIdentity: "ssh://host/repo",
provider: "glm",
});
expect(automationSurfaceService.prepareSession).toHaveBeenCalledWith(
expect.objectContaining({
requestedKinds: ["browser"],
}),
);
expect(createSession).toHaveBeenCalledWith(
expect.objectContaining({
workspacePath: "/repo",
workspaceIdentity: "ssh://host/repo",
mcpServers: [
expect.objectContaining({
name: "browser_use",
type: "http",
}),
],
}),
);
});
});
In zcodeTaskServiceAdapter.ts, before protocol create/resume:
const surfaceSessionId = buildAutomationSurfaceSessionId({
workspacePath: params.workspacePath,
workspaceIdentity: params.workspaceIdentity,
taskId: params.taskId,
});
const automation = await automationSurfaceService.prepareSession({
session: {
surfaceSessionId,
zcodeSessionId: params.taskId,
taskId: params.taskId,
workspacePath: params.workspacePath,
workspaceIdentity: params.workspaceIdentity,
clientMode: params.clientMode ?? "desktop-continuous",
},
requestedKinds: ["browser"],
});
const mcpServers = [...(params.mcpServers ?? []), ...automation.mcpServers];
Do not inject for clientMode === "web-remote-replayable" unless the call is executing inside the already-attached desktop host. Add a Chinese comment explaining the remote boundary.
If packages/ui/src/lib/zcodeSessionPromptControl.ts still has a direct createSession/resumeSession path, include mcpServers in both calls.
Run:
pnpm vitest run packages/services/test/zcodeTaskBrowserUseInjection.test.ts packages/ui/test/zcodeSessionPromptControl.test.ts --runInBand
pnpm typecheck
Expected: PASS.
Commit:
git add packages/services/src/zcode-agent/zcodeTaskServiceAdapter.ts packages/services/src/session/zcodeTaskService.ts packages/ui/src/lib/zcodeSessionPromptControl.ts packages/services/test/zcodeTaskBrowserUseInjection.test.ts packages/ui/test/zcodeSessionPromptControl.test.ts
git commit -m "feat: inject browser use mcp per zcode session"
Files:
packages/services/src/automation-surface/browserUseTool.tspackages/services/src/automation-surface/automationSurfaceService.tspackages/ui/src/SettingsPage.tsxpackages/ui/src/i18n/locales/zh-CN.tspackages/ui/src/i18n/locales/en-US.tspackages/services/test/browserUsePermission.test.tsTest: packages/ui/test/automationSurfaceSettingsUi.test.tsx
[ ] Step 1: Add permission tests
Test cases:
goto https://example.com produces permission summary containing origin.screenshot and snapshot use debug logs for high-frequency details.file:// and javascript: are rejected before reaching provider.closing/dispose errors log warn, not error, when recoverable.
[ ] Step 2: Implement permission and logging
In browserUseTool.ts, route dangerous actions through existing permission/elicitation flow. Use concise summaries:
{
permission: "browser_use",
patterns: [`browser:${origin}`],
description: `Allow browser_use to navigate ${origin}`,
}
Do not log raw DOM snapshot or typed text at info.
Add settings rows:
Use SettingsRow, existing Switch components, and i18n strings. No standalone marketing copy.
Run:
pnpm vitest run packages/services/test/browserUsePermission.test.ts packages/ui/test/automationSurfaceSettingsUi.test.tsx --runInBand
pnpm typecheck
Expected: PASS.
Commit:
git add packages/services/src/automation-surface/browserUseTool.ts packages/services/src/automation-surface/automationSurfaceService.ts packages/ui/src/SettingsPage.tsx packages/ui/src/i18n/locales/zh-CN.ts packages/ui/src/i18n/locales/en-US.ts packages/services/test/browserUsePermission.test.ts packages/ui/test/automationSurfaceSettingsUi.test.tsx
git commit -m "feat: add browser use permissions and settings"
Files:
packages/desktop/test/browserUseMcp.e2e.test.ts or WebdriverIO spec under current desktop e2e structureModify: package test script if needed
[ ] Step 1: Add e2e scenario
Scenario:
ZCODE_BROWSER_USE_MCP=1browser tool with gotoautoOpenOnToolCall=true opens side panesnapshot, click, screenshotAdd test or manual verification note:
/remote attaches shared hostreplayable task snapshot semantics unchanged
[ ] Step 3: Run focused e2e
Run the repo's desktop e2e command. If no stable command exists, run the closest WebdriverIO/Electron command and record the exact command in docs/browser-use-mcp.md.
Expected: controlled browser opens and tool calls succeed.
[ ] Step 4: Commit Task 9
git add packages/desktop/test/browserUseMcp.e2e.test.ts
git commit -m "test: cover browser use mcp desktop flow"
Files:
docs/browser-use-mcp.mdModify: docs/web-remote-control/task-realtime-sync.md
[ ] Step 1: Write architecture doc
Create docs/browser-use-mcp.md with sections:
# Browser Use MCP
## Summary
## Feature Switches
## Session And Instance Isolation
## Data Flow
## Permission Model
## Desktop Continuous Boundary
## Mobile Remote Replayable Boundary
## Provider Extension Guide
## Verification
Provider extension guide must explain how iOS/Android add a provider without changing session manager:
AutomationSurfaceService
-> AutomationSurfaceProvider(kind)
-> platform runtime
-> retained UI view
-> optional MCP/tool adapter
In docs/web-remote-control/task-realtime-sync.md, add:
automation surface events are UI/platform events, not replayable stream source of truth
[ ] Step 3: Full validation
Run:
pnpm typecheck
pnpm lint
Expected: PASS.
[ ] Step 4: Commit Task 10
git add docs/browser-use-mcp.md docs/web-remote-control/task-realtime-sync.md
git commit -m "docs: document browser use mcp architecture"
sequenceDiagram
participant UI as Renderer UI
participant Host as Host Services
participant Agent as zcode app-server
participant MCP as per-session browser_use MCP
participant Main as Desktop Main Runtime
participant View as Retained Webview
UI->>Host: create/resume ZCode session
Host->>Host: resolve feature policy
Host->>MCP: start loopback HTTP server when enabled
Host->>Agent: session/new or session/load with injected mcpServers
Agent->>MCP: tools/call browser
MCP->>Host: executeBrowserCommand(sessionRef, instanceRef)
Host->>Main: AutomationSurfacePlatformRequest
Main->>UI: AutomationSurfaceEvent(open/focus/state)
UI->>View: mount retained browser webview
UI->>Main: attachAutomationSurfaceView(webContentsId)
Main->>View: guest preload command
View-->>Main: guest preload reply
Main-->>Host: AutomationSurfacePlatformResponse
Host-->>MCP: MCP result text/image
MCP-->>Agent: tool result
BrowserRuntime becomes provider under AutomationSurfaceRuntime.sessionID with AutomationSurfaceSessionRef.AutomationSurfaceSidePaneTab.AutomationSurfaceSession / AutomationSurfaceInstance / provider structure for browser, iOS simulator, and Android emulator.sandbox=true, keep sandbox=false only for automation partition and document the reason in code and docs.