Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(browser): 保留重启登录状态并等待浏览器正常退出
Dasha5488d8c9108
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.tsindex cb955ac957..3acd17102b 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts@@ -25,6 +25,19 @@ function isInNet(host: string, pattern: string, mask: string): boolean {}describe('managed browser runtime config', () => {+ // Chromium's launch protocol controls session-cookie restoration after a+ // clean exit. Previously no route/profile enabled it, even with a persistent+ // user-data-dir. Unit tier covers config composition; a real Chrome restart+ // with a local HttpOnly session cookie verifies the browser behavior.+ it.each([+ { useRealProfile: false },+ { useRealProfile: true },+ { useRealProfile: false, proxyServer: 'http://proxy.example.test:8080' },+ { useRealProfile: true, proxyServer: 'http://proxy.example.test:8080' },+ ])('restores session cookies across restarts for %j', (options) => {+ expect(buildManagedConfig(options).browser?.extraArgs).toContain('--restore-last-session');+ });+it.each([false, true])('allows private-network browsing with useRealProfile=%s', (useRealProfile) => {expect(buildManagedConfig({ useRealProfile }).browser?.ssrfPolicy).toEqual({dangerouslyAllowPrivateNetwork: true,@@ -215,7 +228,8 @@ describe('managed browser runtime config', () => {});it('does not emit PAC args for a direct launch', () => {- expect(buildManagedConfig().browser?.extraArgs).toBeUndefined();+ expect(buildManagedConfig().browser?.extraArgs?.some((arg) => arg.startsWith('--proxy-')))+ .toBe(false);});it('keeps hostile hostname patterns as data, not PAC source', () => {@@ -269,7 +283,8 @@ describe('managed browser runtime config', () => {expect(proxied.join(' ')).not.toContain('--force-webrtc-ip-handling-policy');// A direct launch has no proxy to bypass, so it keeps default behavior.- expect(buildManagedConfig().browser?.extraArgs).toBeUndefined();+ expect(buildManagedConfig().browser?.extraArgs)+ .not.toContain('--webrtc-ip-handling-policy=disable_non_proxied_udp');});it('rejects a credentialed proxy URL before building any launch args', () => {diff --git a/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts b/apps/desktop/src/main/mcp-integrations/browser-managed-config.tsindex 40eef8988a..194193f72d 100644--- a/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts@@ -232,7 +232,13 @@ export function buildManagedConfig(options: ManagedBrowserConfigOptions = {}): BdefaultProfile,headless: false, // headed so the user can see + log into sites...(executablePath ? { executablePath } : {}),- ...(proxyServer ? { extraArgs: buildProxyLaunchArgs(proxyServer, route.allowedHostnames) } : {}),+ // A persistent directory alone does not restore session cookies after a+ // clean exit. Apply Chrome's native session restore to both profiles and+ // routes; --no-startup-window still keeps automation launches unobtrusive.+ extraArgs: [+ '--restore-last-session',+ ...(proxyServer ? buildProxyLaunchArgs(proxyServer, route.allowedHostnames) : []),+ ],// Two different contracts, so two different policies:// - DIRECT is the agent's own browser, where reaching the intranet is a// deliberate product decision (see the posture note above).diff --git a/packages/browser-control-runtime/src/__tests__/chrome-stop.test.ts b/packages/browser-control-runtime/src/__tests__/chrome-stop.test.tsnew file mode 100644index 0000000000..373844d50f--- /dev/null+++ b/packages/browser-control-runtime/src/__tests__/chrome-stop.test.ts@@ -0,0 +1,84 @@+import type { ChildProcessWithoutNullStreams } from "node:child_process";+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ stopOpenClawChrome,+ type RunningChrome,+} from "../_generated/extension/src/browser/chrome.js";++/**+ * Regression: stop treated ChildProcess.killed (signal sent) as process exit,+ * immediately SIGKILLing Chrome before it could flush login data. Existing+ * launch tests never exercise shutdown. A live fake process after SIGTERM is+ * the minimal input; unit tier uses virtual time, no real process or profile.+ */+function runningChrome(alreadySignalled = false) {+ const proc = {+ killed: alreadySignalled,+ exitCode: null as number | null,+ signalCode: null as NodeJS.Signals | null,+ kill: vi.fn((_signal: NodeJS.Signals) => {+ proc.killed = true;+ return true;+ }),+ };+ const release = vi.fn();+ const running: RunningChrome = {+ pid: 123,+ exe: { kind: "chrome", path: "/fake/chrome" },+ userDataDir: "/fake/profile",+ cdpPort: 18800,+ startedAt: 0,+ proc: proc as unknown as ChildProcessWithoutNullStreams,+ releaseCdpProxyBypass: release,+ };+ return { running, proc, release };+}++afterEach(() => vi.useRealTimers());++describe("managed Chrome shutdown", () => {+ it.each([false, true])(+ "waits for process exit with an earlier signal=%s",+ async (alreadySignalled) => {+ vi.useFakeTimers();+ const { running, proc, release } = runningChrome(alreadySignalled);+ let settled = false;+ const stopping = stopOpenClawChrome(running, 100).then(() => {+ settled = true;+ });+ await vi.advanceTimersByTimeAsync(50);+ expect(settled).toBe(false);+ expect(release).not.toHaveBeenCalled();+ expect(proc.kill.mock.calls).toEqual(+ alreadySignalled ? [] : [["SIGTERM"]],+ );++ proc.exitCode = 0;+ await vi.advanceTimersByTimeAsync(50);+ await stopping;+ expect(proc.kill).not.toHaveBeenCalledWith("SIGKILL");+ expect(release).toHaveBeenCalledOnce();+ },+ );++ it("force-stops an unresponsive process only after the grace period", async () => {+ vi.useFakeTimers();+ const { running, proc, release } = runningChrome();+ const stopping = stopOpenClawChrome(running, 100);+ await vi.advanceTimersByTimeAsync(99);+ expect(proc.kill.mock.calls).toEqual([["SIGTERM"]]);+ await vi.advanceTimersByTimeAsync(1);+ await stopping;+ expect(proc.kill.mock.calls).toEqual([["SIGTERM"], ["SIGKILL"]]);+ expect(release).toHaveBeenCalledOnce();+ });++ it("recognizes an exit caused by a signal and does not signal again", async () => {+ const { running, proc, release } = runningChrome();+ proc.signalCode = "SIGTERM";+ await stopOpenClawChrome(running, 100);+ expect(proc.kill).not.toHaveBeenCalled();+ expect(release).toHaveBeenCalledOnce();+ });+});diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/chrome.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/chrome.tsindex 205c8f3b13..ce8c7fdebe 100644--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/chrome.ts+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/chrome.ts@@ -1220,26 +1220,27 @@ export async function stopOpenClawChrome() {const proc = running.proc;try {- if (proc.killed) {+ if (proc.exitCode != null || proc.signalCode != null) {return;}- try {- proc.kill("SIGTERM");- } catch {- // ignore+ // LOCAL PATCH (Cindy, via sync.mjs): killed means a signal was sent,+ // not that Chrome exited. Give it the grace period to flush site data.+ if (!proc.killed) {+ try {+ proc.kill("SIGTERM");+ } catch {+ // ignore+ }}const start = Date.now();- while (Date.now() - start < timeoutMs) {- if (!proc.exitCode && proc.killed) {- break;- }- if (- !(await isChromeReachable(cdpUrlForPort(running.cdpPort), CHROME_STOP_PROBE_TIMEOUT_MS))- ) {+ while (true) {+ // CDP can disappear while Chrome is still flushing its profile.+ if (proc.exitCode != null || proc.signalCode != null) {return;}const remainingMs = timeoutMs - (Date.now() - start);+ if (remainingMs <= 0) break;await new Promise((r) => {setTimeout(r, Math.max(1, Math.min(100, remainingMs)));});diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.mdindex 74e6d2102c..06982ac7f8 100644--- a/packages/browser-control-runtime/upstream/MAINTAINING.md+++ b/packages/browser-control-runtime/upstream/MAINTAINING.md@@ -9,6 +9,16 @@默认行为:启动**一个专属、持久、headed 的自动化浏览器**(profile 名 "Cindy"),登录态长期保留,与用户日常 Chrome 互不影响。+登录持久性还依赖两点:host 的 `buildManagedConfig` 在两种 profile、直连及代理路径都传+`--restore-last-session`,否则 Chrome 正常退出后不会恢复会话 Cookie(仅有固定目录不够);+退出必须等待子进程的 `exitCode` / `signalCode`,不能把 `ChildProcess.killed`(已发信号)+或 CDP 不可达当成已退出,否则立即跟上的 SIGKILL 会打断登录数据落盘。+退出修正由 `sync.mjs` 的 LOCAL_PATCH 保留,回归见 `src/__tests__/chrome-stop.test.ts`。++「使用我的浏览器登录态」目前是**每次冷启动重新复制**,不是首次导入:只在 Agent 浏览器+里新增或续期的 Cookie 会被来源覆盖,站点 Local Storage / IndexedDB 也不跨快照保留。+这与默认专用 profile 的长期保留不同,修复退出及会话恢复不改变这项既有行为。+工具支持 `browser({action:"setBackend", backend:"rsb-webview"|"external"})`,由 MCP 层调用宿主注入的 `setBackend`,复用设置页的 `setActiveBrowserBackendKind`。这是全局持久选择,影响其他任务,可能中断旧浏览器操作;不迁移 Cookie、标签页或元素引用。`status.data.backend` 明确返回实际模式。切换后重新获取状态和标签页,不能把 `start` 当成切换。非 Desktop 宿主可以不提供此能力,工具会明确返回不支持。用户可在设置 → 自动操作打开「使用我的浏览器登录态」(默认关)。打开后,host 在 `start` 前把系统 Chrome / Edge / Brave **当前 `profile.last_used`** 的 Cookies / Login Data 等 SQLite 库拷进 `browser-runtime/browser/Cindy-real/user-data/Default`(vendored `--user-data-dir` 是 `.../Cindy-real/user-data`),并把 dest `Local State` 的 `last_used` / `last_active_profiles` / `profiles_order` **改写成 Default**(原样拷贝会让 Chrome 打开空的 `Profile N`,窗口看起来已登出)。Chrome 右上角 chip **始终显示 `Cindy`**:磁盘目录必须叫 `Cindy-real`(不能叠到隔离身份 `Cindy` 上),host 通过 `displayName: "Cindy"` 传给 runtime,`launchOpenClawChrome` 用它 decorate,而不是用 map key。再用**同一只浏览器二进制**启动该目录。不 attach 日常 Chrome(Chrome 136+ 会拒绝调试默认 user-data-dir)。关掉开关即删除 `Cindy-real`,`Cindy` 隔离身份不动。Cookies 缺失或复制失败必须 fail-closed,禁止启动一个看起来在浏览、其实全是登出的窗口。Login Data、Login Data For Account、Web Data 是可选的密码/自动填充库,锁定、权限或其它复制失败时跳过并清除目标中的旧副本,不阻止 Cookies 复用。SQLite 备份先取得读事务,可选库不等待锁;不直接复制活跃数据库及 WAL 文件。每次重拍快照会清掉 dest `Default` 里上一份来源留下的站点数据(Local Storage、站点 IndexedDB、Service Worker 等),但**扩展状态归 Agent 浏览器自己**,必须跨快照保留:`Default` 下名字含 `Extension` 的全部条目(`Extensions`、`Local Extension Settings`、`DNR Extension Rules`、`Extension Cookies` 及其 SQLite 边车等,按词匹配而非枚举,避免漏掉新存储)、`Secure Preferences`(扩展登记与 MAC)、`IndexedDB/chrome-extension_*`,以及 dest `Preferences` 的 `extensions` 子树(其余键仍从来源刷新);来源的扩展状态永不拷入。快照当凭证:不要写进日志正文、backup、device-link 或 worktree;`status` 暴露 `{ enabled, applied, source, warnings? }`,warnings 仅包含可选库名称与受控原因(locked / permission-denied / copy-failed),不暴露路径或原始错误。启动及隐式启动的工具结果附面向 Agent 的非阻塞诊断,指示继续执行且仅在实际登录需要协助时告知用户;设置页仍显示普通打开成功提示,不展示复制细节。快照状态跟本进程是否仍有已套用真实登录快照的托管浏览器走,不跟原操作的 ok:没有 live 浏览器时不得发布 applied / warnings;隐式 open/tabs/snapshot 拉起 Chrome 后即使失败或抛错,只要 status 仍是本进程 live pid 就必须发布。内部 stop 返回成功、或 vendored status 为 running:false 时都不得清除这些字段:readiness 下降不代表进程退出,证明 gone 是外层 resolveLiveness 的职责。诊断保留到下一次启动准备看不到本进程 live occupancy 为止。快照实现在 `apps/desktop/src/main/mcp-integrations/browser-real-profile/`;chip 名例外见 `sync.mjs` 对 `chrome.ts` 的 LOCAL_PATCH。diff --git a/packages/browser-control-runtime/upstream/browser-runtime.lock.json b/packages/browser-control-runtime/upstream/browser-runtime.lock.jsonindex cdef079038..68571b5eb4 100644--- a/packages/browser-control-runtime/upstream/browser-runtime.lock.json+++ b/packages/browser-control-runtime/upstream/browser-runtime.lock.json@@ -26,6 +26,10 @@"file": "extension/src/browser/chrome.executables.ts","desc": "classify macOS Google Chrome Beta within the Chrome-only fallback"},+ {+ "file": "extension/src/browser/chrome.ts",+ "desc": "wait for actual Chrome exit after SIGTERM so login data can flush before force-stop"+ },{"file": "extension/src/browser/chrome.ts","desc": "start headed automation Chrome without an empty foreground window"@@ -104,7 +108,7 @@}],"fileCount": 335,- "contentHash": "8aac31b28f77b2d9ea66ff460bb674fbab7a0bedb8200aa253f3d579f816f948",+ "contentHash": "2cd752b051eb29fd8db6b2feb2ff64881ce29fa2b0867e8e43baadc7cfe18295","fsSafe": {"package": "@openclaw/fs-safe","version": "0.4.0"diff --git a/scripts/browser-runtime/sync.mjs b/scripts/browser-runtime/sync.mjsindex 7e79d4754b..8e3a3e3a0c 100644--- a/scripts/browser-runtime/sync.mjs+++ b/scripts/browser-runtime/sync.mjs@@ -1594,6 +1594,50 @@ export async function quarantineTargetWithoutClosing(opts: {},],'extension/src/browser/chrome.ts': [+ {+ desc: 'wait for actual Chrome exit after SIGTERM so login data can flush before force-stop',+ find: ` if (proc.killed) {+ return;+ }+ try {+ proc.kill("SIGTERM");+ } catch {+ // ignore+ }++ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ if (!proc.exitCode && proc.killed) {+ break;+ }+ if (+ !(await isChromeReachable(cdpUrlForPort(running.cdpPort), CHROME_STOP_PROBE_TIMEOUT_MS))+ ) {+ return;+ }+ const remainingMs = timeoutMs - (Date.now() - start);`,+ replace: ` if (proc.exitCode != null || proc.signalCode != null) {+ return;+ }+ // LOCAL PATCH (Cindy, via sync.mjs): killed means a signal was sent,+ // not that Chrome exited. Give it the grace period to flush site data.+ if (!proc.killed) {+ try {+ proc.kill("SIGTERM");+ } catch {+ // ignore+ }+ }++ const start = Date.now();+ while (true) {+ // CDP can disappear while Chrome is still flushing its profile.+ if (proc.exitCode != null || proc.signalCode != null) {+ return;+ }+ const remainingMs = timeoutMs - (Date.now() - start);+ if (remainingMs <= 0) break;`,+ },{desc: 'start headed automation Chrome without an empty foreground window',find: ` if (headlessMode.headless) {\n args.push("--headless=new");\n args.push("--disable-gpu");\n }`,