Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(browser): 密码库复制失败时静默继续启动 (#4535)
Dash83c3dc3eb5e5
diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/launch.test.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/launch.test.tsindex ae8d3dad91..5d80979bc7 100644--- a/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/launch.test.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/launch.test.ts@@ -31,6 +31,14 @@ function fakeInner(state: { running: boolean; headless?: boolean; starts: numberstate.running = true;return result('start', { running: true });}+ if (request.action === 'open') {+ state.running = true;+ return result('open', { running: true });+ }+ if (request.action === 'stop') {+ state.running = false;+ return result('stop', { stopped: true });+ }return result(request.action, {});},};@@ -45,6 +53,388 @@ const chrome: InstalledChromium = {const pick18800 = async () => 18800;describe('wrapRuntimeWithRealProfile', () => {+ it.each(['start', 'open'] as const)(+ 'reports optional copy warnings on %s and status, then clears them on retry',+ async (action) => {+ const state = { running: false, starts: 0 };+ const warnings = [{ database: 'Login Data' as const, reason: 'locked' as const }];+ const snapshotResult = {+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome' as const,+ sourceProfile: 'Default',+ filesCopied: ['Cookies'],+ };+ const snapshot = vi+ .fn()+ .mockResolvedValueOnce({ ...snapshotResult, warnings })+ .mockResolvedValue(snapshotResult);+ const wrapped = wrapRuntimeWithRealProfile(fakeInner(state), {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ });+ const launched = await wrapped.call({ action });+ expect(launched.ok).toBe(true);+ expect(launched.message).toContain('Login Data (database is locked by another process)');+ expect(launched.message).toContain('continue the task without notifying the user');+ expect(launched.data).toMatchObject({ realProfile: { warnings, applied: true } });+ expect((await wrapped.call({ action: 'status' })).data).toMatchObject({+ realProfile: { warnings },+ });++ await wrapped.call({ action: 'stop' });+ expect((await wrapped.call({ action: 'status' })).data).toMatchObject({+ realProfile: { applied: true, warnings },+ });+ const retried = await wrapped.call({ action: 'start' });+ expect(retried.message).toBeUndefined();+ expect(JSON.stringify((await wrapped.call({ action: 'status' })).data)).not.toContain(+ 'warnings',+ );+ },+ );++ it.each([+ ['start', 'failure'],+ ['start', 'throw'],+ ['open', 'failure'],+ ['open', 'throw'],+ ] as const)('does not publish snapshot state when %s ends with %s', async (action, outcome) => {+ const warnings = [{ database: 'Login Data' as const, reason: 'locked' as const }];+ let fail = true;+ const wrapped = wrapRuntimeWithRealProfile(+ {+ async call(request) {+ if (request.action === 'status') return result('status', { running: false });+ if (fail && outcome === 'throw') throw new Error('browser launch failed');+ return result(request.action, {}, !fail);+ },+ },+ {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot: vi.fn().mockResolvedValue({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome',+ sourceProfile: 'Default',+ filesCopied: ['Cookies'],+ warnings,+ }),+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ },+ );+ if (outcome === 'throw') {+ await expect(wrapped.call({ action })).rejects.toThrow('browser launch failed');+ } else {+ expect((await wrapped.call({ action })).ok).toBe(false);+ }+ expect((await wrapped.call({ action: 'status' })).data).toMatchObject({+ realProfile: { applied: false, source: null },+ });+ expect(JSON.stringify((await wrapped.call({ action: 'status' })).data)).not.toContain(+ 'warnings',+ );+ fail = false;+ expect((await wrapped.call({ action })).data).toMatchObject({+ realProfile: { applied: true, warnings },+ });+ });++ it.each(['open', 'tabs', 'snapshot'] as const)(+ 'publishes snapshot state when %s fails after the managed browser is already live',+ async (action) => {+ const warnings = [{ database: 'Login Data' as const, reason: 'locked' as const }];+ let live = false;+ const snapshot = vi.fn().mockResolvedValue({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome',+ sourceProfile: 'Default',+ filesCopied: ['Cookies'],+ warnings,+ });+ const wrapped = wrapRuntimeWithRealProfile(+ {+ async call(request) {+ if (request.action === 'status') {+ return result(+ 'status',+ live+ ? {+ running: true,+ pid: 4321,+ userDataDir: '/runtime/browser/Cindy-real/user-data',+ }+ : { running: false },+ );+ }+ if (request.action === action) {+ live = true;+ return result(request.action, {}, false);+ }+ return result(request.action, {});+ },+ },+ {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ },+ );+ expect((await wrapped.call({ action })).ok).toBe(false);+ expect((await wrapped.call({ action: 'status' })).data).toMatchObject({+ realProfile: { applied: true, source: 'chrome', warnings },+ });+ expect((await wrapped.call({ action: 'start' })).ok).toBe(true);+ expect(snapshot).toHaveBeenCalledOnce();+ },+ );++ it.each(['open', 'tabs'] as const)(+ 'publishes snapshot state when %s throws after the managed browser is already live',+ async (action) => {+ const warnings = [{ database: 'Web Data' as const, reason: 'copy-failed' as const }];+ let live = false;+ const snapshot = vi.fn().mockResolvedValue({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome',+ sourceProfile: 'Default',+ filesCopied: ['Cookies'],+ warnings,+ });+ const wrapped = wrapRuntimeWithRealProfile(+ {+ async call(request) {+ if (request.action === 'status') {+ return result(+ 'status',+ live+ ? {+ running: true,+ pid: 4321,+ userDataDir: '/runtime/browser/Cindy-real/user-data',+ }+ : { running: false },+ );+ }+ if (request.action === action) {+ live = true;+ throw new Error('page action failed');+ }+ return result(request.action, {});+ },+ },+ {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ },+ );+ await expect(wrapped.call({ action })).rejects.toThrow('page action failed');+ expect((await wrapped.call({ action: 'status' })).data).toMatchObject({+ realProfile: { applied: true, source: 'chrome', warnings },+ });+ expect((await wrapped.call({ action: 'start' })).ok).toBe(true);+ expect(snapshot).toHaveBeenCalledOnce();+ },+ );++ it('keeps snapshot state when stop returns ok but the managed browser is still live', async () => {+ const warnings = [{ database: 'Login Data' as const, reason: 'locked' as const }];+ let live = false;+ const snapshot = vi.fn().mockResolvedValue({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome',+ sourceProfile: 'Default',+ filesCopied: ['Cookies'],+ warnings,+ });+ const wrapped = wrapRuntimeWithRealProfile(+ {+ async call(request) {+ if (request.action === 'status') {+ return result(+ 'status',+ live+ ? {+ running: true,+ pid: 4321,+ userDataDir: '/runtime/browser/Cindy-real/user-data',+ }+ : { running: false },+ );+ }+ if (request.action === 'start') {+ live = true;+ return result('start', {});+ }+ if (request.action === 'stop') {+ return result('stop', { stopped: true });+ }+ return result(request.action, {});+ },+ },+ {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ },+ );+ expect((await wrapped.call({ action: 'start' })).ok).toBe(true);+ expect((await wrapped.call({ action: 'stop' })).ok).toBe(true);+ expect((await wrapped.call({ action: 'status' })).data).toMatchObject({+ realProfile: { applied: true, source: 'chrome', warnings },+ });+ expect((await wrapped.call({ action: 'start' })).ok).toBe(true);+ expect(snapshot).toHaveBeenCalledOnce();+ live = false;+ expect((await wrapped.call({ action: 'status' })).data).toMatchObject({+ realProfile: { applied: true, source: 'chrome', warnings },+ });+ });++ it('keeps snapshot state when stop fails while the managed browser is still live', async () => {+ const warnings = [{ database: 'Web Data' as const, reason: 'copy-failed' as const }];+ let live = false;+ const snapshot = vi.fn().mockResolvedValue({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome',+ sourceProfile: 'Default',+ filesCopied: ['Cookies'],+ warnings,+ });+ const wrapped = wrapRuntimeWithRealProfile(+ {+ async call(request) {+ if (request.action === 'status') {+ return result(+ 'status',+ live+ ? {+ running: true,+ pid: 4321,+ userDataDir: '/runtime/browser/Cindy-real/user-data',+ }+ : { running: false },+ );+ }+ if (request.action === 'start') {+ live = true;+ return result('start', {});+ }+ if (request.action === 'stop') {+ return result('stop', { stopped: false }, false);+ }+ return result(request.action, {});+ },+ },+ {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ },+ );+ expect((await wrapped.call({ action: 'start' })).ok).toBe(true);+ expect((await wrapped.call({ action: 'stop' })).ok).toBe(false);+ expect((await wrapped.call({ action: 'status' })).data).toMatchObject({+ realProfile: { applied: true, source: 'chrome', warnings },+ });+ });++ it('clears optional warnings after a later cookie copy failure and when disabled', async () => {+ let enabled = true;+ const snapshot = vi+ .fn()+ .mockResolvedValueOnce({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome',+ sourceProfile: 'Default',+ filesCopied: ['Cookies'],+ warnings: [{ database: 'Web Data', reason: 'copy-failed' }],+ })+ .mockRejectedValue(new RealProfileError('PROFILE_LOCKED', 'Cookie database is locked'));+ const wrapped = wrapRuntimeWithRealProfile(fakeInner({ running: false, starts: 0 }), {+ isEnabled: () => enabled,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ });+ expect((await wrapped.call({ action: 'start' })).ok).toBe(true);+ enabled = false;+ expect(JSON.stringify((await wrapped.call({ action: 'status' })).data)).not.toContain(+ 'warnings',+ );+ enabled = true;+ expect((await wrapped.call({ action: 'start' })).ok).toBe(false);+ expect(JSON.stringify((await wrapped.call({ action: 'status' })).data)).not.toContain(+ 'warnings',+ );+ });++ it('retains warnings when reopening the live browser without resnapshotting', async () => {+ let running = false;+ const snapshot = vi.fn().mockResolvedValue({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome',+ sourceProfile: 'Default',+ filesCopied: ['Cookies'],+ warnings: [{ database: 'Login Data', reason: 'locked' }],+ });+ const wrapped = wrapRuntimeWithRealProfile(+ {+ async call(request) {+ if (request.action === 'status')+ return result(+ 'status',+ running+ ? { running: true, pid: 1234, userDataDir: '/runtime/browser/Cindy-real/user-data' }+ : { running: false },+ );+ running = true;+ return result(request.action, {});+ },+ },+ {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ },+ );+ await wrapped.call({ action: 'start' });+ expect((await wrapped.call({ action: 'start' })).message).toContain('Login Data');+ expect((await wrapped.call({ action: 'navigate' })).message).toBeUndefined();+ expect(snapshot).toHaveBeenCalledOnce();+ });+it('snapshots then starts when consent is on and the browser is stopped', async () => {const inner = fakeInner({ running: false, starts: 0 });const applyConfig = vi.fn();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 0390e418d0..7628def45f 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@@ -326,8 +326,12 @@ describe('snapshotRealProfile', () => {fs.mkdirSync(path.join(destDir, 'Default'), { recursive: true });writeSqlite(path.join(destDir, 'Default', 'Cookies'), 'cookies', 'stale-cookie');writeSqlite(path.join(destDir, 'Default', 'Login Data'), 'logins', 'stale-login');- // Cookies copies first; a corrupt Login Data fails the later backup.- fs.writeFileSync(path.join(source.userDataDir, 'Profile 6', 'Login Data'), 'not-a-sqlite-db');+ // The first cookie DB copies; failure of another required cookie DB must+ // still leave the previous complete snapshot untouched.+ fs.writeFileSync(+ path.join(source.userDataDir, 'Profile 6', 'Network', 'Cookies'),+ 'not-a-sqlite-db',+ );await expect(snapshotRealProfile({ source, destDir, platform: 'darwin' }),@@ -340,6 +344,95 @@ describe('snapshotRealProfile', () => {expect(leftoverStagingNames(destDir)).toEqual([]);});+ it.each(['darwin', 'win32', 'linux'] as const)(+ 'copies cookies while optional stores have exclusive SQLite locks (%s)',+ async (platform) => {+ const source = seedSource(makeTempDir());+ const profile = path.join(source.userDataDir, 'Profile 6');+ const destDir = realProfileDestDir(path.join(makeTempDir(), 'runtime'));+ const names = ['Login Data', 'Login Data For Account', 'Web Data'] as const;+ writeSqlite(path.join(profile, names[1]), 'logins', 'account-password');+ writeSqlite(path.join(profile, names[2]), 'autofill', 'saved-form');+ await snapshotRealProfile({ source, destDir, platform });+ const locks = names.map((name) => {+ const db = new DatabaseSync(path.join(profile, name));+ db.exec('PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE;');+ return db;+ });+ try {+ const result = await snapshotRealProfile({ source, destDir, platform });+ expect(result.warnings).toEqual(names.map((database) => ({ database, reason: 'locked' })));+ expect(readSqlite(path.join(destDir, 'Default', 'Cookies'), 'cookies')).toBe(+ 'session-cookie',+ );+ for (const name of names) {+ // Never leave an old password store from a previous snapshot behind.+ expect(fs.existsSync(path.join(destDir, 'Default', name))).toBe(false);+ expect(result.filesCopied).not.toContain(path.join('Default', name));+ }+ expect(leftoverStagingNames(destDir)).toEqual([]);+ } finally {+ for (const db of locks) db.close();+ }+ const retry = await snapshotRealProfile({ source, destDir, platform });+ expect(retry.warnings).toBeUndefined();+ expect(readSqlite(path.join(destDir, 'Default', 'Login Data'), 'logins')).toBe(+ 'saved-password',+ );+ },+ );++ it('skips a corrupt password database with a controlled warning', async () => {+ const source = seedSource(makeTempDir());+ const destDir = realProfileDestDir(path.join(makeTempDir(), 'runtime'));+ fs.writeFileSync(path.join(source.userDataDir, 'Profile 6', 'Login Data'), 'not-a-sqlite-db');+ const result = await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ expect(result.warnings).toEqual([{ database: 'Login Data', reason: 'copy-failed' }]);+ expect(fs.existsSync(path.join(destDir, 'Default', 'Login Data'))).toBe(false);+ expect(readSqlite(path.join(destDir, 'Default', 'Cookies'), 'cookies')).toBe('session-cookie');+ });++ it.each(['darwin', 'win32'] as const)(+ 'skips optional read denial without exposing paths (%s)',+ async (platform) => {+ const source = seedSource(makeTempDir());+ const destDir = realProfileDestDir(path.join(makeTempDir(), 'runtime'));+ const realOpen = fs.openSync.bind(fs);+ vi.spyOn(fs, 'openSync').mockImplementation(((file, flags, mode) => {+ if (String(file) === path.join(source.userDataDir, 'Profile 6', 'Login Data')) {+ throw Object.assign(new Error(`Access denied: ${file}`), { code: 'EACCES' });+ }+ return realOpen(file, flags, mode);+ }) as typeof fs.openSync);+ try {+ const result = await snapshotRealProfile({ source, destDir, platform });+ expect(result.warnings).toEqual([{ database: 'Login Data', reason: 'permission-denied' }]);+ expect(fs.existsSync(path.join(destDir, 'Default', 'Login Data'))).toBe(false);+ expect(readSqlite(path.join(destDir, 'Default', 'Cookies'), 'cookies')).toBe(+ 'session-cookie',+ );+ } finally {+ vi.restoreAllMocks();+ }+ },+ );++ it('fails closed with a lock reason when the required cookie DB is locked', async () => {+ const source = seedSource(makeTempDir());+ const destDir = realProfileDestDir(path.join(makeTempDir(), 'runtime'));+ const db = new DatabaseSync(path.join(source.userDataDir, 'Profile 6', 'Cookies'));+ db.exec('PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE;');+ try {+ await expect(+ snapshotRealProfile({ source, destDir, platform: 'darwin' }),+ ).rejects.toMatchObject({ code: 'PROFILE_LOCKED' });+ expect(fs.existsSync(destDir)).toBe(false);+ expect(leftoverStagingNames(destDir)).toEqual([]);+ } finally {+ db.close();+ }+ }, 10_000);+it('uses sqlite backup so dest has no WAL sidecar from the source', async () => {const root = makeTempDir();const source = seedSource(root);@@ -378,11 +471,11 @@ describe('snapshotRealProfile', () => {fs.mkdirSync(path.join(destDir, 'Default'), { recursive: true });writeSqlite(path.join(destDir, 'Default', 'Cookies'), 'cookies', 'existing-snapshot');- await expect(- snapshotRealProfile({ source, destDir, platform: 'win32' }),- ).rejects.toMatchObject({- code: 'APP_BOUND_ENCRYPTION_UNSUPPORTED',- });+ await expect(snapshotRealProfile({ source, destDir, platform: 'win32' })).rejects.toMatchObject(+ {+ code: 'APP_BOUND_ENCRYPTION_UNSUPPORTED',+ },+ );expect(readSqlite(path.join(destDir, 'Default', 'Cookies'), 'cookies')).toBe('existing-snapshot',@@ -432,6 +525,22 @@ describe('snapshotRealProfile', () => {});describe('probeSourceProfileReadAccess', () => {+ it('does not require optional password read permission before launching', () => {+ const source = seedSource(makeTempDir());+ const realOpen = fs.openSync.bind(fs);+ vi.spyOn(fs, 'openSync').mockImplementation(((file, flags, mode) => {+ if (String(file).endsWith(`${path.sep}Login Data`)) {+ throw Object.assign(new Error('private source path'), { code: 'EACCES' });+ }+ return realOpen(file, flags, mode);+ }) as typeof fs.openSync);+ try {+ expect(probeSourceProfileReadAccess(source)).toEqual({ readable: true });+ } finally {+ vi.restoreAllMocks();+ }+ });+it('reports readable for a fake last_used profile', () => {const root = makeTempDir();expect(probeSourceProfileReadAccess(seedSource(root))).toEqual({ readable: true });diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/launch.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/launch.tsindex 8910bbf7a1..a1059fbf3d 100644--- a/apps/desktop/src/main/mcp-integrations/browser-real-profile/launch.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/launch.ts@@ -16,6 +16,8 @@ import type {import {FOREIGN_AGENT_BROWSER_ERROR,isBrowserOpenForLoginErrorCode,+ browserProfileCopyWarningsFromData,+ type BrowserProfileCopyWarning,} from '../../../shared/browserBackend.js';import { resolveSourceBrowserFromOs } from './source.js';@@ -143,6 +145,11 @@ export function annotateStatusData(enabled: hint.enabled,applied: hint.applied,source: hint.source,+ ...(hint.warnings?.length+ ? {+ warnings: browserProfileCopyWarningsFromData({ realProfile: hint }),+ }+ : {}),};return next;}@@ -152,6 +159,7 @@ export function wrapRuntimeWithRealProfile(deps: RealProfileLaunchDeps,): Pick<BrowserControlRuntime, 'call'> {let lastApplied: ChromiumKind | null = null;+ let lastWarnings: BrowserProfileCopyWarning[] = [];const resolveSource = deps.resolveSource ?? resolveSourceBrowserFromOs;const snapshot = deps.snapshot ?? snapshotRealProfile;@@ -162,6 +170,7 @@ export function wrapRuntimeWithRealProfile(enabled: deps.isEnabled(),applied: deps.isEnabled() && lastApplied !== null,source: deps.isEnabled() ? lastApplied : null,+ ...(deps.isEnabled() && lastApplied && lastWarnings.length ? { warnings: lastWarnings } : {}),});return {@@ -170,21 +179,46 @@ export function wrapRuntimeWithRealProfile(// /start. Consent-on sessions must snapshot before those implicit// launches, or the next explicit start short-circuits on our live pid.if (shouldPrepareCopiedLogins(request.action, deps.isEnabled())) {- return startWithSnapshot(inner, request, {+ let prepared = false;+ const result = await startWithSnapshot(inner, request, {...deps,resolveSource,snapshot,cleanup,platform,getLastApplied: () => lastApplied,- setLastApplied: (kind) => {+ setLastApplied: (kind, warnings = []) => {lastApplied = kind;+ lastWarnings = warnings;+ prepared = kind !== null;},});+ if (result.ok && hint().warnings?.length && (prepared || request.action === 'start')) {+ const reasons = {+ locked: 'database is locked by another process',+ 'permission-denied': 'read permission denied',+ 'copy-failed': 'database could not be copied',+ };+ return {+ ...result,+ data: annotateStatusData(result.data, hint()),+ message: [+ result.message,+ `Browser login cookies were copied, but some saved passwords or autofill data were skipped: ${lastWarnings.map((warning) => `${warning.database} (${reasons[warning.reason]})`).join('; ')}. Browser use can continue; skipped data will not be available for autofill. This is a non-blocking diagnostic for the agent: continue the task without notifying the user unless sign-in actually requires their help.`,+ ]+ .filter(Boolean)+ .join('\n'),+ };+ }+ return result;}const result = await inner.call(withActiveBrowserProfile(request, deps.isEnabled()));if (request.action === 'status' && result.ok) {+ // Do not treat vendored running:false as process-gone. Readiness can+ // drop while Chrome is still alive after stop signals; proving gone is+ // ExternalChromeBackend.resolveLiveness. Diagnostics stay until the+ // next launch prep that does not see own-live occupancy.return {...result,data: annotateStatusData(result.data, hint()),@@ -230,7 +264,7 @@ async function startWithSnapshot(cleanup: typeof cleanupRealProfileSnapshots;platform: NodeJS.Platform;getLastApplied: () => ChromiumKind | null;- setLastApplied: (kind: ChromiumKind | null) => void;+ setLastApplied: (kind: ChromiumKind | null, warnings?: BrowserProfileCopyWarning[]) => void;},): Promise<BrowserControlResult> {const enabled = deps.isEnabled();@@ -247,6 +281,10 @@ async function startWithSnapshot(return inner.call(withActiveBrowserProfile(request, enabled));}+ // No live browser is using the previous snapshot. Do not expose stale+ // diagnostics while preparing a new launch, including early failure paths.+ deps.setLastApplied(null);+if (!enabled) {return revertToIsolated();}@@ -270,6 +308,7 @@ async function startWithSnapshot(}let cdpPort = MANAGED_CDP_PORT;+ let preparedSnapshot: SnapshotResult;try {const pick = deps.pickCdpPort ?? ((preferred: number) => pickManagedCdpPort(preferred));cdpPort = await pick(MANAGED_CDP_PORT);@@ -305,7 +344,7 @@ async function startWithSnapshot(executablePath: source.executablePath,cdpPort,});- deps.setLastApplied(result.sourceKind);+ preparedSnapshot = result;rememberCopiedLoginsCdpPort(runtimeDir, cdpPort);} catch (err) {deps.setLastApplied(null);@@ -322,7 +361,40 @@ async function startWithSnapshot(if (!deps.isEnabled()) {return revertToIsolated();}- return inner.call(withActiveBrowserProfile(request, true));++ // Snapshot state tracks this Cindy's live managed browser, not the original+ // action result. Implicit open/tabs/snapshot can spawn Chrome and then fail;+ // ExternalChromeBackend keeps that process. Publishing only on `launched.ok`+ // would leave applied=false for the rest of the browser lifetime, so later+ // calls reuse the live pid without restoring diagnostics.+ const publishIfOwnLive = async () => {+ if (!deps.isEnabled() || !runtimeDir) return;+ const after = await inner.call({ action: 'status', profile: managedProfile });+ if (isOwnLiveManagedBrowser(after.data, runtimeDir)) {+ deps.setLastApplied(preparedSnapshot.sourceKind, preparedSnapshot.warnings);+ }+ };++ try {+ const launched = await inner.call(withActiveBrowserProfile(request, true));+ if (launched.ok && deps.isEnabled()) {+ deps.setLastApplied(preparedSnapshot.sourceKind, preparedSnapshot.warnings);+ } else if (!launched.ok) {+ try {+ await publishIfOwnLive();+ } catch {+ // Keep the original action failure.+ }+ }+ return launched;+ } catch (err) {+ try {+ await publishIfOwnLive();+ } catch {+ // Keep the original launch error.+ }+ throw err;+ }}function failure(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 c2f0ef8152..d03fd02e90 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@@ -7,7 +7,11 @@ import {MANAGED_PROFILE,REAL_MANAGED_PROFILE,} from '../browser-managed-config.js';-import { REAL_PROFILE_READ_DENIED } from '../../../shared/browserBackend.js';+import {+ OPTIONAL_BROWSER_PROFILE_DATABASES,+ REAL_PROFILE_READ_DENIED,+ type BrowserProfileCopyWarning,+} from '../../../shared/browserBackend.js';import { resolveSourceBrowserFromOs } from './source.js';import {isRealProfileError,@@ -22,9 +26,7 @@ const COMPLETE_MARKER = '.cindy-real-profile-complete';const AUTH_DB_RELATIVE_PATHS = ['Cookies',path.join('Network', 'Cookies'),- 'Login Data',- 'Login Data For Account',- 'Web Data',+ ...OPTIONAL_BROWSER_PROFILE_DATABASES,] as const;const PLAIN_PROFILE_FILES = ['Preferences'] as const;@@ -211,6 +213,25 @@ function isPermissionDenied(err: unknown): boolean {return code === 'EPERM' || code === 'EACCES';}+function isDatabaseLocked(err: unknown): boolean {+ const error = err as { code?: string; errcode?: number } | null;+ // node:sqlite reports ERR_SQLITE_ERROR plus SQLite's numeric (possibly extended) code.+ const primary = typeof error?.errcode === 'number' ? error.errcode & 0xff : undefined;+ return (+ primary === 5 ||+ primary === 6 ||+ error?.code === 'SQLITE_BUSY' ||+ error?.code === 'SQLITE_LOCKED' ||+ error?.code === 'EBUSY'+ );+}++function copyWarningReason(err: unknown): BrowserProfileCopyWarning['reason'] {+ if (isDatabaseLocked(err)) return 'locked';+ if (isPermissionDenied(err)) return 'permission-denied';+ return 'copy-failed';+}+function tryOpenRead(filePath: string): 'ok' | 'missing' | 'denied' {try {const fd = fs.openSync(filePath, 'r');@@ -262,7 +283,8 @@ export function probeSourceProfileReadAccess(source: InstalledChromium): { readaconst profileDir = tryOpenDir(sourceProfileDir);if (profileDir === 'denied') return { readable: false };- for (const relative of AUTH_DB_RELATIVE_PATHS) {+ // Optional password/autofill access must not prevent cookie reuse.+ for (const relative of COOKIE_DB_CANDIDATES) {const result = tryOpenRead(path.join(sourceProfileDir, relative));if (result === 'denied') return { readable: false };}@@ -351,14 +373,22 @@ function publishStagedSnapshot(options: {fs.rmSync(stagingDir, { recursive: true, force: true });}-async function copySqliteDatabase(src: string, dest: string): Promise<void> {+async function copySqliteDatabase(src: string, dest: string, optional: boolean): Promise<void> {fs.mkdirSync(path.dirname(dest), { recursive: true });removeSqliteAndSidecars(dest);if (typeof backup !== 'function') {throw new Error('sqlite backup API unavailable');}- const source = new DatabaseSync(src, { readOnly: true, timeout: 5000 });+ // Keep OS permission errors distinguishable from SQLite's generic CANTOPEN.+ const fd = fs.openSync(src, 'r');+ fs.closeSync(fd);+ const source = new DatabaseSync(src, { readOnly: true, timeout: optional ? 0 : 5000 });try {+ // Acquire a read snapshot before async backup: an exclusive Chrome password+ // lock should fail promptly, not leave backup retrying SQLITE_BUSY indefinitely.+ // Holding this read transaction also prevents a lock race before backup starts.+ source.exec('BEGIN');+ source.prepare('PRAGMA schema_version').get();// Node 24 / Electron 41: backup is module-level `backup(sourceDb, dest)`.// DatabaseSync#backup does not exist; copyFile + WAL sidecars is not a// consistent snapshot while the source Chrome is open.@@ -368,15 +398,6 @@ async function copySqliteDatabase(src: string, dest: string): Promise<void> {}}-async function copyAuthFile(src: string, dest: string, isSqlite: boolean): Promise<void> {- fs.mkdirSync(path.dirname(dest), { recursive: true });- if (isSqlite) {- await copySqliteDatabase(src, dest);- return;- }- await fs.promises.copyFile(src, dest);-}-export async function snapshotRealProfile(options: {source: InstalledChromium;destDir: string;@@ -432,7 +453,7 @@ export async function snapshotRealProfile(options: {} catch (err) {if (isRealProfileError(err)) throw err;const code = (err as NodeJS.ErrnoException).code;- if (code === 'EPERM' || code === 'EBUSY' || code === 'EACCES') {+ if (isDatabaseLocked(err) || code === 'EPERM' || code === 'EACCES') {throw new RealProfileError('PROFILE_LOCKED','Chrome is locking its cookie database. Quit Chrome completely and try again.',@@ -456,6 +477,7 @@ export async function snapshotRealProfile(options: {secureDir(path.join(stagingProfileDir, 'Network'));const filesCopied: string[] = [];+ const warnings: BrowserProfileCopyWarning[] = [];const copiedRelative = new Set<string>();let authDbCopied = 0;@@ -470,15 +492,24 @@ export async function snapshotRealProfile(options: {const src = path.join(sourceProfileDir, relative);if (!fs.existsSync(src)) continue;const dest = path.join(stagingProfileDir, relative);+ const optionalDatabase = OPTIONAL_BROWSER_PROFILE_DATABASES.find((name) => name === relative);try {- await copyAuthFile(src, dest, true);+ await copySqliteDatabase(src, dest, optionalDatabase !== undefined);filesCopied.push(path.join('Default', relative));copiedRelative.add(relative);authDbCopied += 1;} catch (err) {+ if (optionalDatabase) {+ removeSqliteAndSidecars(dest);+ warnings.push({ database: optionalDatabase, reason: copyWarningReason(err) });+ continue;+ }const code = (err as NodeJS.ErrnoException).code;if (isPermissionDenied(err) && platform !== 'win32') throwReadDenied();- if (platform === 'win32' && (code === 'EPERM' || code === 'EBUSY' || code === 'EACCES')) {+ if (+ isDatabaseLocked(err) ||+ (platform === 'win32' && (code === 'EPERM' || code === 'EACCES'))+ ) {throw new RealProfileError('PROFILE_LOCKED','Chrome is locking its cookie database. Quit Chrome completely and try again.',@@ -522,6 +553,7 @@ export async function snapshotRealProfile(options: {sourceKind: options.source.kind,sourceProfile,filesCopied,+ ...(warnings.length ? { warnings } : {}),};} catch (err) {if (stagingDir) fs.rmSync(stagingDir, { recursive: true, force: true });diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/types.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/types.tsindex f12abe5f56..ccc0774705 100644--- a/apps/desktop/src/main/mcp-integrations/browser-real-profile/types.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/types.ts@@ -4,6 +4,8 @@* that copy. This is consent-gated convenience, not an isolation boundary.*/+import type { BrowserProfileCopyWarning } from '../../../shared/browserBackend.js';+export type ChromiumKind = 'chrome' | 'edge' | 'brave' | 'chromium';export const CHROMIUM_KINDS = ['chrome', 'edge', 'brave', 'chromium'] as const;@@ -43,12 +45,14 @@ export interface SnapshotResult {sourceKind: ChromiumKind;sourceProfile: string;filesCopied: string[];+ warnings?: BrowserProfileCopyWarning[];}export interface RealProfileStatusHint {enabled: boolean;applied: boolean;source: ChromiumKind | null;+ warnings?: BrowserProfileCopyWarning[];}export type DefaultBrowserKind = ChromiumKind | 'other' | null;diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ComputerUseSection.browserHealth.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ComputerUseSection.browserHealth.test.tsxindex 4449b9ad96..ae785e6f7c 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/ComputerUseSection.browserHealth.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/ComputerUseSection.browserHealth.test.tsx@@ -16,12 +16,20 @@ const api = vi.hoisted(() => ({getBackendHealth: vi.fn(),setBackendKind: vi.fn(),recoverBackend: vi.fn(),+ openForLogin: vi.fn(),+ warningToast: vi.fn(),+ successToast: vi.fn(),+ errorToast: vi.fn(),}));vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));+vi.mock('@/lib/toast', () => ({+ toast: { warning: api.warningToast, success: api.successToast, error: api.errorToast },+}));+import { ComputerUseSection } from '../ComputerUseSection';function deferred<T>() {@@ -90,7 +98,7 @@ beforeEach(() => {},browser: {status: api.getBrowserStatus,- openForLogin: vi.fn(),+ openForLogin: api.openForLogin,},computer: {status: api.getComputerStatus,@@ -120,6 +128,39 @@ beforeEach(() => {afterEach(cleanup);describe('ComputerUseSection browser backend health loading', () => {+ it('keeps optional copy diagnostics out of user-facing launch notifications', async () => {+ api.getBackendState.mockResolvedValue({ active: 'external' });+ api.getBackendHealth.mockResolvedValue({+ active: 'external',+ status: 'ready',+ canRecover: false,+ });+ api.getBrowserStatus.mockResolvedValue({+ detected: true,+ browserKind: 'chrome',+ executablePath: '/chrome',+ });+ api.openForLogin.mockResolvedValue({+ launched: true,+ warnings: [+ { database: 'Login Data', reason: 'locked' },+ { database: 'Login Data For Account', reason: 'locked' },+ { database: 'Web Data', reason: 'permission-denied' },+ ],+ });+ render(<ComputerUseSection workingDir="/tmp/project" />);+ fireEvent.click(+ await screen.findByRole('button', { name: 'settings.computerUse.browser.openForLogin' }),+ );+ await waitFor(() =>+ expect(api.successToast).toHaveBeenCalledWith(+ 'settings.computerUse.browser.toast.openedForLogin',+ ),+ );+ expect(api.warningToast).not.toHaveBeenCalled();+ expect(api.errorToast).not.toHaveBeenCalled();+ });+it('renders the Automation settings while the recoverable health probe is still pending', async () => {const initialHealth = deferred<BrowserBackendHealth>();api.getBackendHealth.mockReturnValueOnce(initialHealth.promise);diff --git a/apps/desktop/src/shared/__tests__/browserProfileCopyWarnings.test.ts b/apps/desktop/src/shared/__tests__/browserProfileCopyWarnings.test.tsnew file mode 100644index 0000000000..e7657353a8--- /dev/null+++ b/apps/desktop/src/shared/__tests__/browserProfileCopyWarnings.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';+import { browserProfileCopyWarningsFromData } from '../browserBackend';++describe('browserProfileCopyWarningsFromData', () => {+ it('allows only controlled database names and reasons, stripping native details', () => {+ expect(+ browserProfileCopyWarningsFromData({+ realProfile: {+ warnings: [+ { database: 'Login Data', reason: 'locked', path: '/secret', message: 'credential' },+ { database: '/secret/Login Data', reason: 'locked' },+ { database: 'Web Data', reason: 'native error /secret' },+ null,+ ],+ },+ }),+ ).toEqual([{ database: 'Login Data', reason: 'locked' }]);+ });++ it.each([null, undefined, {}, { realProfile: {} }, { realProfile: { warnings: 'bad' } }])(+ 'keeps older or malformed status payloads compatible: %j',+ (data) => {+ expect(browserProfileCopyWarningsFromData(data)).toEqual([]);+ },+ );+});diff --git a/apps/desktop/src/shared/browserBackend.ts b/apps/desktop/src/shared/browserBackend.tsindex 1068d6168b..c8d3d5aa72 100644--- a/apps/desktop/src/shared/browserBackend.ts+++ b/apps/desktop/src/shared/browserBackend.ts@@ -1,5 +1,31 @@export type BrowserBackendKind = 'external' | 'rsb-webview';+/** Optional profile stores; warning payloads never carry paths or native errors. */+export const OPTIONAL_BROWSER_PROFILE_DATABASES = [+ 'Login Data',+ 'Login Data For Account',+ 'Web Data',+] as const;++export interface BrowserProfileCopyWarning {+ database: (typeof OPTIONAL_BROWSER_PROFILE_DATABASES)[number];+ reason: 'locked' | 'permission-denied' | 'copy-failed';+}++/** Only known, non-sensitive fields may cross the runtime / IPC boundary. */+export function browserProfileCopyWarningsFromData(data: unknown): BrowserProfileCopyWarning[] {+ const raw = (data as { realProfile?: { warnings?: unknown } } | null)?.realProfile?.warnings;+ if (!Array.isArray(raw)) return [];+ return raw.flatMap((entry) => {+ if (!entry || typeof entry !== 'object') return [];+ const { database, reason } = entry;+ if (!(OPTIONAL_BROWSER_PROFILE_DATABASES as readonly unknown[]).includes(database)) return [];+ if (reason !== 'locked' && reason !== 'permission-denied' && reason !== 'copy-failed')+ return [];+ return [{ database, reason } as BrowserProfileCopyWarning];+ });+}+/** Thrown when start/open would attach to another Cindy instance's Chrome on CDP 18800. */export const FOREIGN_AGENT_BROWSER_ERROR = 'FOREIGN_AGENT_BROWSER';@@ -18,8 +44,7 @@ export const BROWSER_OPEN_FOR_LOGIN_ERROR_CODES = ['APP_BOUND_ENCRYPTION_UNSUPPORTED',] as const;-export type BrowserOpenForLoginErrorCode =- (typeof BROWSER_OPEN_FOR_LOGIN_ERROR_CODES)[number];+export type BrowserOpenForLoginErrorCode = (typeof BROWSER_OPEN_FOR_LOGIN_ERROR_CODES)[number];export function isBrowserOpenForLoginErrorCode(value: unknown,@@ -51,11 +76,7 @@ export function browserOpenForLoginErrorCodeFromData(}export type BrowserBackendHealthReason =- | 'disposing'- | 'host-unavailable'- | 'start-failed'- | 'status-failed'- | 'recovery-failed';+ 'disposing' | 'host-unavailable' | 'start-failed' | 'status-failed' | 'recovery-failed';export interface BrowserBackendHealth {active: BrowserBackendKind;diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.mdindex 8aad57be64..9f67cbc107 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` 隔离身份不动。失败必须 fail-closed,禁止启动一个看起来在浏览、其实全是登出的窗口。快照当凭证:不要写进日志正文、backup、device-link 或 worktree;`status` 只暴露 `{ enabled, applied, source }`,不暴露路径。快照实现在 `apps/desktop/src/main/mcp-integrations/browser-real-profile/`;chip 名例外见 `sync.mjs` 对 `chrome.ts` 的 LOCAL_PATCH。+用户可在设置 → 自动操作打开「使用我的浏览器登录态」(默认关)。打开后,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。## 2. 三层架构 + 文件清单