Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(browser): 使用系统登录态时保留 Agent 浏览器里装的扩展 (#5372)
Dashc261c9d205d1
diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.tsindex 7628def45f..973d6b5d9f 100644--- a/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.ts@@ -236,13 +236,149 @@ describe('snapshotRealProfile', () => {fs.writeFileSync(path.join(destDefault, 'GPUCache', 'data'), 'gpu');await snapshotRealProfile({ source, destDir, platform: 'darwin' });expect(fs.existsSync(path.join(destDefault, 'Local Storage'))).toBe(false);- expect(fs.existsSync(path.join(destDefault, 'IndexedDB'))).toBe(false);+ expect(fs.existsSync(path.join(destDefault, 'IndexedDB', 'site'))).toBe(false);expect(fs.existsSync(path.join(destDefault, 'Service Worker'))).toBe(false);expect(fs.readFileSync(path.join(destDefault, 'GPUCache', 'data'), 'utf8')).toBe('gpu');expect(fs.existsSync(path.join(destDefault, 'Cookies'))).toBe(true);expect(leftoverStagingNames(destDir)).toEqual([]);});+ it('keeps extensions installed in the agent browser across re-snapshots', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ const destDefault = path.join(destDir, 'Default');+ const extensionId = 'aeblfdkhhhdcdjpifhhbdiojplfjncoa';+ const extensionIdb = `chrome-extension_${extensionId}_0.indexeddb.leveldb`;+ fs.mkdirSync(path.join(destDefault, 'Extensions', extensionId, '8.0.0_0'), { recursive: true });+ fs.writeFileSync(+ path.join(destDefault, 'Extensions', extensionId, '8.0.0_0', 'manifest.json'),+ '{}',+ );+ fs.writeFileSync(+ path.join(destDefault, 'Secure Preferences'),+ '{"extensions":{"settings":{}}}',+ );+ fs.mkdirSync(path.join(destDefault, 'Local Extension Settings', extensionId), {+ recursive: true,+ });+ fs.mkdirSync(path.join(destDefault, 'IndexedDB', extensionIdb), { recursive: true });+ fs.mkdirSync(path.join(destDefault, 'IndexedDB', 'https_example.com_0.indexeddb.leveldb'), {+ recursive: true,+ });+ const extensionCookieFiles = [+ 'Extension Cookies',+ 'Extension Cookies-wal',+ 'Extension Cookies-journal',+ ];+ for (const name of extensionCookieFiles) {+ fs.writeFileSync(path.join(destDefault, name), name);+ }+ fs.mkdirSync(path.join(destDefault, 'DNR Extension Rules', extensionId), { recursive: true });++ await snapshotRealProfile({ source, destDir, platform: 'darwin' });++ for (const name of extensionCookieFiles) {+ expect(fs.readFileSync(path.join(destDefault, name), 'utf8'), name).toBe(name);+ }+ expect(fs.existsSync(path.join(destDefault, 'DNR Extension Rules', extensionId))).toBe(true);++ expect(+ fs.existsSync(path.join(destDefault, 'Extensions', extensionId, '8.0.0_0', 'manifest.json')),+ ).toBe(true);+ expect(fs.readFileSync(path.join(destDefault, 'Secure Preferences'), 'utf8')).toBe(+ '{"extensions":{"settings":{}}}',+ );+ expect(fs.existsSync(path.join(destDefault, 'Local Extension Settings', extensionId))).toBe(+ true,+ );+ expect(fs.readdirSync(path.join(destDefault, 'IndexedDB'))).toEqual([extensionIdb]);+ });++ it('refreshes Preferences from the source but keeps the agent browser extensions subtree', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const sourcePrefs = path.join(source.userDataDir, 'Profile 6', 'Preferences');+ fs.writeFileSync(+ sourcePrefs,+ JSON.stringify({ session: { restore_on_startup: 1 }, extensions: { commands: 'source' } }),+ );+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ const destPrefs = path.join(destDir, 'Default', 'Preferences');++ await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ expect(JSON.parse(fs.readFileSync(destPrefs, 'utf8'))).toEqual({+ session: { restore_on_startup: 1 },+ });++ fs.writeFileSync(+ destPrefs,+ JSON.stringify({+ session: { restore_on_startup: 5 },+ extensions: { install_signature: 'agent' },+ }),+ );+ fs.writeFileSync(+ sourcePrefs,+ JSON.stringify({ session: { restore_on_startup: 4 }, extensions: { commands: 'source' } }),+ );+ await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ expect(JSON.parse(fs.readFileSync(destPrefs, 'utf8'))).toEqual({+ session: { restore_on_startup: 4 },+ extensions: { install_signature: 'agent' },+ });+ });++ it('copies a malformed source Preferences verbatim', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ fs.writeFileSync(path.join(source.userDataDir, 'Profile 6', 'Preferences'), 'not-json');+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ expect(fs.readFileSync(path.join(destDir, 'Default', 'Preferences'), 'utf8')).toBe('not-json');+ });++ it('keeps a valid dest Preferences when the source one is malformed or missing', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ const destPrefs = path.join(destDir, 'Default', 'Preferences');+ const agentPrefs = JSON.stringify({ extensions: { install_signature: 'agent' } });+ fs.writeFileSync(destPrefs, agentPrefs);+ const sourcePrefs = path.join(source.userDataDir, 'Profile 6', 'Preferences');+ fs.writeFileSync(sourcePrefs, '{"trunc');++ await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ expect(fs.readFileSync(destPrefs, 'utf8')).toBe(agentPrefs);++ fs.rmSync(sourcePrefs);+ await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ expect(fs.readFileSync(destPrefs, 'utf8')).toBe(agentPrefs);+ });++ it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'fails the snapshot when leftover site IndexedDB cannot be enumerated',+ async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ const indexedDb = path.join(destDir, 'Default', 'IndexedDB');+ fs.mkdirSync(path.join(indexedDb, 'https_example.com_0.indexeddb.leveldb'), {+ recursive: true,+ });+ fs.chmodSync(indexedDb, 0o000);+ try {+ await expect(+ snapshotRealProfile({ source, destDir, platform: 'darwin' }),+ ).rejects.toThrow();+ expect(fs.existsSync(path.join(destDir, '.cindy-real-profile-complete'))).toBe(false);+ } finally {+ fs.chmodSync(indexedDb, 0o700);+ }+ },+ );+it('refuses to write anywhere except Cindy-real/user-data', async () => {const root = makeTempDir();const source = seedSource(root);diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/snapshot.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/snapshot.tsindex d03fd02e90..f4a10462bc 100644--- a/apps/desktop/src/main/mcp-integrations/browser-real-profile/snapshot.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/snapshot.ts@@ -142,23 +142,91 @@ const DISCARDABLE_PROFILE_CACHE_NAMES = new Set([]);/**- * Drop leftover Local Storage / IndexedDB / Service Worker / etc. from a- * previous source profile. Keep only this snapshot's auth files and caches.+ * State of extensions installed inside the agent browser. Never copied from+ * the source profile, so it carries no source credentials; dropping it on every+ * launch would uninstall the user's agent-browser extensions.+ *+ * Chrome names every profile-level extension store with "Extension"+ * (`Extensions`, `Local Extension Settings`, `Extension State`,+ * `DNR Extension Rules`, `Extension Cookies` and its SQLite `-wal` / `-journal`+ * sidecars, ...), so match the word rather than enumerate a list that misses+ * new stores. `Secure Preferences` holds the extension registry and its MACs.+ */+function isAgentExtensionState(name: string): boolean {+ return name === 'Secure Preferences' || /Extension/.test(name);+}++/** Per-origin IndexedDB folder owned by an extension (e.g. 1Password's vault). */+const EXTENSION_INDEXED_DB_ENTRY = /^chrome-extension_/;++/** Throws on enumeration failure so leftover site data blocks the snapshot, like `rmSync` does. */+function pruneSiteIndexedDb(indexedDbDir: string): void {+ for (const entry of fs.readdirSync(indexedDbDir, { withFileTypes: true })) {+ if (EXTENSION_INDEXED_DB_ENTRY.test(entry.name)) continue;+ fs.rmSync(path.join(indexedDbDir, entry.name), { recursive: true, force: true });+ }+}++/**+ * Drop leftover Local Storage / site IndexedDB / Service Worker / etc. from a+ * previous source profile. Keep this snapshot's auth files, caches, and the+ * agent browser's own extension state.*/export function pruneNonAuthProfileState(destProfileDir: string): void {const keep = new Set<string>(DISCARDABLE_PROFILE_CACHE_NAMES);for (const relative of SNAPSHOT_PROFILE_RELATIVE_PATHS) {keep.add(relative.split(/[/\\]/)[0] ?? relative);}- let entries: fs.Dirent[];+ for (const entry of fs.readdirSync(destProfileDir, { withFileTypes: true })) {+ if (keep.has(entry.name) || isAgentExtensionState(entry.name)) continue;+ if (entry.name === 'IndexedDB' && entry.isDirectory()) {+ pruneSiteIndexedDb(path.join(destProfileDir, entry.name));+ continue;+ }+ fs.rmSync(path.join(destProfileDir, entry.name), { recursive: true, force: true });+ }+}++function parseJsonObject(raw: string | null): Record<string, unknown> | null {+ if (raw === null) return null;try {- entries = fs.readdirSync(destProfileDir, { withFileTypes: true });+ return asObject(JSON.parse(raw) as unknown);} catch {- return;+ return null;}- for (const entry of entries) {- if (keep.has(entry.name)) continue;- fs.rmSync(path.join(destProfileDir, entry.name), { recursive: true, force: true });+}++/**+ * Source `Preferences` refreshed onto dest, except the `extensions` subtree,+ * which belongs to the agent browser (install signature, commands, pins).+ * When the source is missing or not a JSON object (e.g. caught mid-write),+ * keep a valid dest unchanged rather than drop its extension state; return+ * null only when neither side is usable, so the caller falls back to the source+ * file as-is (or to no file).+ */+export function mergeManagedPreferences(+ sourceRaw: string | null,+ destRaw: string | null,+): string | null {+ const dest = parseJsonObject(destRaw);+ const source = parseJsonObject(sourceRaw);+ if (!source) return dest ? destRaw : null;+ const merged = { ...source };+ const destExtensions = dest?.extensions;+ if (destExtensions === undefined) {+ delete merged.extensions;+ } else {+ merged.extensions = destExtensions;+ }+ return JSON.stringify(merged);+}++function readFileIfExists(filePath: string): string | null {+ try {+ return fs.readFileSync(filePath, 'utf8');+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw err;}}@@ -533,9 +601,18 @@ export async function snapshotRealProfile(options: {for (const relative of PLAIN_PROFILE_FILES) {const src = path.join(sourceProfileDir, relative);- if (!fs.existsSync(src)) continue;+ const sourceRaw = readFileIfExists(src);const dest = path.join(stagingProfileDir, relative);- await fs.promises.copyFile(src, dest);+ const merged = mergeManagedPreferences(+ sourceRaw,+ readFileIfExists(path.join(destDir, 'Default', relative)),+ );+ if (merged === null) {+ if (sourceRaw === null) continue;+ await fs.promises.copyFile(src, dest);+ } else {+ await fs.promises.writeFile(dest, merged, 'utf8');+ }filesCopied.push(path.join('Default', relative));copiedRelative.add(relative);}diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.mdindex 9f67cbc107..ea3276b25c 100644--- a/packages/browser-control-runtime/upstream/MAINTAINING.md+++ b/packages/browser-control-runtime/upstream/MAINTAINING.md@@ -11,7 +11,7 @@工具支持 `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 文件。快照当凭证:不要写进日志正文、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。+用户可在设置 → 自动操作打开「使用我的浏览器登录态」(默认关)。打开后,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。## 2. 三层架构 + 文件清单