JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
[mirror] openJiuwen-ai/jiuwenswarm#1259: fix(browser subagent): Simplified browser startup logic and fixed bro…
m056838700d1c19455a48c
diff --git a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yamlindex f6cf1be592..6e8e1fe0eb 100644--- a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml+++ b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml@@ -810,11 +810,10 @@ browser:# windows: "C:\\Users\\YOUR_USER\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"# macos: "/Applications/Google Chrome.app"# linux: "/usr/bin/google-chrome"- remote_debugging_address: "127.0.0.1"- remote_debugging_port: 9222- # empty means use launcher default profile path by OS- user_data_dir: ""- profile_directory: "Default"+ # Leave empty to let the managed browser driver detect Chrome.+ chrome_path: ""+ # Managed Chrome runs headless by default. Set false to show the window.+ headless: trueupdater:enabled: truediff --git a/docs/en/Browser.md b/docs/en/Browser.mdindex bf2a489f73..f2bec8287f 100644--- a/docs/en/Browser.md+++ b/docs/en/Browser.md@@ -1,273 +1,136 @@# Browser tools-## 1. Conceptual Overview+## 1. Overview-Browser tools in JiuwenSwarm enable driving a real Chrome instance for form filling, clicks, uploads, and web tasks. Users first configure Chrome path in the web UI and start the browser service; the system launches an attachable Chrome instance. When needed, the agent connects to and controls this browser.+JiuwenSwarm browser tools drive a real Chrome instance for navigation, form+filling, clicks, uploads, and other web tasks.-### 1.1 Key Capabilities+Chrome is managed by the browser agent. The user configures the Chrome+executable and display mode in the web UI, and the agent starts the browser on+the first browser task. There is no separate browser service to start from the+frontend.-The browser tools currently support the following capabilities:+The managed browser can:-- Open web pages and wait for loading-- Continue operations on already logged-in websites-- Click buttons, input text, select page elements+- Open pages and wait for loading+- Click elements, enter text, and upload files- Execute multi-step web tasks-- Reuse the same browser session to reduce repeated logins-- Read page titles, URLs, and page content when needed-- Support complex tasks like file uploads, email composition, and web form submissions+- Reuse a session and its login state+- Read page titles, URLs, and page content-### 1.2 Typical Use Cases+## 2. Quick start-- **Web Information Extraction**: Extract structured information from news sites, document pages, etc.-- **Email Operations**: Log in to email to send messages, check inbox, download attachments-- **Form Filling**: Automatically fill out online registration, application forms-- **Online Shopping**: Browse products, compare prices, add to cart-- **Enterprise System Operations**: Complete approvals, queries, etc. in internal systems+### 2.1 Install Chrome-## 2. Quick Start (Frontend Operations Only)+Install Google Chrome on the machine that runs JiuwenSwarm. The managed driver+normally detects a standard Chrome installation automatically.-Install Chrome first.+If Chrome is installed in a custom location, open `chrome://version`, copy the+**Executable Path**, and use it in the next step.-### 2.1 Step 1: Chrome path and profile--1. Open Chrome.-2. Visit `chrome://version`.-3. Note:- - **Executable path** → `CHROME_PATH`- - **Profile path** → confirms user data for login debugging--Where:-- Executable path is generally the complete path to `chrome.exe`.-- Profile directory helps confirm the current browser account and data directory, facilitating troubleshooting of login state or authorization issues.--### 2.2 Step 2: Open the browser service panel+### 2.2 Configure the browser1. Open the JiuwenSwarm web UI.+2. Go to **Settings** > **Browser**.+3. Optionally enter the full Chrome executable path. Leave it empty to use+ automatic detection.+4. Enable **Show browser** when you need to see or manually authenticate in the+ managed browser. Disable it for headless execution.+5. Save the settings.- --2. Go to **Settings** → **Browser service**.-3. Find the Chrome path field.-- ---### 2.3 Step 3: Set `CHROME_PATH`-1. Copy the executable path from `chrome://version`.-- --2. Paste into **CHROME_PATH** and **Save path**.--### 2.4 Step 4: Start the browser service-1. Click **Start browser service**.-2. A new Chrome window should open — that instance is controlled by the agent.--This popped-up Chrome is the browser instance that can be controlled by the agent later.--### 2.5 Step 5: Log in manually--For mail, SSO, or intranet, complete login **in that Chrome window** first.--If your tasks require website login, email authorization, enterprise system access, or using existing account states, complete the necessary manual operations in that Chrome, such as:--- Log in to Gmail / Outlook / corporate email-- Complete manual authentication via SMS, verification code, QR code scan, etc.-- Allow site access permissions-- Open the target page to be operated--### 2.6 Step 6: Use from chat--Ask the agent to open pages, fill forms, or continue logged-in flows. It uses the authorized Chrome, not a cold profile.--After completing authorization, you can ask the agent to perform browser tasks in the conversation, such as:--- Open a webpage and read information-- Continue clicking and filling forms after login-- Compose emails, upload attachments, wait for confirmation in email--When the task requires a browser, the agent will control this already authorized Chrome, not create a completely stateless browser again.--## 3. Usage Tips+Changing the display mode restarts the browser runtime when necessary so the+next task uses the selected mode.-To make the browser tools more stable, follow these recommendations:+### 2.3 Run a browser task-- Prefer using the real Chrome installed locally rather than a temporary browser.-- After starting the browser service, prioritize completing login and authorization in the popped-up Chrome.-- For long-flow tasks, try to maintain the same session to avoid frequently changing browser states.-- For scenarios involving email, enterprise systems, online banking, etc., it is recommended to complete manual login first before letting the agent continue operations.-- If the browser state is abnormal, restart the browser service and test again.-- Ensure `PLAYWRIGHT_CDP_URL` matches the debugging address and port in `config.yaml`.-- Keep `BROWSER_ALLOW_SHORT_TIMEOUT_OVERRIDE=0` to prevent the model from splitting browser tasks into too many short calls.+Ask the agent to open a page, extract information, fill a form, or continue an+authenticated workflow. The browser agent starts and owns Chrome automatically.-## 4. Practical Cases+In visible mode, the Chrome window appears when the first browser task starts.+Complete login, MFA, or other required manual authorization in that window, then+continue the task in the conversation.-### 4.1 Case 1: Web Information Extraction-**Task Description**: Extract news titles and summaries from a specific web page+## 3. Usage guidance-**Operation Steps**:-1. Start the browser service and complete necessary authorization-2. Enter in the conversation: "Please extract today's headline news title and summary from https://example.com/news"-3. The agent will automatically call browser tools to access the specified web page-4. The browser will parse the page content and extract the required information-5. The agent will organize the extracted information and return it to the user+- Keep the same agent session for long workflows that depend on login state.+- Use visible mode for manual login, MFA, QR codes, and authorization prompts.+- Use headless mode for tasks that do not require manual interaction.+- Do not start a separate Chrome with a fixed debugging port for normal+ JiuwenSwarm usage. The managed driver selects and injects the correct CDP+ endpoint.+- Keep `BROWSER_ALLOW_SHORT_TIMEOUT_OVERRIDE=0` unless short browser task+ timeouts are explicitly required.-### 4.2 Case 2: Email Sending (with Attachment)-**Task Description**: Send an email with attachment using Gmail+## 4. Examples-**Operation Steps**:-1. Start the browser service-2. Log in to Gmail account in the popped-up Chrome-3. Enter in the conversation: "Please send an email to [email protected], subject: Test Email, content: This is a test email, attachment: /path/to/file.pdf"-4. The agent will call browser tools to open Gmail compose page-5. The browser will automatically fill in recipient, subject, content, and upload the attachment-6. After sending is complete, the agent will notify the user that the email has been sent+### 4.1 Extract web information-> **Note**: Operation screenshots will be added after future frontend updates. Each case will display 1-2 images, mainly showing the key execution process and final results.+1. Ask: "Extract today's headlines and summaries from+ https://example.com/news."+2. The agent starts the managed browser, visits the page, and returns the+ requested information.-## 5. Backend Configuration+### 4.2 Send email with an attachment-### 5.1 Configuration Files Overview+1. Enable **Show browser** and save the setting.+2. Ask the agent to open Gmail.+3. Sign in in the managed Chrome window if required.+4. Ask the agent to compose the message and attach the file.-The browser tool configuration involves several core files that work together to configure and run the browser:+## 5. Configuration-- **`config/config.yaml`**: Mainly configures Chrome startup parameters, such as Chrome executable path, remote debugging address and port. These configurations are the foundation for browser startup.-- **`.env`**: Configures browser runtime, MCP connection, Playwright parameters, timeout settings and other environment variables that affect the browser's runtime behavior.-- **`.env.template`**: Environment variable template file containing all available environment variables and their default values, which can be used as a configuration reference.+### 5.1 `config.yaml`-The relationship between these three files is: `config/config.yaml` provides the basic parameters for browser startup, and `.env` provides the runtime environment configuration. Together, they ensure the browser tools work properly.+| Configuration | Type | Default | Description |+|---|---|---|---|+| `browser.chrome_path` | string/map | `""` | Chrome executable. Empty uses automatic detection. A map may provide OS-specific paths. |+| `browser.headless` | boolean | `true` | `false` shows the managed browser window. |-### 5.2 Browser Configuration in config.yaml+Example:-| Configuration Item | Type | Default Value | Description |-|--------------------|------|---------------|-------------|-| `browser.chrome_path` | string/map | - | Chrome executable path, can be a single string or a map by OS |-| `browser.remote_debugging_address` | string | "127.0.0.1" | Chrome remote debugging listening address |-| `browser.remote_debugging_port` | integer | 9222 | Chrome remote debugging port |-| `browser.user_data_dir` | string | "" | Chrome user data directory, use system default when empty |-| `browser.profile_directory` | string | "Default" | Chrome Profile name to use |--**Example configuration by OS**:```yamlbrowser:chrome_path:- windows: "C:\\Users\\YOUR_USER\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"- macos: "/Applications/Google Chrome.app"+ windows: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"+ macos: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"linux: "/usr/bin/google-chrome"- remote_debugging_address: "127.0.0.1"- remote_debugging_port: 9222- user_data_dir: ""- profile_directory: "Default"+ headless: true```-### 5.2 Browser Configuration in .env--#### 5.2.1 Browser MCP Wrapper Configuration--| Environment Variable | Default Value | Description |-|----------------------|---------------|-------------|-| `BROWSER_RUNTIME_MCP_ENABLED` | 1 | Whether to enable browser MCP wrapper |-| `BROWSER_RUNTIME_MCP_CLIENT_TYPE` | streamable-http | MCP client type |-| `BROWSER_RUNTIME_MCP_SERVER_ID` | playwright_runtime_wrapper | Wrapper identifier information |-| `BROWSER_RUNTIME_MCP_SERVER_NAME` | playwright-runtime-wrapper | Wrapper name |-| `BROWSER_RUNTIME_MCP_SERVER_PATH` | http://127.0.0.1:8940/mcp | Wrapper access address |-| `BROWSER_RUNTIME_MCP_TIMEOUT_S` | 300 | MCP connection or call layer timeout control |-| `BROWSER_RUNTIME_MCP_HOST` | 127.0.0.1 | Host used when automatically starting wrapper locally |-| `BROWSER_RUNTIME_MCP_PORT` | 8940 | Port used when automatically starting wrapper locally |-| `BROWSER_RUNTIME_MCP_PATH` | /mcp | Path used when automatically starting wrapper locally |-| `BROWSER_RUNTIME_MCP_COMMAND` | - | Wrapper startup command override, usually left empty |-| `BROWSER_RUNTIME_MCP_ARGS` | - | Wrapper startup arguments override, usually left empty |-| `BROWSER_RUNTIME_MCP_AUTO_SSE_FALLBACK` | 1 | Whether to allow SSE fallback in certain modes |--#### 5.2.2 Official Playwright MCP Configuration--| Environment Variable | Default Value | Description |-|----------------------|---------------|-------------|-| `PLAYWRIGHT_MCP_COMMAND` | npx | Command to start official Playwright MCP |-| `PLAYWRIGHT_MCP_ARGS` | -y @playwright/mcp@latest | Arguments to start official Playwright MCP |-| `PLAYWRIGHT_CDP_URL` | http://127.0.0.1:9222 | CDP address to connect to the started Chrome, should match debugging address and port in config.yaml |--#### 5.2.3 Timeout and Execution Strategy Configuration--| Environment Variable | Default Value | Description |-|----------------------|---------------|-------------|-| `PLAYWRIGHT_TOOL_TIMEOUT_S` | 300 | Total watchdog timeout for browser tool execution |-| `BROWSER_TIMEOUT_S` | 300 | Default long timeout for browser tasks; if the model passes a smaller timeout_s, it will be clamped to at least this value |-| `BROWSER_ALLOW_SHORT_TIMEOUT_OVERRIDE` | 0 | Whether to allow the model to shorten task timeouts, recommended to keep as 0 |--### 5.3 Recommended Minimal Configuration--To use the browser tools properly, ensure at least the following fields are correct:--**config/config.yaml**-```yaml-browser:- chrome_path: "C:\\Users\\YOUR_USER\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"- remote_debugging_address: "127.0.0.1"- remote_debugging_port: 9222- user_data_dir: ""- profile_directory: "Default"-```--**.env**-```dotenv-BROWSER_RUNTIME_MCP_ENABLED=1-BROWSER_RUNTIME_MCP_CLIENT_TYPE=streamable-http-BROWSER_RUNTIME_MCP_SERVER_PATH=http://127.0.0.1:8940/mcp-PLAYWRIGHT_MCP_COMMAND=npx-PLAYWRIGHT_MCP_ARGS=-y @playwright/mcp@latest-PLAYWRIGHT_CDP_URL=http://127.0.0.1:9222-PLAYWRIGHT_TOOL_TIMEOUT_S=300-BROWSER_TIMEOUT_S=300-BROWSER_ALLOW_SHORT_TIMEOUT_OVERRIDE=0-```--## 6. Principle and Code Architecture--### 6.1 Technical Architecture--The core flow of the current browser tools is as follows:--- **Web UI**: Provides a "Browser service" panel for configuring Chrome executable path and starting/stopping the browser service-- **Backend Application**: Starts local Chrome with remote debugging capabilities via `browser_start_client.py`-- **Browser Runtime**: Based on Playwright MCP encapsulation, browser tools communicate with the runtime via MCP client-- **Agent Call**: When the agent calls tools like `browser_run_task`, the runtime converts natural language tasks into browser operation steps-- **Session Management**: Browsers are reused by `session_id`, maintaining login state, page context, and authorization status within the same session--In simple terms:--### Frontend-- `jiuwenswarm/channels/web/frontend/src/components/BrowserPanel/index.tsx` — path, save, start service.+An empty `chrome_path` clears any previously configured binary and lets+openJiuwen detect Chrome from the system. A non-empty path is authoritative: if+it does not identify a Chrome executable, browser startup reports an error+instead of silently using another installation.-### Backend-- `app.py` — `path.get`, `path.set`, `browser.start`, etc.-- `jiuwenswarm/agents/harness/common/tools/browser_start_client.py` — Chrome launch from `config.yaml`.-- `jiuwenswarm/agents/harness/common/tools/browser_tools.py` — MCP client, auto-start wrapper.-- `jiuwenswarm/agents/harness/common/tools/browser-move/src/playwright_runtime_mcp_server.py` — MCP server.-- `.../playwright_runtime/runtime.py`, `service.py`, `agents.py`, `config.py` — runtime orchestration.+### 5.2 Advanced environment overrides-`UI config → start Chrome → runtime attaches → agent runs tasks`+Most installations do not need these variables.-### 6.2 Core Code+| Environment variable | Default | Description |+|---|---|---|+| `BROWSER_DRIVER` | `managed` in JiuwenSwarm | Browser driver mode. |+| `BROWSER_MANAGED_BINARY` | auto-detected | Direct openJiuwen runtime override. JiuwenSwarm derives it from `browser.chrome_path`. |+| `BROWSER_MANAGED_PORT` | `9333` | Port for an unkeyed managed instance. Keyed instances allocate free ports automatically. |+| `BROWSER_MANAGED_USER_DATA_DIR` | managed profile directory | Overrides the managed profile directory. |+| `BROWSER_MANAGED_ARGS` | derived from display mode | Additional Chrome startup arguments. |+| `BROWSER_MANAGED_KILL_EXISTING` | `false` | Allows the driver to terminate a matching existing Chrome before launch. Use only when profile ownership is understood. |-The core code of the browser tools is mainly distributed in the following modules:+`PLAYWRIGHT_CDP_URL` is intended for explicit remote-driver setups. It is not+required for the normal managed-browser flow.-- **Tool Management Module**: `jiuwenswarm/agents/harness/common/tools/` is the underlying module that manages all tools in the system. Browser-related tools are mainly implemented under this module.-- **Frontend Interface Module**: `jiuwenswarm/channels/web/frontend/` is responsible for user interface interaction.+## 6. Architecture-Specific file descriptions:+The browser lifecycle is:-| Module | File Path | Function Description |-|--------|-----------|----------------------|-| Frontend Browser Service Panel | `jiuwenswarm/channels/web/frontend/src/components/BrowserPanel/index.tsx` | Responsible for reading path, saving path, triggering "Start browser service" |-| Backend Application Entry | `app.py` | Provides frontend call entries like `path.get`, `path.set`, `browser.start` |-| Chrome Startup Script | `tools/browser_start_client.py` | Reads `browser.*` configuration from `config/config.yaml`, starts Chrome with remote debugging capabilities |-| Browser MCP Access | `tools/browser_tools.py` | Browser MCP wrapper access, automatic startup, client patch, configuration building |-| Browser Runtime MCP Server | `tools/browser-move/src/playwright_runtime_mcp_server.py` | Browser runtime MCP server entry |-| Browser Runtime Orchestration Layer | `tools/browser-move/src/playwright_runtime/runtime.py` | Browser runtime orchestration layer |-| Browser Task Execution | `tools/browser-move/src/playwright_runtime/service.py` | Browser task execution, session reuse, timeout guardrails |-| Browser Runtime Configuration | `tools/browser-move/src/playwright_runtime/config.py` | Playwright MCP and browser runtime configuration parsing |+`frontend settings -> agent browser task -> managed Chrome start -> task execution -> session reuse`-## 7. Summary+- The frontend `BrowserPanel` only reads and saves Chrome path and display mode.+- JiuwenSwarm maps those settings to the browser-agent runtime.+- openJiuwen's `BrowserService` and `ManagedBrowserDriver` allocate the endpoint,+ start Chrome on demand, monitor it, reuse the profile, and stop it with the+ agent lifecycle.+- The Playwright MCP endpoint is injected from the managed browser instance; it+ is not supplied by a frontend-launched browser.-The essence of browser tools is to allow the agent to execute web operations on your already authorized real Chrome; the frontend is responsible for configuration and startup, while the backend is responsible for takeover and automated execution.\ No newline at end of file+This keeps browser startup, profile ownership, endpoint allocation, and cleanup+under one lifecycle owner: the browser agent.diff --git "a/docs/zh/\346\265\217\350\247\210\345\231\250.md" "b/docs/zh/\346\265\217\350\247\210\345\231\250.md"index ed16c7d36e..56d9987618 100644--- "a/docs/zh/\346\265\217\350\247\210\345\231\250.md"+++ "b/docs/zh/\346\265\217\350\247\210\345\231\250.md"@@ -1,279 +1,122 @@# 浏览器工具说明-## 1. 概念科普-浏览器工具是 JiuwenSwarm 中用于驱动真实浏览器完成网页任务的一套能力。它适合处理需要表单填写、页面点击、文件上传、网页检索等场景。+## 1. 概述-从使用方式上看,用户先在前端页面中配置本机 Chrome 路径并启动浏览器服务。系统会拉起一个可被授权的 Chrome 浏览器实例;后续在任务需要时,Agent 会连接并操控这个浏览器完成操作。+JiuwenSwarm 浏览器工具用于驱动真实 Chrome 完成网页访问、表单填写、页面点击、+文件上传和信息提取等任务。-### 1.1 主要功能-浏览器工具目前主要支持以下能力:+Chrome 由浏览器 Agent 统一管理。用户只需在前端配置 Chrome 可执行文件和显示+模式,Agent 会在首次执行浏览器任务时自动启动浏览器,不再需要从前端单独启动+浏览器服务。-- 打开网页并等待页面加载-- 在已登录网站中继续操作-- 点击按钮、输入文本、选择页面元素-- 执行多步网页任务-- 复用同一浏览器会话,减少重复登录-- 在需要时读取页面标题、URL、页面结果-- 配合附件上传、邮件填写、网页表单提交等复杂任务--### 1.2 典型使用场景--- **网页信息提取**:从新闻网站、文档页面等提取结构化信息-- **邮件操作**:登录邮箱发送邮件、查看收件箱、下载附件-- **表单填写**:自动填写在线报名、注册、申请等表单-- **在线购物**:浏览商品、比较价格、加入购物车-- **企业系统操作**:在内部系统中完成审批、查询等任务--## 2. 快速上手(仅展示前端操作即可)--如果要在前端使用浏览器工具,请先确保本机已经安装 Chrome 浏览器。--### 2.1 步骤 1:确认 Chrome 安装路径和 Profile 目录-1. 打开 Chrome 浏览器。-2. 在地址栏输入 `chrome://version` 并回车。-3. 记录以下两个信息:- - **可执行文件路径**:用于填写 `CHROME_PATH`- - **个人资料路径 / Profile 路径**:用于确认当前浏览器使用的用户目录和配置目录--其中:-- 可执行文件路径一般是 `chrome.exe` 的完整路径。-- Profile 目录用于帮助确认当前浏览器账户和资料目录,方便排查登录态或授权问题。--### 2.2 步骤 2:打开前端的“浏览器服务”面板--1. 打开 JiuwenSwarm 前端页面。-- --2. 进入“设置”中的“浏览器服务”区域。-3. 找到 Chrome 路径输入框。-- +浏览器工具支持:+- 打开网页并等待页面加载+- 点击元素、输入文本和上传文件+- 执行多步骤网页任务+- 复用会话及其登录状态+- 读取页面标题、URL 和页面内容-### 2.3 步骤 3:填写 CHROME_PATH-1. 将在 `chrome://version` 中看到的 Chrome 可执行文件完整路径复制出来。+## 2. 快速上手- +### 2.1 安装 Chrome-2. 粘贴到前端页面的 `CHROME_PATH` 输入框中。-3. 点击“保存路径”。+请先在运行 JiuwenSwarm 的机器上安装 Google Chrome。托管驱动通常可以自动识别+标准安装位置。-### 2.4 步骤 4:启动浏览器服务-1. 在浏览器服务面板中点击“启动浏览器服务”。-2. 系统会调用后端启动脚本,拉起一个 Chrome 浏览器。-3. 如果启动成功,通常会弹出一个新的 Chrome 窗口。+如果 Chrome 安装在自定义目录,可打开 `chrome://version`,复制“可执行文件路径”,+并在下一步中配置。-这个弹出的 Chrome 就是后续可被 Agent 操控的浏览器实例。+### 2.2 配置浏览器-### 2.5 步骤 5:在弹出的浏览器中完成必要授权-如果你的任务需要登录网站、授权邮箱、访问企业系统或使用已有账号状态,请在这个 Chrome 中完成必要的人工操作,例如:+1. 打开 JiuwenSwarm 前端。+2. 进入“设置” > “浏览器”。+3. 按需填写 Chrome 可执行文件的完整路径;留空时使用自动检测。+4. 需要观察浏览器或人工登录时,启用“显示浏览器”;无需人工操作时可关闭。+5. 保存设置。-- 登录 Gmail / Outlook / 企业邮箱-- 通过短信、验证码、扫码等人工认证-- 允许站点访问权限-- 打开需要操作的目标页面+显示模式发生变化时,系统会在必要时重启浏览器运行时,确保后续任务使用新的模式。-### 2.6 步骤 6:交给 Agent 使用浏览器工具-完成授权后,用户就可以在对话里提出需要浏览器执行的任务,例如:+### 2.3 执行浏览器任务-- 打开某个网页并读取信息-- 登录后继续点击和填写表单-- 在邮箱中写邮件、上传附件、等待确认+直接让 Agent 打开网页、提取信息、填写表单或继续已授权流程。浏览器 Agent 会自动+启动并管理 Chrome。-当任务需要浏览器时,Agent 会操控这个已经获得授权的 Chrome,而不是重新新建一个完全无状态的浏览器。+在显示模式下,首次浏览器任务开始时会弹出 Chrome 窗口。如任务需要登录、MFA、+扫码或其他人工授权,请在该托管窗口中完成,然后回到对话继续任务。## 3. 使用建议-为了让浏览器工具更稳定,建议遵循以下做法:--- 尽量使用本机真实安装的 Chrome,而不是临时浏览器。-- 启动浏览器服务后,优先在弹出的 Chrome 中完成登录和授权。-- 对于长流程任务,尽量保持同一个会话,避免频繁更换浏览器状态。-- 如果任务涉及邮箱、企业系统、网银等场景,建议先人工完成一次登录,再交给 Agent 继续操作。-- 如果浏览器状态异常,可以重新启动浏览器服务后再测试。-- 建议让 `PLAYWRIGHT_CDP_URL` 与 `config.yaml` 中的远程调试地址、端口保持一致。-- 建议保持 `BROWSER_ALLOW_SHORT_TIMEOUT_OVERRIDE=0`,避免模型把浏览器任务拆成过多短调用。--## 4. 案例实践--### 4.1 案例一:网页信息提取-**任务描述**:从特定网页提取新闻标题和摘要+- 依赖登录态的长流程尽量保持在同一个 Agent 会话中。+- 登录、MFA、扫码和授权场景使用显示模式。+- 不需要人工交互的任务可使用无头模式。+- 正常使用 JiuwenSwarm 时,不要再额外启动使用固定调试端口的 Chrome;托管驱动会+ 自动选择并注入正确的 CDP 地址。+- 除非明确需要短超时,建议保持 `BROWSER_ALLOW_SHORT_TIMEOUT_OVERRIDE=0`。-**操作步骤**:-1. 启动浏览器服务并完成必要的授权-2. 在对话中输入:"请从 https://example.com/news 提取今天的头条新闻标题和摘要"-3. Agent 会自动调用浏览器工具访问指定网页-4. 浏览器会解析页面内容并提取所需信息-5. Agent 将提取到的信息整理后返回给用户+## 4. 案例-### 4.2 案例二:邮件发送(带附件)-**任务描述**:使用 Gmail 发送一封包含附件的邮件+### 4.1 提取网页信息-**操作步骤**:-1. 启动浏览器服务-2. 在弹出的 Chrome 中登录 Gmail 账号-3. 在对话中输入:"请帮我发送一封邮件,收件人:[email protected],主题:测试邮件,内容:这是一封测试邮件,附件:/path/to/file.pdf"-4. Agent 会调用浏览器工具,打开 Gmail 写信页面-5. 浏览器会自动填写收件人、主题、内容,并上传附件-6. 发送完成后,Agent 会通知用户邮件已发送+1. 在对话中输入:“请从 https://example.com/news 提取今天的新闻标题和摘要。”+2. Agent 会自动启动托管浏览器、访问页面并返回结果。-> **说明**:后续前端更新后会补充操作配图,每个案例将展示1-2张图片,主要展示关键执行流程和最终结果。+### 4.2 发送带附件的邮件-## 5. 后端配置方式+1. 启用“显示浏览器”并保存。+2. 让 Agent 打开 Gmail。+3. 如有需要,在托管 Chrome 窗口中完成登录。+4. 让 Agent 编写邮件并上传附件。-### 5.1 配置文件概述+## 5. 配置-浏览器工具的配置涉及以下几个核心文件,它们共同协作完成浏览器的配置和运行:+### 5.1 `config.yaml`-- **`config/config.yaml`**:主要配置 Chrome 启动参数,如 Chrome 可执行文件路径、远程调试地址和端口等,这些配置是浏览器启动的基础-- **`.env`**:配置浏览器运行时、MCP 连接、Playwright 参数和超时设置等环境变量,这些配置会影响浏览器的运行时行为-- **`.env.template`**:环境变量模板文件,包含所有可用的环境变量及其默认值,可作为配置参考--这三个文件的关系是:`config/config.yaml` 提供浏览器启动的基础参数,`.env` 提供运行时环境配置,两者结合确保浏览器工具正常工作。+| 配置项 | 类型 | 默认值 | 说明 |+|---|---|---|---|+| `browser.chrome_path` | string/map | `""` | Chrome 可执行文件。留空时自动检测,也可按操作系统配置路径。 |+| `browser.headless` | boolean | `true` | 设为 `false` 时显示托管浏览器窗口。 |-### 5.2 config.yaml 中浏览器配置+示例:-| 配置项 | 类型 | 默认值 | 说明 |-|--------|------|--------|------|-| `browser.chrome_path` | string/map | - | Chrome 可执行文件路径,可以是单个字符串或按 OS 写成 map |-| `browser.remote_debugging_address` | string | "127.0.0.1" | Chrome 远程调试监听地址 |-| `browser.remote_debugging_port` | integer | 9222 | Chrome 远程调试端口 |-| `browser.user_data_dir` | string | "" | Chrome 用户数据目录,留空时使用系统默认目录 |-| `browser.profile_directory` | string | "Default" | 要使用的 Chrome Profile 名称 |--**按操作系统配置示例**:```yamlbrowser:chrome_path:- windows: "C:\\Users\\YOUR_USER\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"- macos: "/Applications/Google Chrome.app"+ windows: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"+ macos: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"linux: "/usr/bin/google-chrome"- remote_debugging_address: "127.0.0.1"- remote_debugging_port: 9222- user_data_dir: ""- profile_directory: "Default"+ headless: true```-### 5.2 .env 中浏览器配置+`chrome_path` 留空时会清除之前配置的可执行文件,由 openJiuwen 从系统中自动检测+Chrome。填写路径后,该路径是唯一依据;如果它不是有效的 Chrome 可执行文件,浏览器+启动会直接报错,不会静默改用其他安装路径。-#### 5.2.1 浏览器 MCP wrapper 配置+### 5.2 高级环境变量-| 环境变量 | 默认值 | 说明 |-|----------|--------|------|-| `BROWSER_RUNTIME_MCP_ENABLED` | 1 | 是否启用浏览器 MCP wrapper |-| `BROWSER_RUNTIME_MCP_CLIENT_TYPE` | streamable-http | MCP client 类型 |-| `BROWSER_RUNTIME_MCP_SERVER_ID` | playwright_runtime_wrapper | wrapper 的标识信息 |-| `BROWSER_RUNTIME_MCP_SERVER_NAME` | playwright-runtime-wrapper | wrapper 的名称 |-| `BROWSER_RUNTIME_MCP_SERVER_PATH` | http://127.0.0.1:8940/mcp | wrapper 访问地址 |-| `BROWSER_RUNTIME_MCP_TIMEOUT_S` | 300 | MCP 连接或调用层的超时控制 |-| `BROWSER_RUNTIME_MCP_HOST` | 127.0.0.1 | 本地自动拉起 wrapper 时使用的 host |-| `BROWSER_RUNTIME_MCP_PORT` | 8940 | 本地自动拉起 wrapper 时使用的 port |-| `BROWSER_RUNTIME_MCP_PATH` | /mcp | 本地自动拉起 wrapper 时使用的 path |-| `BROWSER_RUNTIME_MCP_COMMAND` | - | wrapper 启动命令覆盖项,通常留空 |-| `BROWSER_RUNTIME_MCP_ARGS` | - | wrapper 启动参数覆盖项,通常留空 |-| `BROWSER_RUNTIME_MCP_AUTO_SSE_FALLBACK` | 1 | 某些模式下是否允许 SSE fallback |--#### 5.2.2 Playwright 官方 MCP 配置+大多数安装无需设置以下变量。| 环境变量 | 默认值 | 说明 |-|----------|--------|------|-| `PLAYWRIGHT_MCP_COMMAND` | npx | 启动官方 Playwright MCP 的命令 |-| `PLAYWRIGHT_MCP_ARGS` | -y @playwright/mcp@latest | 启动官方 Playwright MCP 的参数 |-| `PLAYWRIGHT_CDP_URL` | http://127.0.0.1:9222 | 连接到已启动 Chrome 的 CDP 地址,应与 config.yaml 中的调试地址和端口保持一致 |--#### 5.2.3 超时与执行策略配置--| 环境变量 | 默认值 | 说明 |-|----------|--------|------|-| `PLAYWRIGHT_TOOL_TIMEOUT_S` | 300 | 浏览器工具执行的总 watchdog 超时 |-| `BROWSER_TIMEOUT_S` | 300 | 浏览器任务默认长超时,如果模型传入的 timeout_s 更小,默认会被钳回至少这个值 |-| `BROWSER_ALLOW_SHORT_TIMEOUT_OVERRIDE` | 0 | 是否允许模型把任务超时改得更短,推荐保持为 0 |--### 5.3 推荐最小配置--要正常使用浏览器工具,至少保证下面这些字段配置正确:--**config/config.yaml**-```yaml-browser:- chrome_path: "C:\\Users\\YOUR_USER\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"- remote_debugging_address: "127.0.0.1"- remote_debugging_port: 9222- user_data_dir: ""- profile_directory: "Default"-```--**.env**-```dotenv-BROWSER_RUNTIME_MCP_ENABLED=1-BROWSER_RUNTIME_MCP_CLIENT_TYPE=streamable-http-BROWSER_RUNTIME_MCP_SERVER_PATH=http://127.0.0.1:8940/mcp-PLAYWRIGHT_MCP_COMMAND=npx-PLAYWRIGHT_MCP_ARGS=-y @playwright/mcp@latest-PLAYWRIGHT_CDP_URL=http://127.0.0.1:9222-PLAYWRIGHT_TOOL_TIMEOUT_S=300-BROWSER_TIMEOUT_S=300-BROWSER_ALLOW_SHORT_TIMEOUT_OVERRIDE=0-```--## 6. 原理与代码架构--### 6.1 技术架构--当前浏览器工具的核心链路如下:--- **前端页面**:提供「浏览器服务」面板,用于配置 Chrome 可执行文件路径并启动浏览器服务-- **后端应用**:通过 `browser_start_client.py` 启动本机 Chrome,并开启远程调试能力-- **浏览器运行时**:基于 Playwright MCP 封装,浏览器工具通过 MCP client 与运行时通信-- **Agent 调用**:Agent 调用 `browser_run_task` 等工具时,运行时会把自然语言任务转换为浏览器操作步骤-- **会话管理**:浏览器会按 `session_id` 复用,同一会话下可以保持登录态、页面上下文和授权状态--可以简单理解为:--`前端配置 → 启动 Chrome → 运行时接管 Chrome → Agent 在需要时操控浏览器执行任务`--### 6.2 核心代码--浏览器工具的核心代码主要分布在以下模块:--#### Chrome 启动脚本-- `jiuwenswarm/agentserver/tools/browser_start_client.py`- - 读取 `config/config.yaml` 中的 `browser.*` 配置- - 启动带远程调试能力的 Chrome--#### 浏览器 MCP 接入-- `jiuwenswarm/agentserver/tools/browser_tools.py`- - 浏览器 MCP wrapper 的接入、自动拉起、client patch、配置构建+|---|---|---|+| `BROWSER_DRIVER` | JiuwenSwarm 中为 `managed` | 浏览器驱动模式。 |+| `BROWSER_MANAGED_BINARY` | 自动检测 | openJiuwen 直接运行时的覆盖项;JiuwenSwarm 会根据 `browser.chrome_path` 生成该值。 |+| `BROWSER_MANAGED_PORT` | `9333` | 非 keyed 托管实例的端口;keyed 实例自动分配空闲端口。 |+| `BROWSER_MANAGED_USER_DATA_DIR` | 托管 Profile 目录 | 覆盖托管浏览器的 Profile 目录。 |+| `BROWSER_MANAGED_ARGS` | 根据显示模式生成 | 额外的 Chrome 启动参数。 |+| `BROWSER_MANAGED_KILL_EXISTING` | `false` | 启动前终止匹配的既有 Chrome。仅在明确 Profile 所有权时启用。 |-#### 浏览器运行时-- `jiuwenswarm/agentserver/tools/browser-move/src/playwright_runtime_mcp_server.py`- - 浏览器 runtime 的 MCP server 入口-- `jiuwenswarm/agentserver/tools/browser-move/src/playwright_runtime/runtime.py`- - 浏览器 runtime 编排层-- `jiuwenswarm/agentserver/tools/browser-move/src/playwright_runtime/service.py`- - 浏览器任务执行、session 复用、timeout guardrails-- `jiuwenswarm/agentserver/tools/browser-move/src/playwright_runtime/agents.py`- - 主编排 agent 与浏览器 worker agent 的提示词和构造逻辑-- `jiuwenswarm/agentserver/tools/browser-move/src/playwright_runtime/config.py`- - Playwright MCP 与浏览器运行时配置解析+`PLAYWRIGHT_CDP_URL` 用于显式的远程驱动模式,正常的托管浏览器流程不需要配置它。-- **工具管理模块**:`jiuwenswarm/agents/harness/common/tools/` 是系统管理所有工具的底层模块,浏览器相关工具主要在此模块下实现-- **前端界面模块**:`jiuwenswarm/channels/web/frontend/` 负责用户界面交互+## 6. 架构-具体文件说明:+浏览器生命周期为:-| 模块 | 文件路径 | 功能说明 |-|------|----------|----------|-| 前端浏览器服务面板 | `jiuwenswarm/channels/web/frontend/src/components/BrowserPanel/index.tsx` | 负责读取路径、保存路径、触发「启动浏览器服务」 |-| 后端应用入口 | `app.py` | 提供 `path.get`、`path.set`、`browser.start` 等前端调用入口 |-| Chrome 启动脚本 | `jiuwenswarm/agentserver/tools/browser_start_client.py` | 读取 `config/config.yaml` 中的 `browser.*` 配置,启动带远程调试能力的 Chrome |-| 浏览器 MCP 接入 | `jiuwenswarm/agentserver/tools/browser_tools.py` | 浏览器 MCP wrapper 的接入、自动拉起、client patch、配置构建 |-| 浏览器运行时 MCP 服务 | `jiuwenswarm/agentserver/tools/browser-move/src/playwright_runtime_mcp_server.py` | 浏览器 runtime 的 MCP server 入口 |-| 浏览器运行时编排层 | `jiuwenswarm/agentserver/tools/browser-move/src/playwright_runtime/runtime.py` | 浏览器 runtime 编排层 |-| 浏览器任务执行 | `jiuwenswarm/agentserver/tools/browser-move/src/playwright_runtime/service.py` | 浏览器任务执行、session 复用、timeout guardrails |-| 浏览器运行时配置 | `jiuwenswarm/agentserver/tools/browser-move/src/playwright_runtime/config.py` | Playwright MCP 与浏览器运行时配置解析 |+`前端保存设置 -> Agent 浏览器任务 -> 自动启动托管 Chrome -> 执行任务 -> 复用会话`-## 7. 一句话总结+- 前端 `BrowserPanel` 只负责读取和保存 Chrome 路径与显示模式。+- JiuwenSwarm 将这些设置映射到浏览器 Agent 运行时。+- openJiuwen 的 `BrowserService` 和 `ManagedBrowserDriver` 负责按需分配端口、启动+ Chrome、健康检查、复用 Profile,并随 Agent 生命周期停止。+- Playwright MCP 使用托管实例注入的端点,不再依赖前端启动的浏览器。-浏览器工具的本质,是让 Agent 在用户已经授权过的真实 Chrome 上执行网页操作;前端负责配置和启动,后端负责接管和自动化执行。\ No newline at end of file+这样,浏览器启动、Profile 所有权、端点分配和清理都由浏览器 Agent 这一处统一管理。diff --git a/jiuwenswarm/agents/harness/common/tools/browser_start_client.py b/jiuwenswarm/agents/harness/common/tools/browser_start_client.pydeleted file mode 100644index 7cd138362c..0000000000--- a/jiuwenswarm/agents/harness/common/tools/browser_start_client.py+++ /dev/null@@ -1,531 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.--"""Start Chrome/Chromium with remote debugging enabled (cross-platform).--Reads browser settings from `config/config.yaml`:--browser:- chrome_path: "<path or command>"- remote_debugging_address: "127.0.0.1"- remote_debugging_port: 9222- user_data_dir: ""- profile_directory: "Default"--`chrome_path` can also be a map by OS:--browser:- chrome_path:- windows: "C:\\path\\to\\chrome.exe"- macos: "/Applications/Google Chrome.app"- linux: "/usr/bin/google-chrome"-"""--from __future__ import annotations--import argparse-import logging-import os-import platform-import shutil-import socket-import subprocess-import threading-import time-from dataclasses import dataclass, field-from pathlib import Path-from typing import Any, Optional--import psutil-import yaml-from openjiuwen.harness.tools.browser_move.playwright_runtime.profiles import (- BrowserProfile,- BrowserProfileStore,-)--from jiuwenswarm.common.utils import get_user_workspace_dir---logger = logging.getLogger(__name__)---def _repo_root() -> Path:- return Path(__file__).resolve().parents[3]---def _config_path(custom_path: str = "") -> Path:- if custom_path:- return Path(custom_path).expanduser().resolve()- return _repo_root() / "config" / "config.yaml"----def _browser_runtime_state_root() -> Path:- configured = (os.getenv("BROWSER_RUNTIME_STATE_DIR") or "").strip()- if configured:- return Path(configured).expanduser()- return get_user_workspace_dir()---def _profile_store_path() -> Path:- configured = (os.getenv("BROWSER_PROFILE_STORE_PATH") or "").strip()- if configured:- return Path(configured).expanduser()- return _browser_runtime_state_root() / ".browser" / "profiles.json"---def _profile_name(profile_directory: str) -> str:- configured = (os.getenv("BROWSER_PROFILE_NAME") or "").strip()- if configured:- return configured- fallback = (profile_directory or "").strip()- return fallback or "jiuwenswarm"----def _persist_browser_profile(- *,- host: str,- port: int,- chrome_exec: str,- user_data_dir: str,- profile_directory: str,-) -> None:- store_path = _profile_store_path()- store = BrowserProfileStore(store_path)- profile = BrowserProfile(- name=_profile_name(profile_directory),- driver_type="remote",- cdp_url=f"http://{host}:{port}",- browser_binary=chrome_exec,- user_data_dir=user_data_dir,- debug_port=port,- host=host,- extra_args=[f"--profile-directory={profile_directory}"] if profile_directory else [],- )- store.upsert_profile(profile, select=True)- logger.info(- "Persisted browser profile for manual browser start: "- f"profile={profile.name}, cdp_url={profile.cdp_url}, store_path={store_path}"- )---def _load_browser_config(config_file: str = "") -> dict[str, Any]:- cfg_file = _config_path(config_file)- if not cfg_file.exists():- return {}- with cfg_file.open("r", encoding="utf-8") as f:- data = yaml.safe_load(f) or {}- browser_cfg = data.get("browser")- return browser_cfg if isinstance(browser_cfg, dict) else {}---def _os_key() -> str:- system = platform.system().lower()- if system.startswith("win"):- return "windows"- if system == "darwin":- return "macos"- return "linux"---def _resolve_chrome_path(raw_value: Any, os_name: str) -> str:- if isinstance(raw_value, dict):- for key in (os_name, "default"):- value = raw_value.get(key)- if isinstance(value, str) and value.strip():- return value.strip()- return ""- if isinstance(raw_value, str):- return raw_value.strip()- return ""---def _default_chrome_candidates(os_name: str) -> list[str]:- if os_name == "windows":- local_app_data = os.getenv("LOCALAPPDATA", "")- program_files = os.getenv("PROGRAMFILES", "C:\\Program Files")- program_files_x86 = os.getenv("PROGRAMFILES(X86)", "C:\\Program Files (x86)")- return [- str(Path(local_app_data) / "Google" / "Chrome" / "Application" / "chrome.exe"),- str(Path(program_files) / "Google" / "Chrome" / "Application" / "chrome.exe"),- str(Path(program_files_x86) / "Google" / "Chrome" / "Application" / "chrome.exe"),- "chrome.exe",- ]- if os_name == "macos":- return [- "/Applications/Google Chrome.app",- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",- "Google Chrome",- "google-chrome",- "chromium",- ]- return [- "google-chrome",- "google-chrome-stable",- "chromium-browser",- "chromium",- ]---def _normalize_chrome_executable(path_or_cmd: str, os_name: str) -> str:- if not path_or_cmd:- return ""-- expanded = os.path.expandvars(os.path.expanduser(path_or_cmd))- path = Path(expanded)-- if os_name == "macos" and expanded.endswith(".app"):- candidate = path / "Contents" / "MacOS" / "Google Chrome"- if candidate.exists():- return str(candidate)-- if path.exists():- return str(path)-- resolved = shutil.which(expanded)- if resolved:- return resolved-- return ""---def _resolve_user_data_dir(raw_value: Any, os_name: str) -> str:- if isinstance(raw_value, str) and raw_value.strip():- return os.path.expandvars(os.path.expanduser(raw_value.strip()))-- if os_name == "windows":- local_app_data = os.getenv("LOCALAPPDATA", "")- return str(Path(local_app_data) / "ChromeCDPProfile")-- return str(Path.home() / "chrome-cdp-profile")---def _parse_cdp_from_env(default_host: str, default_port: int) -> tuple[str, int]:- raw = (os.getenv("PLAYWRIGHT_CDP_URL") or "").strip()- if not raw:- return default_host, default_port-- # format: http://host:port- try:- no_scheme = raw.split("://", 1)[-1]- host_port = no_scheme.split("/", 1)[0]- host, port_text = host_port.rsplit(":", 1)- return host, int(port_text)- except Exception:- return default_host, default_port---def _creation_flags_for_windows() -> int:- flags = 0- flags |= getattr(subprocess, "DETACHED_PROCESS", 0)- flags |= getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)- return flags---@dataclass-class _BrowserProcessHandle:- proc: "subprocess.Popen"- chrome_exec: str- host: str- port: int- user_data_dir: str---_BROWSER_PROCESS_REGISTRY: dict[int, _BrowserProcessHandle] = {}-_BROWSER_REGISTRY_LOCK = threading.Lock()---def _register_browser_process(handle: _BrowserProcessHandle) -> None:- with _BROWSER_REGISTRY_LOCK:- previous = _BROWSER_PROCESS_REGISTRY.pop(handle.proc.pid, None)- if previous is not None and previous is not handle:- logger.info(- "Replacing previous browser process handle in registry "- f"pid={previous.proc.pid}"- )- _BROWSER_PROCESS_REGISTRY[handle.proc.pid] = handle---def _unregister_browser_process(pid: int) -> Optional[_BrowserProcessHandle]:- with _BROWSER_REGISTRY_LOCK:- return _BROWSER_PROCESS_REGISTRY.pop(pid, None)---def _reap_browser_on_exit(handle: _BrowserProcessHandle) -> None:- pid = handle.proc.pid- try:- try:- handle.proc.wait()- except Exception as exc:- logger.warning(f"Browser reap watcher wait() failed pid={pid}: {exc}")- return- logger.info(- f"Browser main process exited pid={pid}, reaping child processes "- f"host={handle.host}, port={handle.port}"- )- try:- _stop_existing_browser_service(- chrome_exec=handle.chrome_exec,- host=handle.host,- port=handle.port,- user_data_dir=handle.user_data_dir,- )- except Exception as exc:- logger.warning(- f"Browser reap watcher could not fully clean child processes pid={pid}: {exc}"- )- finally:- _unregister_browser_process(pid)---def _normalized_path(value: str) -> str:- expanded = os.path.expandvars(os.path.expanduser((value or "").strip().strip('"')))- return os.path.normcase(os.path.normpath(os.path.abspath(expanded)))---def _cmdline_option(args: list[str], option: str) -> str:- prefix = f"{option}="- for index, arg in enumerate(args):- if arg.startswith(prefix):- return arg[len(prefix):]- if arg == option and index + 1 < len(args):- return args[index + 1]- return ""---def _find_existing_browser_processes(- *, chrome_exec: str, port: int, user_data_dir: str-) -> list[Any]:- """Find only Chrome processes belonging to this browser service."""- expected_executable = _normalized_path(chrome_exec)- expected_user_data_dir = _normalized_path(user_data_dir)- matches: list[Any] = []- for process in psutil.process_iter(["pid", "ppid", "exe", "cmdline"]):- try:- executable = str(process.info.get("exe") or "")- args = [str(arg) for arg in (process.info.get("cmdline") or [])]- if not executable:- continue- if _normalized_path(executable) != expected_executable:- continue- if _cmdline_option(args, "--remote-debugging-port") != str(port):- continue-- actual_user_data_dir = _cmdline_option(args, "--user-data-dir")- if not actual_user_data_dir:- continue- if _normalized_path(actual_user_data_dir) != expected_user_data_dir:- continue-- matches.append(process)- except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):- continue- return matches---def _port_is_open(host: str, port: int, *, timeout_s: float = 0.2) -> bool:- connect_host = "127.0.0.1" if host in {"", "0.0.0.0", "::"} else host- try:- with socket.create_connection((connect_host, port), timeout=timeout_s):- return True- except OSError:- return False---def _stop_existing_browser_service(- *,- chrome_exec: str,- host: str,- port: int,- user_data_dir: str,- timeout_s: float = 5.0,-) -> list[int]:- matches = _find_existing_browser_processes(- chrome_exec=chrome_exec,- port=port,- user_data_dir=user_data_dir,- )- if not matches:- return []-- matched_pids = {process.pid for process in matches}- roots = [- process- for process in matches- if int(process.info.get("ppid") or 0) not in matched_pids- ] or matches- targets: dict[int, Any] = {process.pid: process for process in matches}- for root in roots:- try:- targets.update({child.pid: child for child in root.children(recursive=True)})- except (psutil.AccessDenied, psutil.NoSuchProcess):- pass-- processes = list(targets.values())- for process in processes:- try:- process.terminate()- except psutil.NoSuchProcess:- pass- _, alive = psutil.wait_procs(processes, timeout=timeout_s)- for process in alive:- try:- process.kill()- except psutil.NoSuchProcess:- pass- if alive:- _, alive = psutil.wait_procs(alive, timeout=2.0)- if alive:- remaining = ", ".join(str(process.pid) for process in alive)- raise RuntimeError(f"Could not stop existing browser service processes: {remaining}")-- deadline = time.monotonic() + timeout_s- while _port_is_open(host, port) and time.monotonic() < deadline:- time.sleep(0.1)- if _port_is_open(host, port):- raise RuntimeError(f"Browser service port {host}:{port} did not close after restart")-- stopped_pids = sorted(targets)- logger.info(- "Stopped existing browser service before restart: "- f"pids={stopped_pids}, host={host}, port={port}"- )- return stopped_pids---def start_browser(*, dry_run: bool = False, config_file: str = "") -> int:- browser_cfg = _load_browser_config(config_file)- os_name = _os_key()- logger.info(- "Starting browser service from browser_start_client: "- f"config_file={_config_path(config_file)}, os={os_name}"- )-- chrome_cfg = _resolve_chrome_path(browser_cfg.get("chrome_path"), os_name)- if not chrome_cfg:- chrome_cfg = os.getenv("CHROME_PATH", "").strip()-- if not chrome_cfg:- raise FileNotFoundError(- "Chrome path is required. Please set browser.chrome_path in config/config.yaml "- "or CHROME_PATH env."- )- chrome_exec = _normalize_chrome_executable(chrome_cfg, os_name)- logger.info(- "Resolved Chrome executable for browser service: "- f"configured={chrome_cfg}, resolved={chrome_exec or '(not found)'}"- )- if not chrome_exec:- raise FileNotFoundError(- f"Chrome executable not found for configured path: {chrome_cfg}"- )-- host = str(browser_cfg.get("remote_debugging_address") or "127.0.0.1").strip()- port = int(browser_cfg.get("remote_debugging_port") or 9222)- host, port = _parse_cdp_from_env(host, port)-- user_data_dir = _resolve_user_data_dir(browser_cfg.get("user_data_dir"), os_name)- profile_directory = str(browser_cfg.get("profile_directory") or "Default").strip()-- raw_headless = browser_cfg.get("headless", True)- headless = bool(raw_headless) if isinstance(raw_headless, bool) else True-- logger.info(- "Resolved browser launch parameters: "- f"host={host}, port={port}, user_data_dir={user_data_dir}, "- f"profile_directory={profile_directory or '(empty)'}, headless={headless}"- )-- args = [- chrome_exec,- f"--remote-debugging-address={host}",- f"--remote-debugging-port={port}",- f"--user-data-dir={user_data_dir}",- ]- if headless:- args.append("--headless=new")- if profile_directory:- args.append(f"--profile-directory={profile_directory}")-- kwargs: dict[str, Any] = {- "stdout": subprocess.DEVNULL,- "stderr": subprocess.DEVNULL,- }- if os_name == "windows":- kwargs["creationflags"] = _creation_flags_for_windows()- else:- kwargs["start_new_session"] = True-- if dry_run:- logger.info("Dry run: browser launch command prepared.")- logger.info(" ".join(args))- return 0-- _stop_existing_browser_service(- chrome_exec=chrome_exec,- host=host,- port=port,- user_data_dir=user_data_dir,- )- if _port_is_open(host, port):- raise RuntimeError(- f"Browser service port {host}:{port} is occupied by an unrecognized process. "- "Stop that process or choose another remote_debugging_port."- )-- logger.info(- "Launching browser process with remote debugging enabled: "- f"command={args}"- )- proc = subprocess.Popen(args, **kwargs)- logger.info(f"Browser process launched successfully: pid={proc.pid}")- handle = _BrowserProcessHandle(- proc=proc,- chrome_exec=chrome_exec,- host=host,- port=port,- user_data_dir=user_data_dir,- )- _register_browser_process(handle)- watcher = threading.Thread(- target=_reap_browser_on_exit,- args=(handle,),- name=f"browser-reap-{proc.pid}",- daemon=True,- )- watcher.start()- _persist_browser_profile(- host=host,- port=port,- chrome_exec=chrome_exec,- user_data_dir=user_data_dir,- profile_directory=profile_directory,- )- logger.info(f"Chrome started (pid={proc.pid}) at {host}:{port}")- logger.info(f"Executable: {chrome_exec}")- logger.info(f"Profile dir: {user_data_dir}")- return 0---def main() -> int:- parser = argparse.ArgumentParser(description="Start Chrome with CDP enabled.")- parser.add_argument(- "--dry-run",- action="store_true",- help="Print resolved launch command without starting Chrome.",- )- parser.add_argument(- "--config",- default="",- help="Optional path to config yaml (default: config/config.yaml).",- )- args = parser.parse_args()- try:- return start_browser(dry_run=args.dry_run, config_file=args.config)- except Exception as exc:- logger.error("Failed to start Chrome: %s", exc)- return 1---if __name__ == "__main__":- raise SystemExit(main())diff --git a/jiuwenswarm/channels/web/frontend/src/components/BrowserPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/BrowserPanel/index.tsxindex 0143557148..4230dcff99 100644--- a/jiuwenswarm/channels/web/frontend/src/components/BrowserPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/BrowserPanel/index.tsx@@ -7,10 +7,6 @@ interface BrowserPathPayload {headless?: unknown;}-interface BrowserStartPayload {- returncode?: unknown;-}-interface BrowserPanelProps {isConnected: boolean;request: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>;@@ -28,13 +24,6 @@ function normalizeHeadless(payload: unknown): boolean {return typeof data.headless === 'boolean' ? data.headless : true;}-function normalizeReturnCode(payload: unknown): number | null {- if (!payload || typeof payload !== 'object') return null;- const data = payload as BrowserStartPayload;- const code = Number(data.returncode);- return Number.isInteger(code) ? code : null;-}-export function BrowserPanel({ isConnected, request }: BrowserPanelProps) {const { t } = useTranslation();const [chromePath, setChromePath] = useState('');@@ -43,20 +32,13 @@ export function BrowserPanel({ isConnected, request }: BrowserPanelProps) {const [initialHeadless, setInitialHeadless] = useState(true);const [loading, setLoading] = useState(false);const [saving, setSaving] = useState(false);- const [starting, setStarting] = useState(false);const [error, setError] = useState<string | null>(null);const [success, setSuccess] = useState<string | null>(null);- const [showPathError, setShowPathError] = useState(false);const hasChanges = useMemo(() => chromePath !== initialPath || headless !== initialHeadless,[chromePath, initialPath, headless, initialHeadless]);- const isPathValid = useMemo(() => chromePath.trim().length > 0, [chromePath]);- const canStart = useMemo(- () => isConnected && !starting && !saving && !loading && isPathValid && !hasChanges,- [hasChanges, isConnected, isPathValid, loading, saving, starting]- );const clearFeedback = () => {setError(null);@@ -120,38 +102,6 @@ export function BrowserPanel({ isConnected, request }: BrowserPanelProps) {}};- const handleStart = async () => {- if (starting || !isConnected) {- return;- }- if (!isPathValid) {- setShowPathError(true);- return;- }- if (hasChanges) {- clearFeedback();- setError(t('browser.errors.saveBeforeStart'));- return;- }- setStarting(true);- clearFeedback();- setShowPathError(false);- try {- const payload = await request<BrowserStartPayload>('browser.start');- const returncode = normalizeReturnCode(payload);- if (returncode === null || returncode === 0) {- setSuccess(t('browser.success.started'));- } else {- setError(t('browser.errors.startFailedWithCode', { code: returncode }));- }- } catch (startError) {- const message = startError instanceof Error ? startError.message : t('browser.errors.startFailed');- setError(t('browser.errors.startFailedWithMessage', { message }));- } finally {- setStarting(false);- }- };-return (<div className="flex-1 min-h-0"><div className="card main-panel-card w-full h-full flex flex-col">@@ -166,7 +116,7 @@ export function BrowserPanel({ isConnected, request }: BrowserPanelProps) {<buttontype="button"onClick={() => void loadPath()}- disabled={saving || starting}+ disabled={saving || loading}className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed">{loading ? t('common.refreshing') : t('browser.refreshPath')}@@ -198,18 +148,13 @@ export function BrowserPanel({ isConnected, request }: BrowserPanelProps) {onChange={(event) => {setChromePath(event.target.value);if (error) setError(null);- if (showPathError) setShowPathError(false);}}placeholder={t('browser.examplePath')}className="w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] text-text outline-none focus:border-accent"- disabled={loading || saving || starting}+ disabled={loading || saving}/></label>- {showPathError && !isPathValid ? (- <div className="text-xs text-danger">{t('browser.errors.pathRequired')}</div>- ) : null}-<div className="flex items-center justify-between gap-4 py-1"><div><span className="text-xs uppercase tracking-wide text-text-muted">{t('browser.showBrowser')}</span>@@ -218,7 +163,7 @@ export function BrowserPanel({ isConnected, request }: BrowserPanelProps) {<Switchchecked={!headless}onChange={(val) => setHeadless(!val)}- disabled={loading || saving || starting}+ disabled={loading || saving}/></div>@@ -231,7 +176,7 @@ export function BrowserPanel({ isConnected, request }: BrowserPanelProps) {setHeadless(initialHeadless);clearFeedback();}}- disabled={!hasChanges || saving || starting}+ disabled={!hasChanges || saving}>{t('common.cancel')}</button>@@ -239,25 +184,10 @@ export function BrowserPanel({ isConnected, request }: BrowserPanelProps) {type="button"className="btn primary !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"onClick={() => void handleSave()}- disabled={!isConnected || !hasChanges || saving || starting || loading}+ disabled={!isConnected || !hasChanges || saving || loading}>{saving ? t('common.saving') : t('browser.savePath')}</button>- <button- type="button"- className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"- onClick={() => void handleStart()}- disabled={!canStart}- title={- !isPathValid- ? t('browser.tooltips.fillPath')- : hasChanges- ? t('browser.tooltips.savePath')- : undefined- }- >- {starting ? t('browser.starting') : t('browser.startService')}- </button></div></div></div>diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex b3c020bc34..b558a07b82 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -37,7 +37,7 @@"more": "More","settings": "Settings","config": "Configuration",- "browser": "Browser Service",+ "browser": "Browser","logs": "Logs","update": "Updates"},@@ -1292,32 +1292,20 @@}},"browser": {- "title": "Browser Service",- "subtitle": "Configure the browser path and start the browser service.",+ "title": "Browser",+ "subtitle": "Configure the Chrome path and display mode used by browser agents.","refreshPath": "Refresh Path","savePath": "Save Path",- "startService": "Start Browser Service",- "starting": "Starting...","pathConfigHelp": "Chrome path configuration (open chrome://version in Chrome and copy the executable path)","examplePath": "Example: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome","success": {- "pathSaved": "Chrome path saved",- "started": "Browser service started successfully"- },- "tooltips": {- "fillPath": "Enter a Chrome path first",- "savePath": "Save the Chrome path first"+ "pathSaved": "Chrome path saved"},"showBrowser": "Show Browser","showBrowserDesc": "Open a visible browser window when running browser tasks.","errors": {"loadPath": "Failed to load Chrome path",- "savePath": "Failed to save Chrome path",- "pathRequired": "Chrome path cannot be empty",- "saveBeforeStart": "Save the Chrome path before starting the browser service",- "startFailed": "Failed to start browser service",- "startFailedWithCode": "Browser service failed to start, return code {{code}}",- "startFailedWithMessage": "Browser service failed to start: {{message}}"+ "savePath": "Failed to save Chrome path"}},"logsPanel": {diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 079c710a05..dcf80d76ff 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -37,7 +37,7 @@"more": "更多","settings": "设置","config": "配置信息",- "browser": "浏览器服务",+ "browser": "浏览器","logs": "日志","update": "更新"},@@ -1293,32 +1293,20 @@}},"browser": {- "title": "浏览器服务",- "subtitle": "配置浏览器路径,启动浏览器服务。",+ "title": "浏览器",+ "subtitle": "配置浏览器 Agent 使用的 Chrome 路径和显示模式。","refreshPath": "刷新路径","savePath": "保存路径",- "startService": "启动浏览器服务",- "starting": "启动中...","pathConfigHelp": "CHROME 路径配置(Chrome地址栏输入:chrome://version查看,复制可执行文件路径)","examplePath": "例如:/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","success": {- "pathSaved": "Chrome 路径已保存",- "started": "浏览器服务启动成功"- },- "tooltips": {- "fillPath": "请先填写 Chrome 路径",- "savePath": "请先保存 Chrome 路径"+ "pathSaved": "Chrome 路径已保存"},"showBrowser": "显示浏览器","showBrowserDesc": "执行浏览器任务时打开可见的浏览器窗口。","errors": {"loadPath": "加载 Chrome 路径失败",- "savePath": "保存 Chrome 路径失败",- "pathRequired": "Chrome 路径不能为空",- "saveBeforeStart": "请先保存 Chrome 路径后再启动浏览器服务",- "startFailed": "启动浏览器服务失败",- "startFailedWithCode": "浏览器服务启动失败,返回码 {{code}}",- "startFailedWithMessage": "浏览器服务启动失败:{{message}}"+ "savePath": "保存 Chrome 路径失败"}},"logsPanel": {diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex 9ae220a1ce..db2444079a 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -56,7 +56,6 @@ class ReqMethod(Enum):PATH_GET = "path.get"PATH_SET = "path.set"- BROWSER_START = "browser.start"BROWSER_RUNTIME_RESTART = "browser.runtime_restart"CONFIG_CACHE_CLEAR = "config.cache_clear"diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.pyindex c73485fe4c..449da25074 100644--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py@@ -215,7 +215,6 @@ CLI_FORWARD_REQ_METHODS = frozenset("chat.user_answer","chat.swarmflow_reply","history.get",- "browser.start","skills.marketplace.list","skills.list","skills.installed",@@ -314,7 +313,6 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset("command.workflows","command.status","command.goal",- "browser.start","skills.marketplace.list","skills.list","skills.installed",diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 6c56d5bc12..37038f7c5c 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -570,7 +570,6 @@ _FORWARD_REQ_METHODS = frozenset({"chat.resume","chat.user_answer","history.get",- "browser.start",# "tts.synthesize","skills.marketplace.list","skills.list",@@ -658,7 +657,6 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({"acp.tool_response","team.delete","command.goal",- "browser.start","team.snapshot","team.history.get","team.mq.publish",@@ -1106,6 +1104,25 @@ async def _clear_agent_config_cache(agent_client=None) -> None:pass+async def _restart_agent_browser_runtime(agent_client=None) -> None:+ """Stop active agent-side browser runtimes so the next task uses new config."""+ if agent_client is None:+ return++ from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenswarm.common.schema.message import ReqMethod++ env = e2a_from_agent_fields(+ request_id=f"browser-restart-{uuid.uuid4().hex[:8]}",+ channel_id="",+ req_method=ReqMethod.BROWSER_RUNTIME_RESTART,+ )+ response = await agent_client.send_request(env)+ if not response.ok:+ error = response.payload.get("error", "browser runtime restart failed")+ raise RuntimeError(str(error))++def _make_session_id() -> str:# 与前端 generateSessionId 保持一致:毫秒时间戳(16进制) + 6位随机16进制ts = format(int(time.time() * 1000), "x")@@ -4285,26 +4302,20 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:try:update_browser_in_config({"chrome_path": chrome_path, "headless": headless})- await _clear_agent_config_cache(_resolve(agent_client))+ resolved_agent_client = _resolve(agent_client)+ await _clear_agent_config_cache(resolved_agent_client)except Exception as e: # noqa: BLE001logger.warning("[path.set] 写回 config.yaml 失败: %s", e)await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")return- # When switching to headless, purge any persisted headed-Chrome profile so the- # managed driver doesn't reuse an existing visible window on the next browser task.- if headless:- try:- from pathlib import Path as _Path- _profile_store = _Path(- os.getenv("BROWSER_PROFILE_STORE_PATH", "").strip()- or str(get_user_workspace_dir() / ".browser" / "profiles.json")- ).expanduser()- if _profile_store.exists():- _profile_store.unlink()- logger.info("[path.set] Cleared browser profile store for headless mode: %s", _profile_store)- except Exception as _e:- logger.debug("[path.set] Could not clear browser profile store: %s", _e)+ try:+ await _restart_agent_browser_runtime(resolved_agent_client)+ except Exception as e: # noqa: BLE001+ logger.warning(+ "[path.set] browser config saved but active runtime reset failed: %s",+ e,+ )await channel.send_response(ws, req_id, ok=True, payload={"chrome_path": chrome_path, "headless": headless})diff --git a/jiuwenswarm/resources/config.team.distributed.leader.yaml b/jiuwenswarm/resources/config.team.distributed.leader.yamlindex 5dae1fa182..b2d1f3c40f 100644--- a/jiuwenswarm/resources/config.team.distributed.leader.yaml+++ b/jiuwenswarm/resources/config.team.distributed.leader.yaml@@ -619,11 +619,9 @@ browser:# windows: "C:\\Users\\YOUR_USER\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"# macos: "/Applications/Google Chrome.app"# linux: "/usr/bin/google-chrome"- remote_debugging_address: "127.0.0.1"- remote_debugging_port: 9222- # empty means use launcher default profile path by OS- user_data_dir: ""- profile_directory: "Default"+ chrome_path: ""+ # true runs Chrome without a visible window; false opens a managed window.+ headless: trueupdater:enabled: truediff --git a/jiuwenswarm/resources/config.team.distributed.teammate.yaml b/jiuwenswarm/resources/config.team.distributed.teammate.yamlindex 24d3fd32b3..189e95a075 100644--- a/jiuwenswarm/resources/config.team.distributed.teammate.yaml+++ b/jiuwenswarm/resources/config.team.distributed.teammate.yaml@@ -625,11 +625,9 @@ browser:# windows: "C:\\Users\\YOUR_USER\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"# macos: "/Applications/Google Chrome.app"# linux: "/usr/bin/google-chrome"- remote_debugging_address: "127.0.0.1"- remote_debugging_port: 9222- # empty means use launcher default profile path by OS- user_data_dir: ""- profile_directory: "Default"+ chrome_path: ""+ # true runs Chrome without a visible window; false opens a managed window.+ headless: trueupdater:enabled: truediff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 8d094391c3..eecfe4c9b0 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -959,11 +959,9 @@ browser:# windows: "C:\\Users\\YOUR_USER\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"# macos: "/Applications/Google Chrome.app"# linux: "/usr/bin/google-chrome"- remote_debugging_address: "127.0.0.1"- remote_debugging_port: 9222- # empty means use launcher default profile path by OS- user_data_dir: ""- profile_directory: "Default"+ chrome_path: ""+ # true runs Chrome without a visible window; false opens a managed window.+ headless: trueupdater:enabled: truediff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex dcf800f1ac..b756ffed7e 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -118,6 +118,23 @@ logger = logging.getLogger(__name__)_background_permission_reload_tasks: set[asyncio.Task] = set()+async def _reset_active_browser_runtimes_if_available(browser_move: Any) -> int:+ """Reset active browser runtimes when supported by the installed SDK."""+ reset_runtimes = getattr(+ browser_move,+ "reset_active_browser_runtimes",+ None,+ )+ if not callable(reset_runtimes):+ logger.warning(+ "[AgentWebSocketServer] installed openjiuwen does not support "+ "reset_active_browser_runtimes; restarting the local browser "+ "runtime server only"+ )+ return 0+ return await reset_runtimes()++def _log_permission_reload_failure(task: asyncio.Task) -> None:"""后台权限重载任务完成回调: 仅在异常时记 debug(与原同步 try/except 语义一致)。"""exc = task.exception()@@ -1374,9 +1391,6 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.COMMAND_STATUS:await self._handle_command_status(ws, request, send_lock)return- if request.req_method == ReqMethod.BROWSER_START:- await self._handle_browser_start(ws, request, send_lock)- returnif request.req_method == ReqMethod.BROWSER_RUNTIME_RESTART:await self._handle_browser_runtime_restart(ws, request, send_lock)return@@ -5661,42 +5675,22 @@ class AgentWebSocketServer:async with send_lock:await send_wire_payload(ws, wire)- async def _handle_browser_start(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:- """启动浏览器并返回执行结果(returncode)。"""- try:- from jiuwenswarm.agents.harness.common.tools.browser_start_client import start_browser-- config_path = str(get_config_file())- returncode = start_browser(dry_run=False, config_file=config_path)- resp = AgentResponse(- request_id=request.request_id,- channel_id=request.channel_id,- ok=True,- payload={"returncode": returncode},- )- except Exception as e: # noqa: BLE001- logger.exception("[AgentWebSocketServer] browser.start failed: %s", e)- resp = AgentResponse(- request_id=request.request_id,- channel_id=request.channel_id,- ok=False,- payload={"error": str(e)},- )-- wire = encode_agent_response_for_wire(resp, response_id=request.request_id)- async with send_lock:- await send_wire_payload(ws, wire)-async def _handle_browser_runtime_restart(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:try:- from openjiuwen.harness.tools.browser_move import restart_local_browser_runtime_server+ from openjiuwen.harness.tools import browser_move- result = restart_local_browser_runtime_server()+ reset_runtimes = await _reset_active_browser_runtimes_if_available(+ browser_move+ )+ result = browser_move.restart_local_browser_runtime_server()resp = AgentResponse(request_id=request.request_id,channel_id=request.channel_id,ok=True,- payload={"result": result},+ payload={+ "result": result,+ "reset_runtimes": reset_runtimes,+ },)except Exception as e: # noqa: BLE001logger.exception("[AgentWebSocketServer] browser.runtime_restart failed: %s", e)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 1f1676537c..762541d099 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -979,6 +979,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):resolved_language = self._resolve_runtime_language()workspace = self._workspace_dir or "./"subagents: list[Any] = []+ self._sync_browser_runtime_environment(config_base)# ── 固定挂载:explore_agent(Code 模式核心子代理,始终启用)──if not self._subagent_list_has_name(subagents, "explore_agent"):@@ -1037,30 +1038,6 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):# browser_agentbrowser_agent_cfg = subagents_cfg.get("browser_agent")- # Headless setup is unconditional: swarm members also spawn @playwright/mcp- # subprocesses and ManagedBrowserDriver both read BROWSER_MANAGED_ARGS.- # This must run regardless of whether the main-agent browser subagent is enabled.- headless = self._resolve_headless_from_config()- _mcp_args_raw = (os.getenv("PLAYWRIGHT_MCP_ARGS") or "-y @playwright/mcp@latest").strip()- _mcp_args_list = _mcp_args_raw.split() if _mcp_args_raw else ["-y", "@playwright/mcp@latest"]- _mcp_args_list = [a for a in _mcp_args_list if a != "--headless"]- if headless:- _mcp_args_list.append("--headless")- os.environ["BROWSER_MANAGED_ARGS"] = "--headless=new"- logger.info(- "[JiuwenSwarmCodeAdapter] browser headless=True → "- "BROWSER_MANAGED_ARGS=--headless=new, PLAYWRIGHT_MCP_ARGS=%s",- " ".join(_mcp_args_list),- )- else:- os.environ.pop("BROWSER_MANAGED_ARGS", None)- logger.info(- "[JiuwenSwarmCodeAdapter] browser headless=False → "- "headed mode (BROWSER_MANAGED_ARGS cleared)",- )- os.environ["PLAYWRIGHT_MCP_ARGS"] = " ".join(_mcp_args_list)- self._browser_headless_setting = headless-browser_enabled = self._browser_runtime_enabled()if browser_enabled:if not str(os.getenv("BROWSER_DRIVER") or "").strip():@@ -1069,14 +1046,6 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):"[JiuwenSwarmCodeAdapter] browser subagent enabled without BROWSER_DRIVER; ""defaulting to managed mode")- if not str(os.getenv("BROWSER_MANAGED_BINARY") or "").strip():- chrome_path = self._resolve_managed_browser_binary_from_config()- if chrome_path:- os.environ["BROWSER_MANAGED_BINARY"] = chrome_path- logger.info(- "[JiuwenSwarmCodeAdapter] using browser.chrome_path for managed browser: %s",- chrome_path,- )browser_spec = build_browser_agent_config(model,workspace=workspace,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex bb9f0aee6b..3bd88cf0e4 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -296,7 +296,6 @@ from jiuwenswarm.common.utils import (get_env_file,get_prompt_attachment_dir,get_runtime_state_path,- get_user_workspace_dir,reset_free_search_runtime_flags,)@@ -886,7 +885,6 @@ class JiuWenSwarmDeepAdapter:self._last_models_config_fingerprint: str | None = Noneself._registered_mcp_server_ids: set[str] = set()self._registered_mcp_servers: dict[str, McpServerConfig] = {}- self._browser_headless_setting: bool | None = Noneself._auto_harness_service: Optional[AutoHarnessService] = Noneself._dreaming_started = Falseself._dreaming_mode: str = "agent"@@ -1640,9 +1638,12 @@ class JiuWenSwarmDeepAdapter:return value in {"1", "true", "yes", "on"}@staticmethod- def _resolve_managed_browser_binary_from_config() -> str:+ def _resolve_managed_browser_binary_from_config(+ config_base: dict[str, Any] | None = None,+ ) -> str:"""Resolve managed-browser binary from saved browser config."""- config_base = get_config()+ if config_base is None:+ config_base = get_config()if not isinstance(config_base, dict):return ""config = resolve_env_vars(config_base)@@ -1669,10 +1670,13 @@ class JiuWenSwarmDeepAdapter:return ""@staticmethod- def _resolve_headless_from_config() -> bool:+ def _resolve_headless_from_config(+ config_base: dict[str, Any] | None = None,+ ) -> bool:"""Read browser.headless from config (default True = headless)."""try:- config_base = get_config()+ if config_base is None:+ config_base = get_config()if not isinstance(config_base, dict):return Truebrowser_cfg = config_base.get("browser", {})@@ -1683,6 +1687,40 @@ class JiuWenSwarmDeepAdapter:except Exception:return True+ def _sync_browser_runtime_environment(+ self,+ config_base: dict[str, Any] | None = None,+ ) -> None:+ """Synchronize browser launch settings before browser runtimes are built."""+ headless = self._resolve_headless_from_config(config_base)+ mcp_args_raw = (+ os.getenv("PLAYWRIGHT_MCP_ARGS") or "-y @playwright/mcp@latest"+ ).strip()+ mcp_args = (+ mcp_args_raw.split()+ if mcp_args_raw+ else ["-y", "@playwright/mcp@latest"]+ )+ mcp_args = [arg for arg in mcp_args if arg != "--headless"]+ if headless:+ mcp_args.append("--headless")+ os.environ["BROWSER_MANAGED_ARGS"] = "--headless=new"+ else:+ os.environ.pop("BROWSER_MANAGED_ARGS", None)+ os.environ["PLAYWRIGHT_MCP_ARGS"] = " ".join(mcp_args)+ chrome_path = self._resolve_managed_browser_binary_from_config(config_base)+ if chrome_path:+ os.environ["BROWSER_MANAGED_BINARY"] = chrome_path+ else:+ os.environ.pop("BROWSER_MANAGED_BINARY", None)++ logger.info(+ "[%s] browser runtime config: headless=%s, chrome_path=%s",+ type(self).__name__,+ headless,+ chrome_path or "<auto>",+ )+@staticmethoddef _is_subagent_enabled(subagent_cfg: Any) -> bool:"""Treat only explicit `enabled: true` as enabled."""@@ -1733,53 +1771,9 @@ class JiuWenSwarmDeepAdapter:subagents_cfg.get("browser_agent") if isinstance(subagents_cfg, dict) else {})- # Apply headless setting unconditionally — PLAYWRIGHT_MCP_ARGS must be set- # even when the main-agent browser subagent is disabled, because swarm members- # also spawn @playwright/mcp subprocesses that read this env var at spec-build time.- headless = self._resolve_headless_from_config()- # @playwright/mcp@latest uses --headless CLI flag (not an env var).- # Rebuild PLAYWRIGHT_MCP_ARGS to add or strip --headless as needed.- _mcp_args_raw = (os.getenv("PLAYWRIGHT_MCP_ARGS") or "-y @playwright/mcp@latest").strip()- _mcp_args_list = _mcp_args_raw.split() if _mcp_args_raw else ["-y", "@playwright/mcp@latest"]- _mcp_args_list = [a for a in _mcp_args_list if a != "--headless"]- if headless:- _mcp_args_list.append("--headless")- os.environ["BROWSER_MANAGED_ARGS"] = "--headless=new"- # Purge any stale managed-browser profile whose extra_args lack- # --headless=new. The managed driver reuses a persisted profile- # by name and would inherit its stale extra_args=[] otherwise.- try:- from pathlib import Path as _Path- from jiuwenswarm.common.utils import get_user_workspace_dir as _get_ws- _profile_store = _Path(- os.getenv("BROWSER_PROFILE_STORE_PATH", "").strip()- or str(_get_ws() / ".browser" / "profiles.json")- ).expanduser()- if _profile_store.exists():- _profile_store.unlink()- logger.info(- "[JiuWenSwarmDeepAdapter] cleared stale browser profile store "- "for headless mode: %s",- _profile_store,- )- except Exception as _e:- logger.debug(- "[JiuWenSwarmDeepAdapter] could not clear browser profile store: %s", _e- )- logger.info(- "[JiuWenSwarmDeepAdapter] browser headless=True → "- "BROWSER_MANAGED_ARGS=--headless=new, PLAYWRIGHT_MCP_ARGS=%s",- " ".join(_mcp_args_list),- )- else:- os.environ.pop("BROWSER_MANAGED_ARGS", None)- logger.info(- "[JiuWenSwarmDeepAdapter] browser headless=False → "- "headed mode (BROWSER_MANAGED_ARGS cleared, PLAYWRIGHT_MCP_ARGS=%s)",- " ".join(_mcp_args_list),- )- os.environ["PLAYWRIGHT_MCP_ARGS"] = " ".join(_mcp_args_list)- self._browser_headless_setting = headless+ # Swarm members and the main browser subagent read these variables when+ # their browser runtimes are built.+ self._sync_browser_runtime_environment(config_base)browser_enabled = self._browser_runtime_enabled()if browser_enabled:@@ -1789,57 +1783,6 @@ class JiuWenSwarmDeepAdapter:"[JiuWenSwarmDeepAdapter] browser subagent enabled without BROWSER_DRIVER; ""defaulting to managed mode")- if not str(os.getenv("BROWSER_MANAGED_BINARY") or "").strip():- chrome_path = self._resolve_managed_browser_binary_from_config()- if chrome_path:- os.environ["BROWSER_MANAGED_BINARY"] = chrome_path- logger.info(- "[JiuWenSwarmDeepAdapter] using browser.chrome_path for managed browser: %s",- chrome_path,- )- headless = self._resolve_headless_from_config()- # @playwright/mcp@latest uses --headless CLI flag (not an env var).- # Rebuild PLAYWRIGHT_MCP_ARGS to add or strip --headless as needed.- _mcp_args_raw = (os.getenv("PLAYWRIGHT_MCP_ARGS") or "-y @playwright/mcp@latest").strip()- _mcp_args_list = _mcp_args_raw.split() if _mcp_args_raw else ["-y", "@playwright/mcp@latest"]- _mcp_args_list = [a for a in _mcp_args_list if a != "--headless"]- if headless:- os.environ["BROWSER_MANAGED_ARGS"] = "--headless=new"- _mcp_args_list.append("--headless")- # Purge any stale managed-browser profile that was persisted without- # --headless=new. If the profile store exists it will be read by the- # managed driver and its extra_args (empty []) will override- # BROWSER_MANAGED_ARGS, causing Chrome to launch headed regardless.- try:- _profile_store = Path(- os.getenv("BROWSER_PROFILE_STORE_PATH", "").strip()- or str(get_user_workspace_dir() / ".browser" / "profiles.json")- ).expanduser()- if _profile_store.exists():- _profile_store.unlink()- logger.info(- "[JiuWenSwarmDeepAdapter] cleared stale browser profile store "- "for headless mode: %s",- _profile_store,- )- except Exception as _e:- logger.debug(- "[JiuWenSwarmDeepAdapter] could not clear browser profile store: %s", _e- )- logger.info(- "[JiuWenSwarmDeepAdapter] browser headless=True → "- "BROWSER_MANAGED_ARGS=--headless=new, PLAYWRIGHT_MCP_ARGS=%s",- " ".join(_mcp_args_list),- )- else:- os.environ.pop("BROWSER_MANAGED_ARGS", None)- logger.info(- "[JiuWenSwarmDeepAdapter] browser headless=False → "- "headed mode (BROWSER_MANAGED_ARGS cleared, PLAYWRIGHT_MCP_ARGS=%s)",- " ".join(_mcp_args_list),- )- os.environ["PLAYWRIGHT_MCP_ARGS"] = " ".join(_mcp_args_list)- self._browser_headless_setting = headlesssubagents.append(build_browser_agent_config(model,@@ -4792,18 +4735,6 @@ class JiuWenSwarmDeepAdapter:# 加载用户自定义的 Rail 扩展await self.load_user_rails()- # Detect headless mode change before rebuilding subagents (which updates the env).- # _build_configured_subagents (called below) also sets self._browser_headless_setting,- # so capture the OLD value now.- _old_headless = self._browser_headless_setting- _new_browser_cfg = config_base.get("browser", {}) if isinstance(config_base, dict) else {}- _raw_headless = _new_browser_cfg.get("headless", True) if isinstance(_new_browser_cfg, dict) else True- _new_headless = bool(_raw_headless) if isinstance(_raw_headless, bool) else True- _headless_changed = (- _old_headless is not None- and _old_headless != _new_headless- )-deep_cfg = self._make_deep_agent_config(model=model,config=config,@@ -4820,89 +4751,6 @@ class JiuWenSwarmDeepAdapter:self._commit_reload_fingerprints(reload_fingerprints)self._sync_active_evolution_review_agent_after_reload()- if _headless_changed:- # The running playwright_official_stdio subprocess was started with the old- # headless args. Kill it so the next browser task spawns a fresh one with- # the updated PLAYWRIGHT_MCP_ARGS (set by _build_configured_subagents above).- await self._unregister_mcp_server("playwright_official_stdio")- # Kill the managed Chrome process so ManagedBrowserDriver.start() doesn't- # reuse it. start() checks _is_endpoint_ready() BEFORE kill_existing, so if- # Chrome is alive on port 9333 it returns the stale endpoint immediately,- # ignoring the new headless/headed args entirely.- _managed_port = int((os.getenv("BROWSER_MANAGED_PORT") or "9333").strip() or "9333")- try:- if os.name == "nt":- _netstat_exe = which("netstat") or r"C:\Windows\System32\netstat.exe"- _netstat = subprocess.run(- [_netstat_exe, "-ano"],- capture_output=True, text=True, timeout=10,- )- for _line in _netstat.stdout.splitlines():- _parts = _line.split()- if (- len(_parts) >= 5- and _parts[3] == "LISTENING"- and _parts[1].endswith(f":{_managed_port}")- ):- _pid = _parts[4]- if _pid.isdigit() and int(_pid) > 0:- _taskkill_exe = which("taskkill") or r"C:\Windows\System32\taskkill.exe"- subprocess.run(- [_taskkill_exe, "/F", "/PID", _pid],- capture_output=True, timeout=5,- )- logger.info(- "[JiuWenSwarmDeepAdapter] killed managed Chrome "- "PID=%s on port %s (headless %s→%s)",- _pid, _managed_port, _old_headless, _new_headless,- )- else:- _lsof_exe = which("lsof") or "/usr/bin/lsof"- _lsof = subprocess.run(- [_lsof_exe, "-ti", f"tcp:{_managed_port}"],- capture_output=True, text=True, timeout=10,- )- for _pid_str in _lsof.stdout.strip().splitlines():- if _pid_str.strip().isdigit():- _kill_exe = which("kill") or "/bin/kill"- subprocess.run(- [_kill_exe, "-9", _pid_str.strip()],- capture_output=True, timeout=5,- )- logger.info(- "[JiuWenSwarmDeepAdapter] killed managed Chrome "- "PID=%s on port %s (headless %s→%s)",- _pid_str.strip(), _managed_port, _old_headless, _new_headless,- )- except Exception as _kill_err:- logger.debug(- "[JiuWenSwarmDeepAdapter] could not kill managed Chrome on port %s: %s",- _managed_port, _kill_err,- )- # Also purge any stale managed-browser profile whose extra_args may still- # encode the old headless=new flag (or lack it).- try:- _profile_store = Path(- os.getenv("BROWSER_PROFILE_STORE_PATH", "").strip()- or str(get_user_workspace_dir() / ".browser" / "profiles.json")- ).expanduser()- if _profile_store.exists():- _profile_store.unlink()- logger.info(- "[JiuWenSwarmDeepAdapter] cleared stale browser profile store "- "on headless mode change (%s→%s): %s",- _old_headless, _new_headless, _profile_store,- )- except Exception as _e:- logger.debug(- "[JiuWenSwarmDeepAdapter] could not clear browser profile store: %s", _e- )- logger.info(- "[JiuWenSwarmDeepAdapter] browser headless changed %s→%s; "- "playwright_official_stdio subprocess will restart on next browser task",- _old_headless, _new_headless,- )-await self._sync_mcp_servers_for_runtime(config_base, tag="agent.reload")if not self._is_session_scoped_adapter:diff --git a/scripts/jiuwenswarm_exe_entry.py b/scripts/jiuwenswarm_exe_entry.pyindex 7a75b88b29..721cdce4e5 100644--- a/scripts/jiuwenswarm_exe_entry.py+++ b/scripts/jiuwenswarm_exe_entry.py@@ -357,13 +357,6 @@ def _dispatch() -> None:from jiuwenswarm.channels.desktop.desktop_app import main as desktop_maindesktop_main()return- # 子命令:浏览器启动(供主进程 subprocess 调用)- if "--browser-start-client" in sys.argv:- idx = sys.argv.index("--browser-start-client")- sys.argv.pop(idx)- from jiuwenswarm.agents.harness.common.tools.browser_start_client import main as browser_main- raise SystemExit(browser_main())-# 子进程模式:argv 有任何参数(.py 脚本或 -m 等),不检查单实例锁if getattr(sys, "frozen", False) and len(sys.argv) >= 2:script_path = next((arg for arg in sys.argv[1:] if arg.endswith(".py") or arg.endswith(".pyw")), None)diff --git a/tests/unit/deep_agent/test_browser_subagent_integration.py b/tests/unit/deep_agent/test_browser_subagent_integration.pyindex 9e52dd9733..678b50889f 100644--- a/tests/unit/deep_agent/test_browser_subagent_integration.py+++ b/tests/unit/deep_agent/test_browser_subagent_integration.py@@ -2,6 +2,7 @@from __future__ import annotations+import osfrom pathlib import Pathfrom unittest.mock import AsyncMock, MagicMock, patch@@ -154,6 +155,38 @@ def test_deep_adapter_subagents_defaults_to_none_when_unconfigured(assert subagents is None+def test_browser_runtime_environment_tracks_mode_and_chrome_path(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ adapter = _TestableJiuWenSwarmDeepAdapter()+ monkeypatch.setenv("BROWSER_MANAGED_BINARY", "C:\\stale\\chrome.exe")+ monkeypatch.setenv(+ "PLAYWRIGHT_MCP_ARGS",+ "-y @playwright/mcp@latest --headless",+ )++ adapter._sync_browser_runtime_environment(+ {+ "browser": {+ "chrome_path": "C:\\custom\\chrome.exe",+ "headless": False,+ }+ }+ )++ assert os.environ["BROWSER_MANAGED_BINARY"] == "C:\\custom\\chrome.exe"+ assert "BROWSER_MANAGED_ARGS" not in os.environ+ assert "--headless" not in os.environ["PLAYWRIGHT_MCP_ARGS"].split()++ adapter._sync_browser_runtime_environment(+ {"browser": {"chrome_path": "", "headless": True}}+ )++ assert "BROWSER_MANAGED_BINARY" not in os.environ+ assert os.environ["BROWSER_MANAGED_ARGS"] == "--headless=new"+ assert os.environ["PLAYWRIGHT_MCP_ARGS"].split().count("--headless") == 1++def test_deep_adapter_subagents_includes_browser_by_default_when_runtime_enabled(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -361,4 +394,4 @@ async def test_interface_deep_browser_subagent_task_tool_chain(assert runtime.ensure_started.await_count >= 1runtime.service.run_task.assert_awaited_once()run_task_kwargs = runtime.service.run_task.await_args.kwargs- assert run_task_kwargs["task"] == "Open https://example.com and summarize the page"\ No newline at end of file+ assert run_task_kwargs["task"] == "Open https://example.com and summarize the page"diff --git a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py b/tests/unit_tests/agentserver/test_agentserver_cli_commands.pyindex 96af152cac..96c1415ca1 100644--- a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py+++ b/tests/unit_tests/agentserver/test_agentserver_cli_commands.py@@ -1,5 +1,6 @@import asyncioimport json+from types import SimpleNamespaceimport pytest@@ -17,6 +18,9 @@ class FakeWebSocket:class AgentWebSocketServerHarness(agent_ws_server_module.AgentWebSocketServer):+ async def handle_browser_runtime_restart_for_test(self, ws, request, send_lock):+ await self._handle_browser_runtime_restart(ws, request, send_lock)+async def handle_command_add_dir_for_test(self, ws, request, send_lock):await self._handle_command_add_dir(ws, request, send_lock)@@ -75,6 +79,63 @@ def patch_wire_encoder(monkeypatch):)+async def test_browser_runtime_restart_resets_active_agent_runtimes(+ server,+ fake_ws,+ monkeypatch,+):+ from openjiuwen.harness.tools import browser_move++ async def fake_reset_active_browser_runtimes():+ return 2++ monkeypatch.setattr(+ browser_move,+ "reset_active_browser_runtimes",+ fake_reset_active_browser_runtimes,+ raising=False,+ )+ monkeypatch.setattr(+ browser_move,+ "restart_local_browser_runtime_server",+ lambda: {"status": "restarted"},+ )+ request = AgentRequest(+ request_id="req-browser-restart",+ channel_id="web",+ req_method=ReqMethod.BROWSER_RUNTIME_RESTART,+ )++ await server.handle_browser_runtime_restart_for_test(+ fake_ws,+ request,+ asyncio.Lock(),+ )++ assert fake_ws.sent == [+ {+ "response_id": "req-browser-restart",+ "payload": {+ "result": {"status": "restarted"},+ "reset_runtimes": 2,+ },+ "ok": True,+ }+ ]+++async def test_browser_runtime_restart_supports_sdk_without_runtime_reset():+ reset_runtimes = (+ await agent_ws_server_module._reset_active_browser_runtimes_if_available(+ SimpleNamespace()+ )+ )++ assert reset_runtimes == 0++@pytest.mark.asyncioasync def test_handle_command_add_dir_returns_path_and_remember(server, fake_ws, monkeypatchdiff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.pyindex 2c73c7d1c4..eed32ed1fe 100644--- a/tests/unit_tests/test_app_web_handlers.py+++ b/tests/unit_tests/test_app_web_handlers.py@@ -87,6 +87,63 @@ class FakeHeartbeatService:return dict(self.config)+async def test_path_set_reloads_config_and_resets_agent_browser_runtime(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ channel = FakeWebChannel()+ agent_client = object()+ saved_configs: list[dict] = []+ lifecycle_calls: list[tuple[str, object]] = []++ monkeypatch.setattr(+ app_web_handlers,+ "update_browser_in_config",+ lambda config: saved_configs.append(config),+ )++ async def fake_clear(client):+ lifecycle_calls.append(("reload", client))++ async def fake_restart(client):+ lifecycle_calls.append(("restart", client))++ monkeypatch.setattr(app_web_handlers, "_clear_agent_config_cache", fake_clear)+ monkeypatch.setattr(+ app_web_handlers,+ "_restart_agent_browser_runtime",+ fake_restart,+ )+ _register_web_handlers(+ WebHandlersBindParams(channel=channel, agent_client=agent_client)+ )++ await channel.methods["path.set"](+ object(),+ "req-path",+ {"chrome_path": " C:\\Chrome\\chrome.exe ", "headless": False},+ "sess-1",+ )++ assert saved_configs == [+ {"chrome_path": "C:\\Chrome\\chrome.exe", "headless": False}+ ]+ assert lifecycle_calls == [+ ("reload", agent_client),+ ("restart", agent_client),+ ]+ assert channel.responses[-1] == {+ "id": "req-path",+ "ok": True,+ "payload": {+ "chrome_path": "C:\\Chrome\\chrome.exe",+ "headless": False,+ },+ "error": None,+ "code": None,+ }++class FakeUpdaterService:def get_runtime_config(self):return {"release_api_type": "gitcode", "release_api_url": ""}diff --git a/tests/unit_tests/test_browser_start_client.py b/tests/unit_tests/test_browser_start_client.pydeleted file mode 100644index adebf8f98b..0000000000--- a/tests/unit_tests/test_browser_start_client.py+++ /dev/null@@ -1,204 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.--import threading-from types import SimpleNamespace--import pytest--from jiuwenswarm.agents.harness.common.tools import browser_start_client---class _FakeProcess:- def __init__(self, pid: int, ppid: int, executable: str, args: list[str]) -> None:- self.pid = pid- self.info = {"pid": pid, "ppid": ppid, "exe": executable, "cmdline": args}---def test_process_discovery_requires_matching_executable_port_and_profile(- monkeypatch: pytest.MonkeyPatch,- tmp_path,-) -> None:- chrome = str(tmp_path / "chrome.exe")- profile = str(tmp_path / "profile")- processes = [- _FakeProcess(- 10,- 1,- chrome,- [chrome, "--remote-debugging-port=9222", f"--user-data-dir={profile}"],- ),- _FakeProcess(- 11,- 1,- chrome,- [- chrome,- "--remote-debugging-port=9222",- f"--user-data-dir={tmp_path / 'other'}",- ],- ),- _FakeProcess(- 12,- 1,- chrome,- [chrome, "--remote-debugging-port=9333", f"--user-data-dir={profile}"],- ),- _FakeProcess(- 13,- 1,- str(tmp_path / "python.exe"),- ["python.exe", "--remote-debugging-port=9222", f"--user-data-dir={profile}"],- ),- ]- monkeypatch.setattr(browser_start_client.psutil, "process_iter", lambda _attrs: processes)-- result = browser_start_client._find_existing_browser_processes(- chrome_exec=chrome,- port=9222,- user_data_dir=profile,- )-- assert [process.pid for process in result] == [10]--- ("headless", "expected_headless_arg"),- [(False, False), (True, True)],-)-def test_start_browser_restarts_with_current_headless_setting(- monkeypatch: pytest.MonkeyPatch,- tmp_path,- headless: bool,- expected_headless_arg: bool,-) -> None:- chrome = str(tmp_path / "chrome.exe")- profile = str(tmp_path / "profile")- events: list[object] = []- monkeypatch.setattr(- browser_start_client,- "_load_browser_config",- lambda _path: {- "chrome_path": chrome,- "remote_debugging_address": "127.0.0.1",- "remote_debugging_port": 9222,- "user_data_dir": profile,- "profile_directory": "Default",- "headless": headless,- },- )- monkeypatch.setattr(browser_start_client, "_os_key", lambda: "windows")- monkeypatch.setattr(browser_start_client, "_normalize_chrome_executable", lambda *_: chrome)- monkeypatch.setattr(browser_start_client, "_parse_cdp_from_env", lambda host, port: (host, port))- monkeypatch.setattr(- browser_start_client,- "_stop_existing_browser_service",- lambda **kwargs: events.append(("stop", kwargs)) or [123],- )- monkeypatch.setattr(browser_start_client, "_port_is_open", lambda *_, **__: False)- monkeypatch.setattr(browser_start_client, "_persist_browser_profile", lambda **_: None)-- def fake_popen(args, **kwargs):- events.append(("popen", args, kwargs))- return SimpleNamespace(pid=456)-- monkeypatch.setattr(browser_start_client.subprocess, "Popen", fake_popen)-- assert browser_start_client.start_browser(config_file="config.yaml") == 0- assert events[0][0] == "stop"- assert ("--headless=new" in events[1][1]) is expected_headless_arg---def test_start_browser_refuses_unrecognized_port_owner(- monkeypatch: pytest.MonkeyPatch,- tmp_path,-) -> None:- chrome = str(tmp_path / "chrome.exe")- monkeypatch.setattr(- browser_start_client,- "_load_browser_config",- lambda _path: {"chrome_path": chrome, "headless": False},- )- monkeypatch.setattr(browser_start_client, "_os_key", lambda: "windows")- monkeypatch.setattr(browser_start_client, "_normalize_chrome_executable", lambda *_: chrome)- monkeypatch.setattr(browser_start_client, "_parse_cdp_from_env", lambda host, port: (host, port))- monkeypatch.setattr(browser_start_client, "_stop_existing_browser_service", lambda **_: [])- monkeypatch.setattr(browser_start_client, "_port_is_open", lambda *_, **__: True)- monkeypatch.setattr(- browser_start_client.subprocess,- "Popen",- lambda *_, **__: pytest.fail("Popen must not run for an unknown port owner"),- )-- with pytest.raises(RuntimeError, match="occupied by an unrecognized process"):- browser_start_client.start_browser(config_file="config.yaml")---def test_reap_watcher_invokes_stop_after_main_process_exit(- monkeypatch: pytest.MonkeyPatch,- tmp_path,-) -> None:- chrome = str(tmp_path / "chrome.exe")- profile = str(tmp_path / "profile")- release = threading.Event()- reap_calls: list[dict] = []-- monkeypatch.setattr(- browser_start_client,- "_load_browser_config",- lambda _path: {- "chrome_path": chrome,- "remote_debugging_address": "127.0.0.1",- "remote_debugging_port": 9222,- "user_data_dir": profile,- "profile_directory": "Default",- "headless": False,- },- )- monkeypatch.setattr(browser_start_client, "_os_key", lambda: "windows")- monkeypatch.setattr(browser_start_client, "_normalize_chrome_executable", lambda *_: chrome)- monkeypatch.setattr(browser_start_client, "_parse_cdp_from_env", lambda host, port: (host, port))- monkeypatch.setattr(browser_start_client, "_port_is_open", lambda *_, **__: False)- monkeypatch.setattr(browser_start_client, "_persist_browser_profile", lambda **_: None)-- def _fake_stop(**kwargs):- reap_calls.append(kwargs)- return []-- monkeypatch.setattr(- browser_start_client,- "_stop_existing_browser_service",- _fake_stop,- )-- class _FakePopen:- def __init__(self) -> None:- self.pid = 789-- def wait(self) -> int:- release.wait(timeout=5.0)- return 0-- fake_proc = _FakePopen()- monkeypatch.setattr(browser_start_client.subprocess, "Popen", lambda *a, **k: fake_proc)-- assert browser_start_client.start_browser(config_file="config.yaml") == 0- with browser_start_client._BROWSER_REGISTRY_LOCK:- assert 789 in browser_start_client._BROWSER_PROCESS_REGISTRY-- release.set()-- import time as _time-- deadline = _time.monotonic() + 5.0- while _time.monotonic() < deadline:- with browser_start_client._BROWSER_REGISTRY_LOCK:- reaped = 789 not in browser_start_client._BROWSER_PROCESS_REGISTRY- if reaped and reap_calls:- break- _time.sleep(0.02)-- assert reap_calls, "reap watcher did not invoke _stop_existing_browser_service"- assert reap_calls[-1]["chrome_exec"] == chrome- assert reap_calls[-1]["port"] == 9222- with browser_start_client._BROWSER_REGISTRY_LOCK:- assert 789 not in browser_start_client._BROWSER_PROCESS_REGISTRY