Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 使用系统浏览器登录态,并拆分链接打开方式 (#3596)
Dashf1dd63ec52bc
diff --git a/apps/desktop/src/main/__tests__/browser-backend-settings-store.test.ts b/apps/desktop/src/main/__tests__/browser-backend-settings-store.test.tsnew file mode 100644index 0000000000..0900610f03--- /dev/null+++ b/apps/desktop/src/main/__tests__/browser-backend-settings-store.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';++import { __testing } from '../browser-backend-settings-store.js';++describe('browser-backend-settings-store normalize', () => {+ it('defaults useRealProfile to false', () => {+ expect(__testing.normalize(undefined)).toEqual({+ kind: 'external',+ useRealProfile: false,+ });+ expect(__testing.normalize({ kind: 'rsb-webview' })).toEqual({+ kind: 'rsb-webview',+ useRealProfile: false,+ });+ });++ it('only accepts an explicit true for useRealProfile', () => {+ expect(__testing.normalize({ useRealProfile: true })).toEqual({+ kind: 'external',+ useRealProfile: true,+ });+ expect(__testing.normalize({ useRealProfile: 'true' })).toEqual({+ kind: 'external',+ useRealProfile: false,+ });+ });+});diff --git a/apps/desktop/src/main/__tests__/browserRuntimeDirStartup.test.ts b/apps/desktop/src/main/__tests__/browserRuntimeDirStartup.test.tsnew file mode 100644index 0000000000..fd0dfead42--- /dev/null+++ b/apps/desktop/src/main/__tests__/browserRuntimeDirStartup.test.ts@@ -0,0 +1,30 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++/**+ * Chrome --user-data-dir joins CONFIG_DIR at launch. Vite's main bundle+ * require()s @cindy/browser-control-runtime before index.ts body, so the pin+ * must sit after the last userData setPath, refresh the live CONFIG_DIR+ * binding, and happen before dispatch.+ */+describe('browser runtime dir startup pin', () => {+ const indexSource = readFileSync(resolve(process.cwd(), 'src/main/index.ts'), 'utf8').replace(+ /\r\n/g,+ '\n',+ );++ it('pins XDT_BROWSER_RUNTIME_DIR after the last userData path and before bootstrap', () => {+ const lastSetPathIdx = indexSource.lastIndexOf("app.setPath('userData'");+ const pinIdx = indexSource.indexOf("process.env.XDT_BROWSER_RUNTIME_DIR = path.join(app.getPath('userData'), 'browser-runtime')");+ const refreshIdx = indexSource.indexOf('refreshBrowserRuntimeConfigDir()');+ const bootstrapIdx = indexSource.indexOf("import('./bootstrap-electron.js')");+ expect(lastSetPathIdx).toBeGreaterThan(-1);+ expect(pinIdx).toBeGreaterThan(lastSetPathIdx);+ expect(refreshIdx).toBeGreaterThan(pinIdx);+ expect(bootstrapIdx).toBeGreaterThan(refreshIdx);+ expect(indexSource).toContain("if (!process.env.XDT_BROWSER_RUNTIME_DIR)");+ expect(indexSource).toContain("from '@cindy/browser-control-runtime/config-dir'");+ expect(indexSource).not.toMatch(/from ['"]@cindy\/browser-control-runtime['"]/);+ });+});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 8dbf9d3081..2b26b88568 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -5929,6 +5929,7 @@ const registerIpcHandlers = () => {const allowedSystemSettingsUrls = new Set(['x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility','x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture',+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles',]);// Open external URL in system default browser, plus a small allowlist ofdiff --git a/apps/desktop/src/main/browser-backend-settings-store.ts b/apps/desktop/src/main/browser-backend-settings-store.tsindex e2b5828ccd..da7347fa0b 100644--- a/apps/desktop/src/main/browser-backend-settings-store.ts+++ b/apps/desktop/src/main/browser-backend-settings-store.ts@@ -79,10 +79,17 @@ const log = desktopMakerLogger.child('browser-backend-settings-store');export interface BrowserBackendSettings {kind: BackendKind;+ /**+ * Consent to copy the user's Chromium-family logins into a Cindy-managed+ * snapshot profile (`Cindy-real`). Default off. Turning this back off deletes+ * the snapshot; the isolated `Cindy` profile is left alone.+ */+ useRealProfile: boolean;}const DEFAULTS: BrowserBackendSettings = {kind: 'external',+ useRealProfile: false,};const VALID_KINDS: readonly BackendKind[] = ['external', 'rsb-webview'];@@ -98,7 +105,8 @@ function normalize(raw: unknown): BrowserBackendSettings {typeof r.kind === 'string' && (VALID_KINDS as string[]).includes(r.kind)? (r.kind as BackendKind): DEFAULTS.kind;- return { kind };+ const useRealProfile = r.useRealProfile === true;+ return { kind, useRealProfile };}const store = createOverrideSettingsFile<BrowserBackendSettings>({@@ -122,6 +130,11 @@ export function writeBrowserBackendKind(kind: BackendKind): void {log.info('browser-backend kind written', { kind });}+export function writeBrowserUseRealProfile(useRealProfile: boolean): void {+ store.writePatch({ useRealProfile });+ log.info('browser-backend useRealProfile written', { useRealProfile });+}+/** Reset = clear user override, fall back to current system default. */export function resetBrowserBackendSettings(): BrowserBackendSettings {return store.reset();diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 348b9a6bc7..c4a0c0b312 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -6,6 +6,7 @@ import path from 'node:path';import { setDefaultAutoSelectFamilyAttemptTimeout } from 'node:net';import { exit, stderr } from 'node:process';import { BRAND_IDENTITY } from '@cindy/maker-shared/brand-identity';+import { refreshBrowserRuntimeConfigDir } from '@cindy/browser-control-runtime/config-dir';import { CURRENT_CINDY_REGION } from '../shared/brandRegion.js';import { resolveRegionUserDataDirName } from './regionUserData.js';import { createLogger, initLogger } from './logger.js';@@ -255,6 +256,15 @@ const desktopDevInstanceOptions = (() => {};})();+// Pin after the last userData setPath. Vite's main bundle require()s+// @cindy/browser-control-runtime at chunk load (before this body), so+// CONFIG_DIR is already the ~/.xdt-maker fallback. Setting env is not+// enough — refresh the live binding Chrome launch actually joins.+if (!process.env.XDT_BROWSER_RUNTIME_DIR) {+ process.env.XDT_BROWSER_RUNTIME_DIR = path.join(app.getPath('userData'), 'browser-runtime');+}+refreshBrowserRuntimeConfigDir();+async function dispatch(): Promise<void> {const cleanupDevInstance = await beginDesktopDevInstance(desktopDevInstanceOptions);// Windows updater forceQuit() ends in process.exit(0), which bypasses Electron will-quit.diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.tsindex d5aa999d6e..383b5cb849 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts@@ -9,4 +9,15 @@ describe('managed browser runtime config', () => {allowIpv6UniqueLocalRange: true,});});++ it('labels both isolated and snapshot profiles Cindy on the Chrome chip', () => {+ const isolated = buildManagedConfig().browser;+ expect(isolated?.defaultProfile).toBe('Cindy');+ expect(isolated?.profiles?.Cindy?.displayName).toBe('Cindy');++ const snapshot = buildManagedConfig({ useRealProfile: true }).browser;+ expect(snapshot?.defaultProfile).toBe('Cindy-real');+ expect(snapshot?.profiles?.['Cindy-real']?.displayName).toBe('Cindy');+ expect(Object.keys(snapshot?.profiles ?? {})).toEqual(['Cindy-real']);+ });});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/raise-agent-browser-window.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/raise-agent-browser-window.test.tsnew file mode 100644index 0000000000..2376bbf439--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/raise-agent-browser-window.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it, vi } from 'vitest';++import { raiseAgentBrowserWindow } from '../raise-agent-browser-window.js';+import type { BrowserControlRequest, BrowserControlResult } from '@cindy/browser-control-runtime';++function tabsResult(+ tabs: Array<{ targetId?: string; suggestedTargetId?: string }> | undefined,+): BrowserControlResult {+ return { ok: true, action: 'tabs', data: tabs === undefined ? {} : { tabs } };+}++describe('raiseAgentBrowserWindow', () => {+ it('focuses the first tab and never opens another', async () => {+ const call = vi.fn(async (request: BrowserControlRequest): Promise<BrowserControlResult> => {+ if (request.action === 'tabs') {+ return tabsResult([{ targetId: 't1' }]);+ }+ return { ok: true, action: request.action };+ });+ const sleep = vi.fn(async () => {});++ await raiseAgentBrowserWindow({ call }, { sleep });++ expect(call.mock.calls.map(([request]) => request)).toEqual([+ { action: 'tabs' },+ { action: 'focus', targetId: 't1' },+ ]);+ expect(sleep).not.toHaveBeenCalled();+ });++ it('prefers suggestedTargetId and waits until CDP reports a tab', async () => {+ const call = vi.fn(async (request: BrowserControlRequest): Promise<BrowserControlResult> => {+ if (request.action === 'tabs') {+ const tabPolls = call.mock.calls.filter(([req]) => req.action === 'tabs').length;+ if (tabPolls < 3) return tabsResult([]);+ return tabsResult([{ targetId: 'ignored', suggestedTargetId: 'preferred' }]);+ }+ return { ok: true, action: request.action };+ });+ const sleep = vi.fn(async () => {});++ await raiseAgentBrowserWindow({ call }, { sleep });++ expect(call.mock.calls.map(([request]) => request)).toEqual([+ { action: 'tabs' },+ { action: 'tabs' },+ { action: 'tabs' },+ { action: 'focus', targetId: 'preferred' },+ ]);+ expect(sleep).toHaveBeenCalledTimes(2);+ });++ it('does not open about:blank when the tab list stays empty', async () => {+ const call = vi.fn(async (request: BrowserControlRequest): Promise<BrowserControlResult> => {+ if (request.action === 'tabs') return tabsResult([]);+ return { ok: true, action: request.action };+ });+ const sleep = vi.fn(async () => {});++ await raiseAgentBrowserWindow({ call }, { sleep });++ expect(call.mock.calls.every(([request]) => request.action === 'tabs')).toBe(true);+ expect(call).toHaveBeenCalledTimes(10);+ expect(sleep).toHaveBeenCalledTimes(9);+ expect(call.mock.calls.some(([request]) => request.action === 'open')).toBe(false);+ expect(call.mock.calls.some(([request]) => request.action === 'focus')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/settings-ipc.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/settings-ipc.test.tsindex ec425cd76b..3c4fb8ccbd 100644--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/settings-ipc.test.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/settings-ipc.test.ts@@ -12,8 +12,10 @@ function buildHandlers() {active: 'rsb-webview' as const,systemDefault: 'external' as const,isOverride: true,+ useRealProfile: false,})),setKind: vi.fn(async (kind: 'external' | 'rsb-webview') => kind),+ setUseRealProfile: vi.fn(async (enabled: boolean) => enabled),reset: vi.fn(async () => 'external' as const),getHealth: vi.fn(async () => ({active: 'rsb-webview' as const,@@ -28,6 +30,7 @@ function buildHandlers() {canRecover: true,},})),+ probeSourceRead: vi.fn(() => ({ readable: true })),};return {trustedEvent,@@ -45,15 +48,21 @@ describe('browser backend Settings IPC handlers', () => {await expect(handlers.setKind(untrusted, { kind: 'external' })).rejects.toThrow(/untrusted renderer/,);+ await expect(handlers.setUseRealProfile(untrusted, { enabled: true })).rejects.toThrow(+ /untrusted renderer/,+ );await expect(handlers.reset(untrusted)).rejects.toThrow(/untrusted renderer/);expect(() => handlers.getHealth(untrusted)).toThrow(/untrusted renderer/);expect(() => handlers.recover(untrusted)).toThrow(/untrusted renderer/);+ expect(() => handlers.probeSourceRead(untrusted)).toThrow(/untrusted renderer/);expect(deps.getState).not.toHaveBeenCalled();expect(deps.setKind).not.toHaveBeenCalled();+ expect(deps.setUseRealProfile).not.toHaveBeenCalled();expect(deps.reset).not.toHaveBeenCalled();expect(deps.getHealth).not.toHaveBeenCalled();expect(deps.recover).not.toHaveBeenCalled();+ expect(deps.probeSourceRead).not.toHaveBeenCalled();});it('validates set-kind and returns stable response contracts', async () => {@@ -63,6 +72,7 @@ describe('browser backend Settings IPC handlers', () => {active: 'rsb-webview',systemDefault: 'external',isOverride: true,+ useRealProfile: false,});await expect(handlers.setKind(trustedEvent, { kind: 'external' })).resolves.toEqual({ok: true,@@ -75,6 +85,13 @@ describe('browser backend Settings IPC handlers', () => {await expect(handlers.getHealth(trustedEvent)).resolves.toMatchObject({ status: 'ready' });await expect(handlers.recover(trustedEvent)).resolves.toMatchObject({ ok: true });expect(deps.setKind).toHaveBeenCalledWith('external');+ await expect(handlers.setUseRealProfile(trustedEvent, { enabled: true })).resolves.toEqual({+ ok: true,+ enabled: true,+ });+ expect(deps.setUseRealProfile).toHaveBeenCalledWith(true);+ expect(handlers.probeSourceRead(trustedEvent)).toEqual({ readable: true });+ expect(deps.probeSourceRead).toHaveBeenCalledTimes(1);await expect(handlers.setKind(trustedEvent, { kind: 'unknown' })).rejects.toThrow();});diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/settings-ipc.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/settings-ipc.tsindex eb3adb271c..ec8eb06948 100644--- a/apps/desktop/src/main/mcp-integrations/browser-backend/settings-ipc.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/settings-ipc.ts@@ -1,23 +1,32 @@import type {BrowserBackendHealth,BrowserBackendRecoveryResult,+ BrowserBackendSourceReadAccess,} from '../../../shared/browserBackend.js';-import { requireEnum, requireObject } from '../../utils/ipcValidate.js';+import { requireBoolean, requireEnum, requireObject } from '../../utils/ipcValidate.js';import type { BackendKind } from './types.js';export interface BrowserBackendSettingsState {active: BackendKind;systemDefault: BackendKind;isOverride: boolean;+ useRealProfile: boolean;+}++export interface BrowserUseRealProfileResult {+ ok: true;+ enabled: boolean;}interface BrowserBackendIpcDeps<Event> {assertTrusted(event: Event): void;getState(): BrowserBackendSettingsState;setKind(kind: BackendKind): Promise<BackendKind>;+ setUseRealProfile(enabled: boolean): Promise<boolean>;reset(): Promise<BackendKind>;getHealth(): Promise<BrowserBackendHealth>;recover(): Promise<BrowserBackendRecoveryResult>;+ probeSourceRead(): BrowserBackendSourceReadAccess;}/** Pure handler factory so trust gates and response contracts stay testable. */@@ -33,6 +42,12 @@ export function createBrowserBackendIpcHandlers<Event>(deps: BrowserBackendIpcDeconst kind = requireEnum(obj.kind, ['external', 'rsb-webview'] as const, 'kind');return { ok: true as const, active: await deps.setKind(kind) };},+ async setUseRealProfile(event: Event, payload: unknown) {+ deps.assertTrusted(event);+ const obj = requireObject(payload, 'set-use-real-profile payload');+ const enabled = requireBoolean(obj.enabled, 'enabled');+ return { ok: true as const, enabled: await deps.setUseRealProfile(enabled) };+ },async reset(event: Event) {deps.assertTrusted(event);return { ok: true as const, active: await deps.reset() };@@ -45,5 +60,9 @@ export function createBrowserBackendIpcHandlers<Event>(deps: BrowserBackendIpcDedeps.assertTrusted(event);return deps.recover();},+ probeSourceRead(event: Event) {+ deps.assertTrusted(event);+ return deps.probeSourceRead();+ },};}diff --git a/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts b/apps/desktop/src/main/mcp-integrations/browser-managed-config.tsindex dc796e1f23..94e4ecf2a0 100644--- a/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts@@ -1,13 +1,12 @@import type { BrowserRuntimeConfig } from '@cindy/browser-control-runtime';/**- * Managed profile identity. The profile key doubles as (a) the Chrome profile- * display name rendered in the launched browser's top-right profile button and (b)- * the user-data-dir folder name — so it's branded "Cindy" to make the automation- * browser obviously distinct from the user's everyday Chrome at a glance. The runtime- * seeds the name + color into the profile's Local State / Preferences before launch- * (decoration re-checks the desired name every launch, so a profile dir carried over- * with an old display name self-heals to "Cindy" on first run).+ * Managed profile identity. The profile key is the on-disk folder+ * `browser/<key>/user-data`. Chrome's top-right chip follows `displayName` when+ * set, otherwise the key. Isolated and snapshot profiles both pass+ * `displayName: "Cindy"` so the chip never shows the disk identifier. The runtime+ * seeds name + color into Local State / Preferences before launch (decoration+ * re-checks every launch, so an old chip label self-heals on first run).* (Same Chrome binary as the user's, so the dock/taskbar icon is unchanged.)** ⚠️ 磁盘标识符:这是 2026-07 品牌翻转时钉死的目录名,之后【不要】再跟随@@ -20,6 +19,15 @@ import type { BrowserRuntimeConfig } from '@cindy/browser-control-runtime';*/export const MANAGED_PROFILE = 'Cindy';+/**+ * Snapshot profile for consented "use my browser logins". Disk name is pinned+ * like `Cindy` — do not rename, or leftover cookie copies become unreachable+ * and cleanup will miss them. Never overlay onto `MANAGED_PROFILE`. The Chrome+ * chip still shows `MANAGED_PROFILE` via `displayName`; this string is not+ * user-facing.+ */+export const REAL_MANAGED_PROFILE = 'Cindy-real';+/*** Fixed brand tint for the managed profile. This intentionally stays on the vivid* teal variant instead of the Default Light auto-approval text color. NOTE:@@ -45,7 +53,7 @@ const MANAGED_DRIVER = 'openclaw' as const;* profile MUST define its own `cdpPort` or the runtime rejects it with "must define* cdpPort or cdpUrl". 18800 is the vendored default CDP port-range start.*/-const MANAGED_CDP_PORT = 18800;+export const MANAGED_CDP_PORT = 18800;/*** Default ("managed") config: a single playwright-launched Chrome profile, headed,@@ -66,21 +74,32 @@ const MANAGED_CDP_PORT = 18800;* surface is accepted as inherent to browser automation (it's the same* capability the `act:evaluate` tool already exposes), not a regression.*/-export function buildManagedConfig(): BrowserRuntimeConfig {+export function buildManagedConfig(options?: {+ useRealProfile?: boolean;+ executablePath?: string;+ cdpPort?: number;+}): BrowserRuntimeConfig {+ const useRealProfile = options?.useRealProfile === true;+ const defaultProfile = useRealProfile ? REAL_MANAGED_PROFILE : MANAGED_PROFILE;+ const executablePath = options?.executablePath;+ const cdpPort = options?.cdpPort ?? MANAGED_CDP_PORT;return {browser: {enabled: true,- defaultProfile: MANAGED_PROFILE,+ defaultProfile,headless: false, // headed so the user can see + log into sites+ ...(executablePath ? { executablePath } : {}),ssrfPolicy: {allowRfc2544BenchmarkRange: true,allowIpv6UniqueLocalRange: true,},profiles: {- [MANAGED_PROFILE]: {+ [defaultProfile]: {driver: MANAGED_DRIVER,color: DEFAULT_PROFILE_COLOR,- cdpPort: MANAGED_CDP_PORT,+ cdpPort,+ displayName: MANAGED_PROFILE,+ ...(executablePath ? { executablePath } : {}),},},},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.tsnew file mode 100644index 0000000000..248c160f6d--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/launch.test.ts@@ -0,0 +1,618 @@+import { describe, expect, it, vi } from 'vitest';++import type { BrowserControlRequest, BrowserControlResult } from '@cindy/browser-control-runtime';++import {+ annotateStatusData,+ isOwnLiveManagedBrowser,+ shouldPrepareCopiedLogins,+ shouldStopRememberedLeftover,+ withActiveBrowserProfile,+ wrapRuntimeWithRealProfile,+} from '../launch.js';+import { RealProfileError, type InstalledChromium } from '../types.js';++function result(+ action: BrowserControlRequest['action'],+ data: unknown,+ ok = true,+): BrowserControlResult {+ return { ok, action, status: ok ? 200 : 500, data };+}++function fakeInner(state: { running: boolean; headless?: boolean; starts: number }) {+ return {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', { running: state.running, headless: state.headless === true });+ }+ if (request.action === 'start') {+ state.starts += 1;+ state.running = true;+ return result('start', { running: true });+ }+ return result(request.action, {});+ },+ };+}++const chrome: InstalledChromium = {+ kind: 'chrome',+ executablePath: '/chrome',+ userDataDir: '/src',+};++const pick18800 = async () => 18800;++describe('wrapRuntimeWithRealProfile', () => {+ 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();+ const snapshot = vi.fn(async () => ({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome' as const,+ sourceProfile: 'Default',+ filesCopied: ['Local State'],+ }));+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig,+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ platform: 'darwin',+ pickCdpPort: pick18800,+ });++ const started = await wrapped.call({ action: 'start' });+ expect(started.ok).toBe(true);+ expect(snapshot).toHaveBeenCalledOnce();+ expect(applyConfig).toHaveBeenCalledWith({+ useRealProfile: true,+ executablePath: '/chrome',+ cdpPort: 18800,+ });++ const status = await wrapped.call({ action: 'status' });+ expect(status.data).toMatchObject({+ realProfile: { enabled: true, applied: true, source: 'chrome' },+ });+ });++ it('does not overlay while this instance already launched the managed browser', async () => {+ const inner = {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', {+ running: true,+ pid: 1234,+ userDataDir: '/runtime/browser/Cindy/user-data',+ });+ }+ if (request.action === 'start') {+ return result('start', { running: true });+ }+ return result(request.action, {});+ },+ };+ const snapshot = vi.fn();+ const applyConfig = vi.fn();+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig,+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ });+ await wrapped.call({ action: 'start' });+ expect(snapshot).not.toHaveBeenCalled();+ expect(applyConfig).not.toHaveBeenCalled();+ });++ it('keeps the isolated Cindy profile on the fixed CDP port', async () => {+ let started = 0;+ const inner = {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', { running: true });+ }+ if (request.action === 'start') {+ started += 1;+ return result('start', { running: true });+ }+ return result(request.action, {});+ },+ };+ const applyConfig = vi.fn();+ const pickCdpPort = vi.fn(async () => 18801);+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => false,+ getRuntimeDir: () => '/Users/dash/Library/Application Support/Cindy-dev2/browser-runtime',+ applyConfig,+ pickCdpPort,+ });+ const resultStart = await wrapped.call({ action: 'start' });+ expect(resultStart.ok).toBe(true);+ expect(started).toBe(1);+ expect(pickCdpPort).not.toHaveBeenCalled();+ expect(applyConfig).toHaveBeenCalledWith({ useRealProfile: false, cdpPort: 18800 });+ });++ it('cleans the snapshot and does not start a signed-out session on copy failure', async () => {+ const innerState = { running: false, starts: 0 };+ const inner = fakeInner(innerState);+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot: async () => {+ throw new RealProfileError('NO_AUTH_DB', 'missing cookies');+ },+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ });+ const started = await wrapped.call({ action: 'start' });+ expect(started.ok).toBe(false);+ expect(started.message).toMatch(/missing cookies/);+ expect(innerState.starts).toBe(0);+ });++ it('rejects headless real-profile launches', async () => {+ const inner = fakeInner({ running: false, headless: true, starts: 0 });+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot: vi.fn(),+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ });+ const started = await wrapped.call({ action: 'start' });+ expect(started.ok).toBe(false);+ expect(started.message).toMatch(/headless/i);+ });++ it('deletes the snapshot store when consent is off', async () => {+ const inner = fakeInner({ running: false, starts: 0 });+ const cleanup = vi.fn();+ const applyConfig = vi.fn();+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => false,+ getRuntimeDir: () => '/runtime',+ applyConfig,+ cleanup,+ snapshot: vi.fn(),+ resolveSource: () => chrome,+ pickCdpPort: pick18800,+ });+ const started = await wrapped.call({ action: 'start' });+ expect(started.ok).toBe(true);+ expect(cleanup).toHaveBeenCalledWith('/runtime');+ expect(applyConfig).toHaveBeenCalledWith({ useRealProfile: false, cdpPort: 18800 });+ });++ it('does not relocate isolated Cindy when leftover Chrome sits on 18800', async () => {+ let started = 0;+ const inner = {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', {+ running: true,+ userDataDir: '/Users/dash/.xdt-maker/browser-runtime/browser/Cindy/user-data',+ });+ }+ if (request.action === 'start') {+ started += 1;+ return result('start', { running: true });+ }+ return result(request.action, {});+ },+ };+ const applyConfig = vi.fn();+ const pickCdpPort = vi.fn(async () => 18801);+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => false,+ getRuntimeDir: () => '/Users/dash/Library/Application Support/Cindy-dev2/browser-runtime',+ applyConfig,+ pickCdpPort,+ });+ const resultStart = await wrapped.call({ action: 'start' });+ expect(resultStart.ok).toBe(true);+ expect(started).toBe(1);+ expect(pickCdpPort).not.toHaveBeenCalled();+ expect(applyConfig).toHaveBeenCalledWith({ useRealProfile: false, cdpPort: 18800 });+ });++ it('snapshots into this runtime when leftover Chrome sits under ~/.xdt-maker', async () => {+ let started = 0;+ let stops = 0;+ const inner = {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', {+ running: true,+ userDataDir: '/Users/dash/.xdt-maker/browser-runtime/browser/Cindy-real/user-data',+ });+ }+ if (request.action === 'stop') {+ stops += 1;+ return result('stop', { stopped: true });+ }+ if (request.action === 'start') {+ started += 1;+ return result('start', { running: true });+ }+ return result(request.action, {});+ },+ };+ const snapshot = vi.fn(async () => ({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome' as const,+ sourceProfile: 'Default',+ filesCopied: ['Local State'],+ }));+ const applyConfig = vi.fn();+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig,+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ platform: 'darwin',+ pickCdpPort: async () => 18801,+ readRememberedCdpPort: () => null,+ });+ const startedResult = await wrapped.call({ action: 'start' });+ expect(startedResult.ok).toBe(true);+ expect(startedResult.errorCode).toBeUndefined();+ expect(started).toBe(1);+ expect(stops).toBe(0);+ expect(snapshot).toHaveBeenCalledOnce();+ expect(applyConfig).toHaveBeenCalledWith({+ useRealProfile: true,+ executablePath: '/chrome',+ cdpPort: 18801,+ });+ });++ it('starts Cindy-real by name after config swap so a stale default Cindy does not miss it', async () => {+ let startedProfile: string | undefined;+ const inner = {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', { running: false });+ }+ if (request.action === 'start') {+ startedProfile = request.profile;+ if (request.profile !== 'Cindy-real') {+ return {+ ok: false,+ action: 'start',+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',+ message: 'Profile "Cindy" not found. Available profiles: Cindy-real',+ };+ }+ return result('start', { running: true });+ }+ return result(request.action, {});+ },+ };+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot: vi.fn(async () => ({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome' as const,+ sourceProfile: 'Default',+ filesCopied: ['Local State'],+ })),+ cleanup: vi.fn(),+ platform: 'darwin',+ pickCdpPort: pick18800,+ });+ const started = await wrapped.call({ action: 'start' });+ expect(started.ok).toBe(true);+ expect(startedProfile).toBe('Cindy-real');+ });++ it('snapshots before open so implicit ensureBrowserAvailable does not skip the copy', async () => {+ let opened = 0;+ const inner = {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', { running: false });+ }+ if (request.action === 'open') {+ opened += 1;+ return result('open', { running: true });+ }+ return result(request.action, {});+ },+ };+ const snapshot = vi.fn(async () => ({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome' as const,+ sourceProfile: 'Default',+ filesCopied: ['Local State'],+ }));+ const applyConfig = vi.fn();+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig,+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ platform: 'darwin',+ pickCdpPort: pick18800,+ });+ const openedResult = await wrapped.call({ action: 'open', url: 'https://example.com' });+ expect(openedResult.ok).toBe(true);+ expect(opened).toBe(1);+ expect(snapshot).toHaveBeenCalledOnce();+ expect(applyConfig).toHaveBeenCalledWith({+ useRealProfile: true,+ executablePath: '/chrome',+ cdpPort: 18800,+ });+ });++ it('does not snapshot status or a consent-off open', async () => {+ const snapshot = vi.fn();+ const cleanup = vi.fn();+ const applyConfig = vi.fn();+ const inner = fakeInner({ running: false, starts: 0 });+ const wrappedOn = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig,+ resolveSource: () => chrome,+ snapshot,+ cleanup,+ pickCdpPort: pick18800,+ });+ await wrappedOn.call({ action: 'status' });+ expect(snapshot).not.toHaveBeenCalled();+ expect(applyConfig).not.toHaveBeenCalled();++ const wrappedOff = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => false,+ getRuntimeDir: () => '/runtime',+ applyConfig,+ snapshot,+ cleanup,+ pickCdpPort: pick18800,+ });+ await wrappedOff.call({ action: 'open', url: 'https://example.com' });+ expect(snapshot).not.toHaveBeenCalled();+ expect(cleanup).not.toHaveBeenCalled();+ expect(applyConfig).not.toHaveBeenCalled();+ });++ it('stops a remembered Cindy-real leftover before snapshotting after a crash', async () => {+ const innerState = { running: true, starts: 0, stops: 0 };+ const inner = {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', { running: innerState.running });+ }+ if (request.action === 'stop') {+ innerState.stops += 1;+ innerState.running = false;+ return result('stop', { stopped: true });+ }+ if (request.action === 'start') {+ innerState.starts += 1;+ return result('start', { running: true });+ }+ return result(request.action, {});+ },+ };+ const snapshot = vi.fn(async () => ({+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome' as const,+ sourceProfile: 'Default',+ filesCopied: ['Local State'],+ }));+ const applyConfig = vi.fn();+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig,+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ platform: 'darwin',+ pickCdpPort: pick18800,+ readRememberedCdpPort: () => 18801,+ });+ const started = await wrapped.call({ action: 'start' });+ expect(started.ok).toBe(true);+ expect(innerState.stops).toBe(1);+ expect(innerState.starts).toBe(1);+ expect(snapshot).toHaveBeenCalledOnce();+ expect(applyConfig).toHaveBeenCalledWith({+ useRealProfile: true,+ executablePath: '/chrome',+ cdpPort: 18800,+ });+ });++ it('does not snapshot when a remembered leftover cannot be stopped', async () => {+ const inner = {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', { running: true });+ }+ if (request.action === 'stop') {+ return result('stop', { stopped: false });+ }+ return result(request.action, {});+ },+ };+ const snapshot = vi.fn();+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => true,+ getRuntimeDir: () => '/runtime',+ applyConfig: vi.fn(),+ resolveSource: () => chrome,+ snapshot,+ cleanup: vi.fn(),+ pickCdpPort: pick18800,+ readRememberedCdpPort: () => 18801,+ });+ const started = await wrapped.call({ action: 'start' });+ expect(started.ok).toBe(false);+ expect(started.message).toMatch(/stop/i);+ expect(snapshot).not.toHaveBeenCalled();+ });++ it('discards an in-flight snapshot when consent is revoked before apply', async () => {+ let enabled = true;+ let startedProfile: string | undefined;+ const inner = {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ if (request.action === 'status') {+ return result('status', { running: false });+ }+ if (request.action === 'start') {+ startedProfile = request.profile;+ return result('start', { running: true });+ }+ return result(request.action, {});+ },+ };+ const snapshot = vi.fn(async () => {+ enabled = false;+ return {+ destDir: '/runtime/browser/Cindy-real/user-data',+ sourceKind: 'chrome' as const,+ sourceProfile: 'Default',+ filesCopied: ['Local State'],+ };+ });+ const cleanup = vi.fn();+ const applyConfig = vi.fn();+ const wrapped = wrapRuntimeWithRealProfile(inner, {+ isEnabled: () => enabled,+ getRuntimeDir: () => '/runtime',+ applyConfig,+ resolveSource: () => chrome,+ snapshot,+ cleanup,+ platform: 'darwin',+ pickCdpPort: pick18800,+ });+ const started = await wrapped.call({ action: 'start' });+ expect(started.ok).toBe(true);+ expect(snapshot).toHaveBeenCalledOnce();+ expect(cleanup).toHaveBeenCalledWith('/runtime');+ expect(applyConfig).toHaveBeenCalledWith({ useRealProfile: false, cdpPort: 18800 });+ expect(applyConfig).not.toHaveBeenCalledWith(expect.objectContaining({ useRealProfile: true }));+ expect(startedProfile).toBe('Cindy');+ });+});++describe('shouldStopRememberedLeftover', () => {+ it('stops only a consent-on leftover on a remembered Cindy-real port', () => {+ expect(+ shouldStopRememberedLeftover({+ enabled: true,+ running: true,+ ownLive: false,+ rememberedCdpPort: 18801,+ }),+ ).toBe(true);+ expect(+ shouldStopRememberedLeftover({+ enabled: true,+ running: true,+ ownLive: true,+ rememberedCdpPort: 18801,+ }),+ ).toBe(false);+ expect(+ shouldStopRememberedLeftover({+ enabled: true,+ running: true,+ ownLive: false,+ rememberedCdpPort: null,+ }),+ ).toBe(false);+ expect(+ shouldStopRememberedLeftover({+ enabled: false,+ running: true,+ ownLive: false,+ rememberedCdpPort: 18801,+ }),+ ).toBe(false);+ });+});++describe('shouldPrepareCopiedLogins', () => {+ it('gates every consent-on action except status and stop', () => {+ expect(shouldPrepareCopiedLogins('start', false)).toBe(true);+ expect(shouldPrepareCopiedLogins('open', false)).toBe(false);+ expect(shouldPrepareCopiedLogins('open', true)).toBe(true);+ expect(shouldPrepareCopiedLogins('tabs', true)).toBe(true);+ expect(shouldPrepareCopiedLogins('status', true)).toBe(false);+ expect(shouldPrepareCopiedLogins('stop', true)).toBe(false);+ });+});++describe('withActiveBrowserProfile', () => {+ it('pins Cindy-real when consent is on and leaves an explicit profile alone', () => {+ expect(withActiveBrowserProfile({ action: 'start' }, true).profile).toBe('Cindy-real');+ expect(withActiveBrowserProfile({ action: 'start' }, false).profile).toBe('Cindy');+ expect(withActiveBrowserProfile({ action: 'tabs', profile: 'Cindy' }, true).profile).toBe(+ 'Cindy',+ );+ });+});++describe('isOwnLiveManagedBrowser', () => {+ it('requires a live pid under this runtime, not just a running CDP port', () => {+ const runtimeDir = '/runtime';+ expect(isOwnLiveManagedBrowser({ running: true }, runtimeDir)).toBe(false);+ expect(+ isOwnLiveManagedBrowser(+ { running: true, userDataDir: '/runtime/browser/Cindy/user-data' },+ runtimeDir,+ ),+ ).toBe(false);+ expect(+ isOwnLiveManagedBrowser(+ { running: true, pid: 99, userDataDir: '/elsewhere/Cindy/user-data' },+ runtimeDir,+ ),+ ).toBe(false);+ expect(+ isOwnLiveManagedBrowser(+ { running: true, pid: 99, userDataDir: '/runtime/browser/Cindy/user-data' },+ runtimeDir,+ ),+ ).toBe(true);+ });+});++describe('annotateStatusData', () => {+ it('adds the boolean hint and never forwards a snapshot path', () => {+ expect(+ annotateStatusData(+ { running: true, realProfilePath: '/secret' },+ { enabled: true, applied: true, source: 'chrome' },+ ),+ ).toEqual({+ running: true,+ realProfile: { enabled: true, applied: true, source: 'chrome' },+ });+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/runtime-stop.test.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/runtime-stop.test.tsnew file mode 100644index 0000000000..12e1d7a925--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/runtime-stop.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from 'vitest';+import type { BrowserControlResult } from '@cindy/browser-control-runtime';++import { assertManagedBrowserStopped, managedConfigPatchBeforeStop } from '../runtime-stop.js';+import { RealProfileError } from '../types.js';++function result(action: 'status' | 'stop', ok: boolean, data?: unknown): BrowserControlResult {+ return { ok, action, data };+}++describe('managedConfigPatchBeforeStop', () => {+ it('never rebuilds config before stop, even when a relocated CDP port was remembered', () => {+ expect(managedConfigPatchBeforeStop({ rememberedCdpPort: 18801 })).toBeNull();+ expect(managedConfigPatchBeforeStop({ rememberedCdpPort: null })).toBeNull();+ });+});++describe('assertManagedBrowserStopped', () => {+ it('allows the switch when status says the browser is not running', () => {+ expect(() =>+ assertManagedBrowserStopped({+ status: result('status', true, { running: false }),+ stop: null,+ }),+ ).not.toThrow();+ });++ it('allows the switch after a successful stop', () => {+ expect(() =>+ assertManagedBrowserStopped({+ status: result('status', true, { running: true }),+ stop: result('stop', true, { stopped: true }),+ }),+ ).not.toThrow();+ });++ it('fails closed when status cannot be verified', () => {+ try {+ assertManagedBrowserStopped({+ status: result('status', false),+ stop: null,+ });+ expect.unreachable();+ } catch (err) {+ expect(err).toBeInstanceOf(RealProfileError);+ expect(err).toMatchObject({ code: 'STOP_FAILED' });+ }+ });++ it('fails closed when stop returns ok:false or is missing', () => {+ try {+ assertManagedBrowserStopped({+ status: result('status', true, { running: true }),+ stop: result('stop', false),+ });+ expect.unreachable();+ } catch (err) {+ expect(err).toBeInstanceOf(RealProfileError);+ expect(err).toMatchObject({ code: 'STOP_FAILED' });+ }++ expect(() =>+ assertManagedBrowserStopped({+ status: result('status', true, { running: true }),+ stop: null,+ }),+ ).toThrow(RealProfileError);+ });++ it('fails closed when stop is ok but did not actually stop the process', () => {+ try {+ assertManagedBrowserStopped({+ status: result('status', true, { running: true }),+ stop: result('stop', true, { stopped: false }),+ });+ expect.unreachable();+ } catch (err) {+ expect(err).toBeInstanceOf(RealProfileError);+ expect(err).toMatchObject({ code: 'STOP_FAILED' });+ }++ expect(() =>+ assertManagedBrowserStopped({+ status: result('status', true, { running: true }),+ stop: result('stop', true, {}),+ }),+ ).toThrow(RealProfileError);+ });+});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.tsnew file mode 100644index 0000000000..e64b4faae1--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/snapshot.test.ts@@ -0,0 +1,513 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DatabaseSync } from 'node:sqlite';++import {+ cleanupCopiedLoginsThen,+ cleanupRealProfileSnapshots,+ isolatedProfileDestDir,+ lastUsedProfileName,+ probeOsSourceProfileReadAccess,+ probeSourceProfileReadAccess,+ profileIsLocked,+ readCopiedLoginsCdpPort,+ realProfileDestDir,+ realProfileProfileDir,+ rememberCopiedLoginsCdpPort,+ rewriteLocalStateForManagedDefault,+ snapshotRealProfile,+} from '../snapshot.js';+import { REAL_MANAGED_PROFILE } from '../../browser-managed-config.js';+import { REAL_PROFILE_READ_DENIED } from '../../../../shared/browserBackend.js';+import { RealProfileError, type InstalledChromium } from '../types.js';++const tempDirs: string[] = [];++function makeTempDir(): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-real-profile-'));+ tempDirs.push(dir);+ return dir;+}++afterEach(() => {+ for (const dir of tempDirs.splice(0)) {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++function leftoverStagingNames(destDir: string): string[] {+ const parent = path.dirname(destDir);+ if (!fs.existsSync(parent)) return [];+ return fs+ .readdirSync(parent)+ .filter((name) => name.startsWith(`${path.basename(destDir)}.staging`));+}++function writeSqlite(filePath: string, table: string, value: string): void {+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ const db = new DatabaseSync(filePath);+ db.exec(`CREATE TABLE ${table} (name TEXT); INSERT INTO ${table} VALUES ('${value}');`);+ db.close();+}++function readSqlite(filePath: string, table: string): string {+ const db = new DatabaseSync(filePath, { readOnly: true });+ const row = db.prepare(`SELECT name FROM ${table}`).get() as { name: string };+ db.close();+ return row.name;+}++function seedSource(root: string, lastUsed = 'Profile 6'): InstalledChromium {+ const userDataDir = path.join(root, 'Chrome');+ const profileDir = path.join(userDataDir, lastUsed);+ fs.mkdirSync(path.join(profileDir, 'Network'), { recursive: true });+ fs.writeFileSync(+ path.join(userDataDir, 'Local State'),+ JSON.stringify({+ os_crypt: { keep: true },+ profile: {+ last_used: lastUsed,+ last_active_profiles: [lastUsed],+ profiles_order: ['Default', lastUsed],+ info_cache: {+ Default: { name: 'Person 1' },+ [lastUsed]: { name: 'Dash' },+ },+ },+ }),+ );+ writeSqlite(path.join(profileDir, 'Cookies'), 'cookies', 'session-cookie');+ writeSqlite(path.join(profileDir, 'Login Data'), 'logins', 'saved-password');+ fs.writeFileSync(path.join(profileDir, 'Preferences'), '{"session":{"restore_on_startup":1}}');+ fs.mkdirSync(path.join(userDataDir, 'Default'), { recursive: true });+ writeSqlite(path.join(userDataDir, 'Default', 'Cookies'), 'cookies', 'other-profile');+ return {+ kind: 'chrome',+ executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ userDataDir,+ };+}++describe('lastUsedProfileName', () => {+ it('reads profile.last_used and falls back to Default', () => {+ expect(lastUsedProfileName('{"profile":{"last_used":"Profile 6"}}')).toBe('Profile 6');+ expect(lastUsedProfileName('not-json')).toBe('Default');+ expect(lastUsedProfileName('{}')).toBe('Default');+ });+});++describe('rewriteLocalStateForManagedDefault', () => {+ it('points every selection field at Default and stamps the chip name Cindy', () => {+ const rewritten = JSON.parse(+ rewriteLocalStateForManagedDefault(+ JSON.stringify({+ os_crypt: { keep: true },+ profile: {+ last_used: 'Profile 2',+ last_active_profiles: ['Profile 2'],+ profiles_order: ['Default', 'Profile 1', 'Profile 2'],+ show_picker_on_startup: true,+ info_cache: {+ Default: { name: 'Person 1' },+ 'Profile 2': { name: 'Dash' },+ },+ },+ }),+ 'Profile 2',+ ),+ ) as {+ os_crypt: { keep: boolean };+ profile: {+ last_used: string;+ last_active_profiles: string[];+ profiles_order: string[];+ show_picker_on_startup: boolean;+ info_cache: Record<string, { name: string }>;+ };+ };+ expect(rewritten.os_crypt.keep).toBe(true);+ expect(rewritten.profile.last_used).toBe('Default');+ expect(rewritten.profile.last_active_profiles).toEqual(['Default']);+ expect(rewritten.profile.profiles_order).toEqual(['Default']);+ expect(rewritten.profile.show_picker_on_startup).toBe(false);+ expect(Object.keys(rewritten.profile.info_cache)).toEqual(['Default']);+ expect(rewritten.profile.info_cache.Default).toMatchObject({+ name: 'Cindy',+ shortcut_name: 'Cindy',+ user_name: 'Cindy',+ });+ });++ it('still yields Default when Local State is malformed', () => {+ const rewritten = JSON.parse(rewriteLocalStateForManagedDefault('not-json', 'Default')) as {+ profile: { last_used: string };+ };+ expect(rewritten.profile.last_used).toBe('Default');+ });+});++describe('realProfileDestDir', () => {+ it('is the Chrome user-data-dir under Cindy-real, not the profile wrapper', () => {+ expect(realProfileDestDir('/runtime')).toBe(+ path.join('/runtime', 'browser', REAL_MANAGED_PROFILE, 'user-data'),+ );+ expect(realProfileProfileDir('/runtime')).toBe(+ path.join('/runtime', 'browser', REAL_MANAGED_PROFILE),+ );+ });+});++describe('snapshotRealProfile', () => {+ it('copies only the last_used profile into dest Default', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ const result = await snapshotRealProfile({ source, destDir, platform: 'darwin' });++ expect(result.sourceProfile).toBe('Profile 6');+ expect(readSqlite(path.join(destDir, 'Default', 'Cookies'), 'cookies')).toBe('session-cookie');+ expect(readSqlite(path.join(destDir, 'Default', 'Login Data'), 'logins')).toBe(+ 'saved-password',+ );+ expect(fs.existsSync(path.join(destDir, 'Default', 'Preferences'))).toBe(true);+ expect(result.filesCopied).toContain('Local State');+ expect(result.filesCopied).toContain(path.join('Default', 'Cookies'));+ const destLocalState = JSON.parse(+ fs.readFileSync(path.join(destDir, 'Local State'), 'utf8'),+ ) as {+ os_crypt: { keep: boolean };+ profile: {+ last_used: string;+ last_active_profiles: string[];+ info_cache: Record<string, { name: string }>;+ };+ };+ expect(destLocalState.os_crypt.keep).toBe(true);+ expect(destLocalState.profile.last_used).toBe('Default');+ expect(destLocalState.profile.last_active_profiles).toEqual(['Default']);+ expect(destLocalState.profile.info_cache.Default.name).toBe('Cindy');+ expect(destLocalState.profile.info_cache['Profile 6']).toBeUndefined();+ });++ it('deletes leftover Profile N folders so Chrome cannot reopen an empty sibling', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ fs.mkdirSync(path.join(destDir, 'Profile 2'), { recursive: true });+ fs.writeFileSync(path.join(destDir, 'Profile 2', 'Cookies'), 'empty');+ await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ expect(fs.existsSync(path.join(destDir, 'Profile 2'))).toBe(false);+ expect(fs.existsSync(path.join(destDir, 'Default', 'Cookies'))).toBe(true);+ });++ it('drops leftover site credential stores but keeps HTTP/GPU caches', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ const destDefault = path.join(destDir, 'Default');+ fs.mkdirSync(path.join(destDefault, 'Local Storage'), { recursive: true });+ fs.writeFileSync(path.join(destDefault, 'Local Storage', 'leveldb'), 'old-ls');+ fs.mkdirSync(path.join(destDefault, 'IndexedDB'), { recursive: true });+ fs.writeFileSync(path.join(destDefault, 'IndexedDB', 'site'), 'old-idb');+ fs.mkdirSync(path.join(destDefault, 'Service Worker'), { recursive: true });+ fs.writeFileSync(path.join(destDefault, 'Service Worker', 'script'), 'old-sw');+ fs.mkdirSync(path.join(destDefault, 'GPUCache'), { recursive: true });+ 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, '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('refuses to write anywhere except Cindy-real/user-data', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ await expect(+ snapshotRealProfile({+ source,+ destDir: path.join(root, 'runtime', 'browser', 'Cindy'),+ platform: 'darwin',+ }),+ ).rejects.toBeInstanceOf(RealProfileError);+ await expect(+ snapshotRealProfile({+ source,+ destDir: path.join(root, 'runtime', 'browser', REAL_MANAGED_PROFILE),+ platform: 'darwin',+ }),+ ).rejects.toBeInstanceOf(RealProfileError);+ });++ it('maps macOS permission denial to a stable read-denied token', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ const realRead = fs.readFileSync.bind(fs);+ vi.spyOn(fs, 'readFileSync').mockImplementation((file, encoding) => {+ if (String(file).endsWith(`${path.sep}Local State`)) {+ const err = new Error('operation not permitted') as NodeJS.ErrnoException;+ err.code = 'EPERM';+ throw err;+ }+ return realRead(file, encoding as BufferEncoding);+ });+ try {+ await expect(+ snapshotRealProfile({ source, destDir, platform: 'darwin' }),+ ).rejects.toMatchObject({+ code: 'COPY_FAILED',+ message: REAL_PROFILE_READ_DENIED,+ });+ } finally {+ vi.restoreAllMocks();+ }+ });++ it('replaces dest auth files and deletes leftovers absent from this snapshot', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ expect(fs.existsSync(path.join(destDir, 'Default', 'Login Data'))).toBe(true);+ expect(fs.existsSync(path.join(destDir, 'Default', 'Cookies'))).toBe(true);++ const nextRoot = makeTempDir();+ const userDataDir = path.join(nextRoot, 'Chrome');+ const profileDir = path.join(userDataDir, 'Default');+ fs.mkdirSync(path.join(profileDir, 'Network'), { recursive: true });+ fs.writeFileSync(path.join(userDataDir, 'Local State'), '{"profile":{"last_used":"Default"}}');+ writeSqlite(path.join(profileDir, 'Network', 'Cookies'), 'cookies', 'network-cookie');++ await snapshotRealProfile({+ source: {+ kind: 'chrome',+ executablePath: '/chrome',+ userDataDir,+ },+ destDir,+ platform: 'darwin',+ });++ expect(readSqlite(path.join(destDir, 'Default', 'Network', 'Cookies'), 'cookies')).toBe(+ 'network-cookie',+ );+ expect(fs.existsSync(path.join(destDir, 'Default', 'Cookies'))).toBe(false);+ expect(fs.existsSync(path.join(destDir, 'Default', 'Login Data'))).toBe(false);+ });++ it('leaves dest unchanged when a later sqlite backup fails', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ 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');++ await expect(+ snapshotRealProfile({ source, destDir, platform: 'darwin' }),+ ).rejects.toMatchObject({+ code: 'COPY_FAILED',+ });+ expect(readSqlite(path.join(destDir, 'Default', 'Cookies'), 'cookies')).toBe('stale-cookie');+ expect(readSqlite(path.join(destDir, 'Default', 'Login Data'), 'logins')).toBe('stale-login');+ expect(fs.existsSync(`${destDir}.staging`)).toBe(false);+ expect(leftoverStagingNames(destDir)).toEqual([]);+ });++ it('uses sqlite backup so dest has no WAL sidecar from the source', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const cookies = path.join(source.userDataDir, 'Profile 6', 'Cookies');+ fs.writeFileSync(`${cookies}-wal`, 'wal-bytes');+ fs.writeFileSync(`${cookies}-shm`, 'shm-bytes');+ const destDir = realProfileDestDir(path.join(root, 'runtime'));+ await snapshotRealProfile({ source, destDir, platform: 'darwin' });+ expect(fs.existsSync(path.join(destDir, 'Default', 'Cookies-wal'))).toBe(false);+ expect(readSqlite(path.join(destDir, 'Default', 'Cookies'), 'cookies')).toBe('session-cookie');+ });++ it('fails closed when cookie databases are missing', async () => {+ const root = makeTempDir();+ const userDataDir = path.join(root, 'Chrome');+ fs.mkdirSync(path.join(userDataDir, 'Default'), { recursive: true });+ fs.writeFileSync(path.join(userDataDir, 'Local State'), '{"profile":{"last_used":"Default"}}');+ await expect(+ snapshotRealProfile({+ source: {+ kind: 'chrome',+ executablePath: '/chrome',+ userDataDir,+ },+ destDir: realProfileDestDir(path.join(root, 'runtime')),+ platform: 'darwin',+ }),+ ).rejects.toMatchObject({ code: 'NO_AUTH_DB' });+ });++ it('treats a Windows exclusive lock as PROFILE_LOCKED', () => {+ const root = makeTempDir();+ const profileDir = path.join(root, 'Default');+ fs.mkdirSync(profileDir, { recursive: true });+ const cookies = path.join(profileDir, 'Cookies');+ fs.writeFileSync(cookies, 'x');+ fs.chmodSync(cookies, 0);+ // chmod 0 is not a Windows share lock; the helper only flags win32 EPERM/EBUSY.+ expect(profileIsLocked({ profileDir, platform: 'darwin' })).toBe(false);+ expect(profileIsLocked({ profileDir, platform: 'linux' })).toBe(false);+ });+});++describe('probeSourceProfileReadAccess', () => {+ it('reports readable for a fake last_used profile', () => {+ const root = makeTempDir();+ expect(probeSourceProfileReadAccess(seedSource(root))).toEqual({ readable: true });+ });++ it('reports not readable when Local State is EPERM', () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const realOpen = fs.openSync.bind(fs);+ vi.spyOn(fs, 'openSync').mockImplementation(((file, flags, mode) => {+ if (String(file).endsWith(`${path.sep}Local State`)) {+ const err = new Error('operation not permitted') as NodeJS.ErrnoException;+ err.code = 'EPERM';+ throw err;+ }+ return realOpen(file, flags, mode);+ }) as typeof fs.openSync);+ try {+ expect(probeSourceProfileReadAccess(source)).toEqual({ readable: false });+ } finally {+ vi.restoreAllMocks();+ }+ });++ it('reports not readable when Cookies is EPERM', () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const realOpen = fs.openSync.bind(fs);+ vi.spyOn(fs, 'openSync').mockImplementation(((file, flags, mode) => {+ if (String(file).endsWith(`${path.sep}Cookies`)) {+ const err = new Error('operation not permitted') as NodeJS.ErrnoException;+ err.code = 'EPERM';+ throw err;+ }+ return realOpen(file, flags, mode);+ }) as typeof fs.openSync);+ try {+ expect(probeSourceProfileReadAccess(source)).toEqual({ readable: false });+ } finally {+ vi.restoreAllMocks();+ }+ });++ it('skips the disk-permission prompt when cookie databases are missing', () => {+ const root = makeTempDir();+ const userDataDir = path.join(root, 'Chrome');+ fs.mkdirSync(path.join(userDataDir, 'Default'), { recursive: true });+ fs.writeFileSync(path.join(userDataDir, 'Local State'), '{"profile":{"last_used":"Default"}}');+ expect(+ probeSourceProfileReadAccess({+ kind: 'chrome',+ executablePath: '/chrome',+ userDataDir,+ }),+ ).toEqual({ readable: true });+ });++ it('skips the disk-permission prompt when no Chromium is installed', () => {+ expect(+ probeOsSourceProfileReadAccess({+ resolveSource: () => {+ throw new RealProfileError('NO_CHROMIUM', 'none');+ },+ }),+ ).toEqual({ readable: true });+ });+});++describe('copied logins CDP port marker', () => {+ it('round-trips a relocated port on the complete marker', async () => {+ const root = makeTempDir();+ const source = seedSource(root);+ const runtimeDir = path.join(root, 'runtime');+ await snapshotRealProfile({+ source,+ destDir: realProfileDestDir(runtimeDir),+ platform: 'darwin',+ });+ expect(readCopiedLoginsCdpPort(runtimeDir)).toBeNull();+ rememberCopiedLoginsCdpPort(runtimeDir, 18801);+ expect(readCopiedLoginsCdpPort(runtimeDir)).toBe(18801);+ });++ it('ignores missing markers and ports outside the managed range', () => {+ expect(readCopiedLoginsCdpPort('')).toBeNull();+ const runtimeDir = path.join(makeTempDir(), 'runtime');+ rememberCopiedLoginsCdpPort(runtimeDir, 18801);+ expect(readCopiedLoginsCdpPort(runtimeDir)).toBeNull();+ rememberCopiedLoginsCdpPort(runtimeDir, 80);+ expect(readCopiedLoginsCdpPort(runtimeDir)).toBeNull();+ });+});++describe('cleanupCopiedLoginsThen', () => {+ it('runs persist only after Cindy-real is gone', () => {+ const runtimeDir = makeTempDir();+ const profileDir = realProfileProfileDir(runtimeDir);+ fs.mkdirSync(path.join(profileDir, 'user-data'), { recursive: true });+ fs.writeFileSync(path.join(profileDir, 'user-data', 'Cookies'), 'copied');+ const order: string[] = [];+ cleanupCopiedLoginsThen(runtimeDir, () => {+ order.push('persist');+ expect(fs.existsSync(profileDir)).toBe(false);+ });+ expect(order).toEqual(['persist']);+ });++ it('does not persist when deleting the copy fails', () => {+ const runtimeDir = makeTempDir();+ const profileDir = realProfileProfileDir(runtimeDir);+ fs.mkdirSync(profileDir, { recursive: true });+ const persist = vi.fn();+ const realRm = fs.rmSync.bind(fs);+ vi.spyOn(fs, 'rmSync').mockImplementation(((target, opts) => {+ if (path.resolve(String(target)) === path.resolve(profileDir)) {+ throw Object.assign(new Error('busy'), { code: 'EBUSY' });+ }+ return realRm(target, opts);+ }) as typeof fs.rmSync);+ try {+ expect(() => cleanupCopiedLoginsThen(runtimeDir, persist)).toThrow(/busy/);+ expect(persist).not.toHaveBeenCalled();+ } finally {+ vi.restoreAllMocks();+ }+ });+});++describe('cleanupRealProfileSnapshots', () => {+ it('deletes Cindy-real and leaves the isolated Cindy profile alone', () => {+ const runtimeDir = makeTempDir();+ const realDir = realProfileDestDir(runtimeDir);+ const profileDir = realProfileProfileDir(runtimeDir);+ const cindyDir = isolatedProfileDestDir(runtimeDir);+ fs.mkdirSync(path.join(realDir, 'Default'), { recursive: true });+ fs.writeFileSync(path.join(realDir, 'Default', 'Cookies'), 'copied');+ fs.mkdirSync(cindyDir, { recursive: true });+ fs.writeFileSync(path.join(cindyDir, 'keep.txt'), 'isolated');++ cleanupRealProfileSnapshots(runtimeDir);++ expect(fs.existsSync(realDir)).toBe(false);+ expect(fs.existsSync(profileDir)).toBe(false);+ expect(fs.readFileSync(path.join(cindyDir, 'keep.txt'), 'utf8')).toBe('isolated');+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/source.test.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/source.test.tsnew file mode 100644index 0000000000..1cc02aaeb9--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/__tests__/source.test.ts@@ -0,0 +1,198 @@+import path from 'node:path';+import { describe, expect, it } from 'vitest';++import {+ listInstalledChromium,+ parseDefaultHandler,+ resolveSourceBrowser,+ userDataDirFor,+} from '../source.js';+import { RealProfileError, type InstalledChromium } from '../types.js';++const chrome: InstalledChromium = {+ kind: 'chrome',+ executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ userDataDir: '/Users/x/Library/Application Support/Google/Chrome',+};+const edge: InstalledChromium = {+ kind: 'edge',+ executablePath: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',+ userDataDir: '/Users/x/Library/Application Support/Microsoft Edge',+};++describe('parseDefaultHandler', () => {+ it('reads the last https handler from a LaunchServices dump', () => {+ const raw = `+ {+ LSHandlerRoleAll = "com.apple.Safari";+ LSHandlerURLScheme = https;+ }+ {+ LSHandlerRoleAll = "com.google.Chrome";+ LSHandlerURLScheme = https;+ }+ `;+ expect(parseDefaultHandler('darwin', raw)).toBe('chrome');+ });++ it('treats Safari and Firefox as other so Chrome can still be selected', () => {+ expect(parseDefaultHandler('darwin', 'com.apple.Safari')).toBe('other');+ expect(parseDefaultHandler('linux', 'firefox.desktop')).toBe('other');+ expect(+ parseDefaultHandler('win32', ' ProgId REG_SZ FirefoxURL-308046B0AF4A39CB'),+ ).toBe('other');+ });++ it('maps Edge / Brave / Chrome progids and desktop files', () => {+ expect(parseDefaultHandler('win32', 'ProgId REG_SZ ChromeHTML')).toBe('chrome');+ expect(parseDefaultHandler('win32', 'ProgId REG_SZ MSEdgeHTM')).toBe('edge');+ expect(parseDefaultHandler('linux', 'brave-browser.desktop')).toBe('brave');+ });++ it('treats beta/canary channels as other', () => {+ expect(parseDefaultHandler('darwin', 'com.google.Chrome.canary')).toBe('other');+ expect(parseDefaultHandler('linux', 'google-chrome-beta.desktop')).toBe('other');+ });+});++describe('resolveSourceBrowser', () => {+ it('uses the default Chromium-family browser when it is installed', () => {+ expect(resolveSourceBrowser({ defaultKind: 'edge', installed: [chrome, edge] })).toEqual(edge);+ });++ it('falls back to Chrome when the OS default is Safari', () => {+ expect(resolveSourceBrowser({ defaultKind: 'other', installed: [edge, chrome] })).toEqual(+ chrome,+ );+ });++ it('falls back to Chrome when default detection fails', () => {+ expect(resolveSourceBrowser({ defaultKind: null, installed: [edge, chrome] })).toEqual(chrome);+ });++ it('uses Edge when Chrome is not installed', () => {+ expect(resolveSourceBrowser({ defaultKind: 'other', installed: [edge] })).toEqual(edge);+ });++ it('fails closed when no Chromium-family browser is installed', () => {+ expect(() => resolveSourceBrowser({ defaultKind: 'other', installed: [] })).toThrow(+ RealProfileError,+ );+ });+});++describe('listInstalledChromium', () => {+ it('finds Chrome under the user Applications folder on darwin', () => {+ const home = '/Users/x';+ const exe = `${home}/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`;+ expect(+ listInstalledChromium({+ platform: 'darwin',+ home,+ exists: (filePath) => filePath === exe,+ }),+ ).toEqual([+ {+ kind: 'chrome',+ executablePath: exe,+ userDataDir: `${home}/Library/Application Support/Google/Chrome`,+ },+ ]);+ });++ it('finds Snap Brave / Chromium / Chrome and maps their profile dirs', () => {+ const home = '/home/x';+ const brave = '/snap/bin/brave';+ const chromium = '/snap/bin/chromium';+ const chromeSnap = '/snap/bin/google-chrome';+ expect(+ listInstalledChromium({+ platform: 'linux',+ home,+ exists: (filePath) =>+ filePath === brave || filePath === chromium || filePath === chromeSnap,+ }),+ ).toEqual([+ {+ kind: 'chrome',+ executablePath: chromeSnap,+ userDataDir: `${home}/snap/google-chrome/current/.config/google-chrome`,+ },+ {+ kind: 'brave',+ executablePath: brave,+ userDataDir: `${home}/snap/brave/current/.config/BraveSoftware/Brave-Browser`,+ },+ {+ kind: 'chromium',+ executablePath: chromium,+ userDataDir: `${home}/snap/chromium/common/chromium`,+ },+ ]);+ });++ it('prefers distro Chrome over Snap and keeps ~/.config user-data', () => {+ const home = '/home/x';+ const distro = '/usr/bin/google-chrome-stable';+ const snap = '/snap/bin/google-chrome';+ expect(+ listInstalledChromium({+ platform: 'linux',+ home,+ exists: (filePath) => filePath === distro || filePath === snap,+ }),+ ).toEqual([+ {+ kind: 'chrome',+ executablePath: distro,+ userDataDir: `${home}/.config/google-chrome`,+ },+ ]);+ });++ it('finds Edge under LOCALAPPDATA on win32', () => {+ const home = 'C:\\Users\\x';+ const local = 'C:\\Users\\x\\AppData\\Local';+ const exe = path.join(local, 'Microsoft', 'Edge', 'Application', 'msedge.exe');+ expect(+ listInstalledChromium({+ platform: 'win32',+ home,+ env: {+ LOCALAPPDATA: local,+ PROGRAMFILES: 'C:\\Program Files',+ 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)',+ },+ exists: (filePath) => filePath === exe,+ }),+ ).toEqual([+ {+ kind: 'edge',+ executablePath: exe,+ userDataDir: path.win32.join(local, 'Microsoft', 'Edge', 'User Data'),+ },+ ]);+ });+});++describe('userDataDirFor', () => {+ it('resolves Chromium user-data directories with the target OS separators', () => {+ expect(userDataDirFor('chrome', 'darwin', '/Users/dash')).toBe(+ '/Users/dash/Library/Application Support/Google/Chrome',+ );+ expect(userDataDirFor('chrome', 'linux', '/home/dash')).toBe(+ '/home/dash/.config/google-chrome',+ );+ expect(+ userDataDirFor('chrome', 'win32', 'C:\\Users\\dash', {+ LOCALAPPDATA: 'C:\\Users\\dash\\AppData\\Local',+ }),+ ).toBe('C:\\Users\\dash\\AppData\\Local\\Google\\Chrome\\User Data');+ expect(userDataDirFor('brave', 'linux', '/home/dash', {}, '/snap/bin/brave')).toBe(+ '/home/dash/snap/brave/current/.config/BraveSoftware/Brave-Browser',+ );+ expect(userDataDirFor('brave', 'linux', '/home/dash', {}, '/usr/bin/brave')).toBe(+ '/home/dash/.config/BraveSoftware/Brave-Browser',+ );+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/index.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/index.tsnew file mode 100644index 0000000000..7f177a1426--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/index.ts@@ -0,0 +1,46 @@+export { REAL_MANAGED_PROFILE } from '../browser-managed-config.js';+export {+ RealProfileError,+ isRealProfileError,+ type ChromiumKind,+ type InstalledChromium,+ type RealProfileErrorCode,+ type RealProfileStatusHint,+ type SnapshotResult,+} from './types.js';+export {+ detectDefaultHandlerFromOs,+ listInstalledChromium,+ parseDefaultHandler,+ resolveSourceBrowser,+ resolveSourceBrowserFromOs,+ userDataDirFor,+} from './source.js';+export { assertManagedBrowserStopped, managedConfigPatchBeforeStop } from './runtime-stop.js';+export {+ cleanupCopiedLoginsThen,+ cleanupRealProfileSnapshots,+ isolatedProfileDestDir,+ lastUsedProfileName,+ probeOsSourceProfileReadAccess,+ probeSourceProfileReadAccess,+ profileIsLocked,+ pruneExtraChromeProfiles,+ pruneNonAuthProfileState,+ readCopiedLoginsCdpPort,+ realProfileDestDir,+ realProfileProfileDir,+ rememberCopiedLoginsCdpPort,+ rewriteLocalStateForManagedDefault,+ snapshotRealProfile,+} from './snapshot.js';+export {+ activeManagedProfileName,+ annotateStatusData,+ FOREIGN_AGENT_BROWSER_ERROR,+ isOurManagedBrowser,+ isOwnLiveManagedBrowser,+ wrapRuntimeWithRealProfile,+ withActiveBrowserProfile,+ type RealProfileLaunchDeps,+} from './launch.js';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.tsnew file mode 100644index 0000000000..39b44942bf--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/launch.ts@@ -0,0 +1,349 @@+import net from 'node:net';+import path from 'node:path';++import {+ MANAGED_CDP_PORT,+ MANAGED_PROFILE,+ REAL_MANAGED_PROFILE,+} from '../browser-managed-config.js';++import type {+ BrowserControlRequest,+ BrowserControlResult,+ BrowserControlRuntime,+} from '@cindy/browser-control-runtime';++import { FOREIGN_AGENT_BROWSER_ERROR } from '../../../shared/browserBackend.js';++import { resolveSourceBrowserFromOs } from './source.js';+import { assertManagedBrowserStopped } from './runtime-stop.js';+import {+ cleanupRealProfileSnapshots,+ readCopiedLoginsCdpPort,+ realProfileDestDir,+ rememberCopiedLoginsCdpPort,+ snapshotRealProfile,+} from './snapshot.js';+import {+ isRealProfileError,+ RealProfileError,+ type ChromiumKind,+ type InstalledChromium,+ type RealProfileStatusHint,+ type SnapshotResult,+} from './types.js';++export interface RealProfileLaunchDeps {+ isEnabled: () => boolean;+ getRuntimeDir: () => string;+ applyConfig: (opts: {+ useRealProfile: boolean;+ executablePath?: string;+ cdpPort?: number;+ }) => void;+ resolveSource?: () => InstalledChromium;+ snapshot?: typeof snapshotRealProfile;+ cleanup?: typeof cleanupRealProfileSnapshots;+ platform?: NodeJS.Platform;+ /** Return a free CDP port at or after `preferred`. Injected in tests. */+ pickCdpPort?: (preferred: number) => Promise<number>;+ /** Cindy-real CDP port from the existing complete marker. Injected in tests. */+ readRememberedCdpPort?: (runtimeDir: string) => number | null;+}++function asRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === 'object' ? (value as Record<string, unknown>) : {};+}++function isRunning(data: unknown): boolean {+ return asRecord(data).running === true;+}++function isHeadless(data: unknown): boolean {+ return asRecord(data).headless === true;+}++/** True when status.userDataDir lives under this Cindy's browser-runtime tree. */+export function isOurManagedBrowser(data: unknown, runtimeDir: string): boolean {+ if (!runtimeDir) return false;+ const userDataDir = asRecord(data).userDataDir;+ if (typeof userDataDir !== 'string' || userDataDir.length === 0) return false;+ const root = path.resolve(runtimeDir);+ const dir = path.resolve(userDataDir);+ return dir === root || dir.startsWith(root + path.sep);+}++/**+ * True only when this Cindy process itself launched the Chrome that status sees.+ * `running` alone is not enough: the vendored status probes the configured CDP+ * port, so another instance's Chrome on 18800 looks "running". Until we spawn,+ * `userDataDir`/`pid` are also missing (config does not set userDataDir), so+ * occupancy must require a live pid plus our user-data-dir.+ */+export function isOwnLiveManagedBrowser(data: unknown, runtimeDir: string): boolean {+ const pid = asRecord(data).pid;+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return false;+ return isOurManagedBrowser(data, runtimeDir);+}++export function activeManagedProfileName(useRealProfile: boolean): string {+ return useRealProfile ? REAL_MANAGED_PROFILE : MANAGED_PROFILE;+}++/**+ * The vendored control service captures `defaultProfile` before hot-reloading+ * config. After we swap Cindy → Cindy-real, a start without `profile` looks up+ * the stale name and throws BrowserProfileNotFoundError. Pin the active name+ * on every call except when the caller already chose one.+ */+export function withActiveBrowserProfile(+ request: BrowserControlRequest,+ useRealProfile: boolean,+): BrowserControlRequest {+ if (request.profile) return request;+ return { ...request, profile: activeManagedProfileName(useRealProfile) };+}++export { FOREIGN_AGENT_BROWSER_ERROR };++export function isPortFree(port: number, host = '127.0.0.1'): Promise<boolean> {+ return new Promise((resolve) => {+ const server = net.createServer();+ server.once('error', () => resolve(false));+ server.once('listening', () => {+ server.close(() => resolve(true));+ });+ server.listen(port, host);+ });+}++export async function pickManagedCdpPort(+ preferred = MANAGED_CDP_PORT,+ isFree: (port: number) => Promise<boolean> = isPortFree,+): Promise<number> {+ for (let port = preferred; port < preferred + 20; port += 1) {+ if (await isFree(port)) return port;+ }+ throw new RealProfileError(+ 'COPY_FAILED',+ `No free agent-browser CDP port in ${preferred}-${preferred + 19}.`,+ );+}++export function annotateStatusData(+ data: unknown,+ hint: RealProfileStatusHint,+): Record<string, unknown> {+ const next = { ...asRecord(data) };+ delete next.realProfilePath;+ next.realProfile = {+ enabled: hint.enabled,+ applied: hint.applied,+ source: hint.source,+ };+ return next;+}++export function wrapRuntimeWithRealProfile(+ inner: Pick<BrowserControlRuntime, 'call'>,+ deps: RealProfileLaunchDeps,+): Pick<BrowserControlRuntime, 'call'> {+ let lastApplied: ChromiumKind | null = null;++ const resolveSource = deps.resolveSource ?? resolveSourceBrowserFromOs;+ const snapshot = deps.snapshot ?? snapshotRealProfile;+ const cleanup = deps.cleanup ?? cleanupRealProfileSnapshots;+ const platform = deps.platform ?? process.platform;++ const hint = (): RealProfileStatusHint => ({+ enabled: deps.isEnabled(),+ applied: deps.isEnabled() && lastApplied !== null,+ source: deps.isEnabled() ? lastApplied : null,+ });++ return {+ async call(request: BrowserControlRequest): Promise<BrowserControlResult> {+ // Vendored open/tabs/snapshot/… call ensureBrowserAvailable() without+ // /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, {+ ...deps,+ resolveSource,+ snapshot,+ cleanup,+ platform,+ getLastApplied: () => lastApplied,+ setLastApplied: (kind) => {+ lastApplied = kind;+ },+ });+ }++ const result = await inner.call(withActiveBrowserProfile(request, deps.isEnabled()));+ if (request.action === 'status' && result.ok) {+ return {+ ...result,+ data: annotateStatusData(result.data, hint()),+ };+ }+ return result;+ },+ };+}++export function shouldPrepareCopiedLogins(+ action: BrowserControlRequest['action'],+ enabled: boolean,+): boolean {+ if (action === 'status' || action === 'stop') return false;+ return action === 'start' || enabled;+}++/**+ * Crash restart can see `running: true` on the remembered Cindy-real port+ * without pid/userDataDir (vendored status only fills those from in-process+ * state). Occupancy of 18800 without a marker is some other instance — relocate+ * rather than stop. A marker means this runtime already launched Cindy-real on+ * that port, so stop the leftover before copying onto the same user-data.+ */+export function shouldStopRememberedLeftover(input: {+ enabled: boolean;+ running: boolean;+ ownLive: boolean;+ rememberedCdpPort: number | null;+}): boolean {+ return (+ input.enabled && input.running && !input.ownLive && typeof input.rememberedCdpPort === 'number'+ );+}++async function startWithSnapshot(+ inner: Pick<BrowserControlRuntime, 'call'>,+ request: BrowserControlRequest,+ deps: RealProfileLaunchDeps & {+ resolveSource: () => InstalledChromium;+ snapshot: typeof snapshotRealProfile;+ cleanup: typeof cleanupRealProfileSnapshots;+ platform: NodeJS.Platform;+ getLastApplied: () => ChromiumKind | null;+ setLastApplied: (kind: ChromiumKind | null) => void;+ },+): Promise<BrowserControlResult> {+ const enabled = deps.isEnabled();+ const status = await inner.call({ action: 'status' });+ const runtimeDir = deps.getRuntimeDir();+ const revertToIsolated = () => {+ if (runtimeDir) deps.cleanup(runtimeDir);+ deps.applyConfig({ useRealProfile: false, cdpPort: MANAGED_CDP_PORT });+ deps.setLastApplied(null);+ return inner.call(withActiveBrowserProfile(request, false));+ };+ if (isRunning(status.data) && isOwnLiveManagedBrowser(status.data, runtimeDir)) {+ return inner.call(withActiveBrowserProfile(request, enabled));+ }++ if (!enabled) {+ return revertToIsolated();+ }++ const readRemembered = deps.readRememberedCdpPort ?? readCopiedLoginsCdpPort;+ if (+ shouldStopRememberedLeftover({+ enabled: true,+ running: isRunning(status.data),+ ownLive: false,+ rememberedCdpPort: readRemembered(runtimeDir),+ })+ ) {+ const stop = await inner.call({ action: 'stop' });+ try {+ assertManagedBrowserStopped({ status, stop });+ } catch (err) {+ if (isRealProfileError(err)) return failure(request.action, err.code, err.message);+ return failure(request.action, FOREIGN_AGENT_BROWSER_ERROR, FOREIGN_AGENT_BROWSER_ERROR);+ }+ }++ let cdpPort = MANAGED_CDP_PORT;+ try {+ const pick = deps.pickCdpPort ?? ((preferred: number) => pickManagedCdpPort(preferred));+ cdpPort = await pick(MANAGED_CDP_PORT);+ } catch (err) {+ if (isRealProfileError(err)) return failure(request.action, err.code, err.message);+ return failure(request.action, FOREIGN_AGENT_BROWSER_ERROR, FOREIGN_AGENT_BROWSER_ERROR);+ }++ if (isHeadless(status.data)) {+ return failure(+ request.action,+ 'HEADLESS_FORBIDDEN',+ 'Real-profile browsing cannot run in headless mode (it would use a separate cookie store).',+ );+ }++ if (!runtimeDir) {+ return failure(request.action, 'COPY_FAILED', 'Browser runtime directory is not configured.');+ }++ try {+ const source = deps.resolveSource();+ const result: SnapshotResult = await deps.snapshot({+ source,+ destDir: realProfileDestDir(runtimeDir),+ platform: deps.platform,+ });+ if (!deps.isEnabled()) {+ return revertToIsolated();+ }+ deps.applyConfig({+ useRealProfile: true,+ executablePath: source.executablePath,+ cdpPort,+ });+ deps.setLastApplied(result.sourceKind);+ rememberCopiedLoginsCdpPort(runtimeDir, cdpPort);+ } catch (err) {+ deps.setLastApplied(null);+ if (isRealProfileError(err)) {+ return failure(request.action, err.code, err.message);+ }+ return failure(+ request.action,+ 'COPY_FAILED',+ err instanceof Error ? err.message : 'Failed to copy browser logins.',+ );+ }++ if (!deps.isEnabled()) {+ return revertToIsolated();+ }+ return inner.call(withActiveBrowserProfile(request, true));+}++function failure(+ action: BrowserControlRequest['action'],+ code: string,+ message: string,+): BrowserControlResult {+ void code;+ return {+ ok: false,+ action,+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',+ message,+ };+}++export function realProfileErrorFromCode(code: string, message: string): RealProfileError {+ if (+ code === 'NO_CHROMIUM' ||+ code === 'PROFILE_LOCKED' ||+ code === 'NO_AUTH_DB' ||+ code === 'HEADLESS_FORBIDDEN' ||+ code === 'COPY_FAILED'+ ) {+ return new RealProfileError(code, message);+ }+ return new RealProfileError('COPY_FAILED', message);+}diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/runtime-stop.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/runtime-stop.tsnew file mode 100644index 0000000000..b37f91a3dd--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/runtime-stop.ts@@ -0,0 +1,53 @@+import type { BrowserControlResult } from '@cindy/browser-control-runtime';++import { RealProfileError } from './types.js';++function isRunningFlag(data: unknown): boolean {+ return (+ data !== null && typeof data === 'object' && (data as { running?: unknown }).running === true+ );+}++function isStoppedFlag(data: unknown): boolean {+ return (+ data !== null && typeof data === 'object' && (data as { stopped?: unknown }).stopped === true+ );+}++/**+ * Live-stop must not hot-reload managed identity. Crash restart already+ * injected the remembered CDP port at module load; a live session still has+ * `executablePath` + `cdpPort` from the last start. Rebuilding config with+ * only `cdpPort` drops the source browser path, the vendored runtime treats+ * that as a profile invariant change, kills the process, then returns+ * `stopped: false`.+ */+export function managedConfigPatchBeforeStop(_input: {+ rememberedCdpPort: number | null;+}): { useRealProfile: true; cdpPort: number; executablePath?: string } | null {+ return null;+}++/**+ * Profile / consent switches must not proceed while the managed Chrome is still+ * up. POSIX unlinks leave cookie and password bytes in open handles; a failed+ * or unverifiable stop is therefore a hard failure, not a warning.+ */+export function assertManagedBrowserStopped(options: {+ status: BrowserControlResult;+ stop: BrowserControlResult | null;+}): void {+ if (!options.status.ok) {+ throw new RealProfileError(+ 'STOP_FAILED',+ 'Could not verify that the agent browser has stopped.',+ );+ }+ if (!isRunningFlag(options.status.data)) return;+ if (!options.stop?.ok || !isStoppedFlag(options.stop.data)) {+ throw new RealProfileError(+ 'STOP_FAILED',+ 'Could not stop the agent browser before changing copied logins.',+ );+ }+}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.tsnew file mode 100644index 0000000000..33c80b1590--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/snapshot.ts@@ -0,0 +1,536 @@+import fs from 'node:fs';+import path from 'node:path';+import { backup, DatabaseSync } from 'node:sqlite';++import {+ MANAGED_CDP_PORT,+ MANAGED_PROFILE,+ REAL_MANAGED_PROFILE,+} from '../browser-managed-config.js';+import { REAL_PROFILE_READ_DENIED } from '../../../shared/browserBackend.js';+import { resolveSourceBrowserFromOs } from './source.js';+import {+ isRealProfileError,+ RealProfileError,+ type InstalledChromium,+ type SnapshotResult,+} from './types.js';++const COMPLETE_MARKER = '.cindy-real-profile-complete';++/** SQLite auth databases that must be copied consistently (online-backup). */+const AUTH_DB_RELATIVE_PATHS = [+ 'Cookies',+ path.join('Network', 'Cookies'),+ 'Login Data',+ 'Login Data For Account',+ 'Web Data',+] as const;++const PLAIN_PROFILE_FILES = ['Preferences'] as const;++const SNAPSHOT_PROFILE_RELATIVE_PATHS = [+ ...AUTH_DB_RELATIVE_PATHS,+ ...PLAIN_PROFILE_FILES,+] as const;++const COOKIE_DB_CANDIDATES = ['Cookies', path.join('Network', 'Cookies')] as const;++/** Profile wrapper under the runtime (`browser/Cindy-real`). Cleanup deletes this whole tree. */+export function realProfileProfileDir(runtimeDir: string): string {+ return path.join(runtimeDir, 'browser', REAL_MANAGED_PROFILE);+}++/**+ * Chrome `--user-data-dir` for the consented snapshot. The vendored runtime+ * launches `CONFIG_DIR/browser/<profile>/user-data`, so cookies must land here+ * — not in the profile wrapper itself.+ */+export function realProfileDestDir(runtimeDir: string): string {+ return path.join(realProfileProfileDir(runtimeDir), 'user-data');+}++export function isolatedProfileDestDir(runtimeDir: string): string {+ return path.join(runtimeDir, 'browser', 'Cindy');+}++export function lastUsedProfileName(localStateRaw: string): string {+ try {+ const parsed = JSON.parse(localStateRaw) as { profile?: { last_used?: unknown } };+ const lastUsed = parsed.profile?.last_used;+ if (typeof lastUsed === 'string' && lastUsed.trim()) return lastUsed.trim();+ } catch {+ // Fall through to Default when Local State is missing or malformed.+ }+ return 'Default';+}++function asObject(value: unknown): Record<string, unknown> | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ return value as Record<string, unknown>;+}++/**+ * Copies last_used cookies into dest `Default`. Chrome still honors+ * Local State `profile.last_used`, so a verbatim copy would open the original+ * folder (often an empty `Profile 2`) and look signed-out. Point every+ * selection field at Default and keep only that info_cache entry, taking+ * metadata from the source last_used profile when present. Stamp the chip+ * name to `Cindy` so a copied "Dash" / "Person 1" label never leaks; launch+ * decoration uses the same display name.+ */+export function rewriteLocalStateForManagedDefault(+ localStateRaw: string,+ sourceProfile: string,+): string {+ let parsed =+ asObject(+ (() => {+ try {+ return JSON.parse(localStateRaw) as unknown;+ } catch {+ return {};+ }+ })(),+ ) ?? {};+ const profile = { ...(asObject(parsed.profile) ?? {}) };+ const infoCache = asObject(profile.info_cache) ?? {};+ const sourceInfo = {+ ...(asObject(infoCache[sourceProfile]) ?? asObject(infoCache.Default) ?? {}),+ };+ sourceInfo.name = MANAGED_PROFILE;+ sourceInfo.shortcut_name = MANAGED_PROFILE;+ sourceInfo.user_name = MANAGED_PROFILE;+ profile.last_used = 'Default';+ profile.last_active_profiles = ['Default'];+ profile.profiles_order = ['Default'];+ profile.profiles_created = 1;+ profile.show_picker_on_startup = false;+ profile.info_cache = { Default: sourceInfo };+ parsed = { ...parsed, profile };+ return `${JSON.stringify(parsed)}\n`;+}++/** Chrome user-profile folders that are not dest `Default` leftover from a previous launch. */+const EXTRA_CHROME_PROFILE_DIR = /^(Profile \d+|Guest Profile)$/;++export function pruneExtraChromeProfiles(userDataDir: string): void {+ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(userDataDir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ if (!EXTRA_CHROME_PROFILE_DIR.test(entry.name)) continue;+ fs.rmSync(path.join(userDataDir, entry.name), { recursive: true, force: true });+ }+}++/** HTTP / GPU caches that cannot replay a login. Dest Default is otherwise rebuilt. */+const DISCARDABLE_PROFILE_CACHE_NAMES = new Set([+ 'Cache',+ 'Code Cache',+ 'GPUCache',+ 'GrShaderCache',+ 'ShaderCache',+ 'DawnGraphiteCache',+ 'DawnWebGPUCache',+]);++/**+ * Drop leftover Local Storage / IndexedDB / Service Worker / etc. from a+ * previous source profile. Keep only this snapshot's auth files and caches.+ */+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[];+ try {+ entries = fs.readdirSync(destProfileDir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (keep.has(entry.name)) continue;+ fs.rmSync(path.join(destProfileDir, entry.name), { recursive: true, force: true });+ }+}++export function profileIsLocked(options: {+ profileDir: string;+ platform: NodeJS.Platform;+}): boolean {+ if (options.platform !== 'win32') return false;+ for (const relative of COOKIE_DB_CANDIDATES) {+ const cookieDb = path.join(options.profileDir, relative);+ if (!fs.existsSync(cookieDb)) continue;+ try {+ const fd = fs.openSync(cookieDb, 'r+');+ fs.closeSync(fd);+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === 'EPERM' || code === 'EBUSY' || code === 'EACCES') return true;+ }+ }+ return false;+}++function isPermissionDenied(err: unknown): boolean {+ const code = (err as NodeJS.ErrnoException | undefined)?.code;+ return code === 'EPERM' || code === 'EACCES';+}++function tryOpenRead(filePath: string): 'ok' | 'missing' | 'denied' {+ try {+ const fd = fs.openSync(filePath, 'r');+ fs.closeSync(fd);+ return 'ok';+ } catch (err) {+ if (isPermissionDenied(err)) return 'denied';+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';+ return 'ok';+ }+}++function tryOpenDir(dirPath: string): 'ok' | 'missing' | 'denied' {+ try {+ const dir = fs.opendirSync(dirPath);+ dir.closeSync();+ return 'ok';+ } catch (err) {+ if (isPermissionDenied(err)) return 'denied';+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';+ return 'ok';+ }+}++/**+ * Open-only probe of the source Chromium profile. Does not copy cookies.+ * `readable: true` means Full Disk Access is already granted or not the blocker+ * (missing Chrome / missing files). Tests must pass a fake `source`.+ */+export function probeSourceProfileReadAccess(source: InstalledChromium): { readable: boolean } {+ const userData = tryOpenDir(source.userDataDir);+ if (userData === 'denied') return { readable: false };+ if (userData === 'missing') return { readable: true };++ const localStatePath = path.join(source.userDataDir, 'Local State');+ const localState = tryOpenRead(localStatePath);+ if (localState === 'denied') return { readable: false };++ let sourceProfile = 'Default';+ if (localState === 'ok') {+ try {+ sourceProfile = lastUsedProfileName(fs.readFileSync(localStatePath, 'utf8'));+ } catch (err) {+ if (isPermissionDenied(err)) return { readable: false };+ }+ }++ const sourceProfileDir = path.join(source.userDataDir, sourceProfile);+ const profileDir = tryOpenDir(sourceProfileDir);+ if (profileDir === 'denied') return { readable: false };++ for (const relative of AUTH_DB_RELATIVE_PATHS) {+ const result = tryOpenRead(path.join(sourceProfileDir, relative));+ if (result === 'denied') return { readable: false };+ }+ return { readable: true };+}++/** Production entry: resolve the OS source browser, then probe. Never returns paths. */+export function probeOsSourceProfileReadAccess(options?: {+ resolveSource?: () => InstalledChromium;+}): { readable: boolean } {+ try {+ const source = (options?.resolveSource ?? resolveSourceBrowserFromOs)();+ return probeSourceProfileReadAccess(source);+ } catch (err) {+ if (isRealProfileError(err) && err.code === 'NO_CHROMIUM') return { readable: true };+ if (isPermissionDenied(err)) return { readable: false };+ return { readable: true };+ }+}++function throwReadDenied(): never {+ throw new RealProfileError('COPY_FAILED', REAL_PROFILE_READ_DENIED);+}++function secureDir(dir: string): void {+ fs.mkdirSync(dir, { recursive: true });+ try {+ fs.chmodSync(dir, 0o700);+ } catch {+ // Windows cannot always chmod; the snapshot still lives under userData.+ }+}++const SQLITE_SIDECARS = ['-wal', '-shm', '-journal'] as const;++function removeSqliteAndSidecars(filePath: string): void {+ fs.rmSync(filePath, { force: true });+ for (const suffix of SQLITE_SIDECARS) {+ fs.rmSync(filePath + suffix, { force: true });+ }+}++function publishStagedFile(src: string, dest: string): void {+ fs.mkdirSync(path.dirname(dest), { recursive: true });+ removeSqliteAndSidecars(dest);+ fs.renameSync(src, dest);+ for (const suffix of SQLITE_SIDECARS) {+ const side = src + suffix;+ if (fs.existsSync(side)) {+ fs.renameSync(side, dest + suffix);+ }+ }+}++/**+ * Swap this snapshot's auth files onto dest only after the staging tree is+ * complete. Dest HTTP/GPU caches stay; leftover Cookies vs Network/Cookies,+ * Login Data, and site credential stores from a previous source do not.+ */+function publishStagedSnapshot(options: {+ stagingDir: string;+ destDir: string;+ copiedRelative: ReadonlySet<string>;+}): void {+ const { stagingDir, destDir, copiedRelative } = options;+ secureDir(path.dirname(destDir));+ secureDir(destDir);+ const destProfileDir = path.join(destDir, 'Default');+ secureDir(destProfileDir);+ secureDir(path.join(destProfileDir, 'Network'));++ publishStagedFile(path.join(stagingDir, 'Local State'), path.join(destDir, 'Local State'));++ for (const relative of SNAPSHOT_PROFILE_RELATIVE_PATHS) {+ const destFile = path.join(destProfileDir, relative);+ const stagingFile = path.join(stagingDir, 'Default', relative);+ if (copiedRelative.has(relative)) {+ publishStagedFile(stagingFile, destFile);+ } else {+ removeSqliteAndSidecars(destFile);+ }+ }++ pruneNonAuthProfileState(destProfileDir);+ pruneExtraChromeProfiles(destDir);+ fs.rmSync(stagingDir, { recursive: true, force: true });+}++async function copySqliteDatabase(src: string, dest: string): 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 });+ try {+ // 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.+ await backup(source, dest);+ } finally {+ source.close();+ }+}++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;+ platform?: NodeJS.Platform;+}): Promise<SnapshotResult> {+ const platform = options.platform ?? process.platform;+ const destDir = options.destDir;+ if (+ path.basename(destDir) !== 'user-data' ||+ path.basename(path.dirname(destDir)) !== REAL_MANAGED_PROFILE+ ) {+ throw new RealProfileError(+ 'COPY_FAILED',+ `Refusing to snapshot into ${path.basename(path.dirname(destDir))}/${path.basename(destDir)}; expected ${REAL_MANAGED_PROFILE}/user-data.`,+ );+ }++ const localStatePath = path.join(options.source.userDataDir, 'Local State');+ let localStateRaw = '{}';+ try {+ if (fs.existsSync(localStatePath)) {+ localStateRaw = fs.readFileSync(localStatePath, 'utf8');+ }+ } catch (err) {+ if (isPermissionDenied(err)) throwReadDenied();+ throw err;+ }+ const sourceProfile = lastUsedProfileName(localStateRaw);+ const sourceProfileDir = path.join(options.source.userDataDir, sourceProfile);++ if (!fs.existsSync(sourceProfileDir)) {+ throw new RealProfileError(+ 'NO_AUTH_DB',+ `Chrome profile folder "${sourceProfile}" was not found.`,+ );+ }++ if (profileIsLocked({ profileDir: sourceProfileDir, platform })) {+ throw new RealProfileError(+ 'PROFILE_LOCKED',+ 'Chrome is locking its cookie database. Quit Chrome completely (including the tray icon) and try again.',+ );+ }++ secureDir(path.dirname(destDir));+ let stagingDir = '';++ try {+ stagingDir = fs.mkdtempSync(`${destDir}.staging-`);+ secureDir(stagingDir);+ const stagingProfileDir = path.join(stagingDir, 'Default');+ secureDir(stagingProfileDir);+ secureDir(path.join(stagingProfileDir, 'Network'));++ const filesCopied: string[] = [];+ const copiedRelative = new Set<string>();+ let authDbCopied = 0;++ await fs.promises.writeFile(+ path.join(stagingDir, 'Local State'),+ rewriteLocalStateForManagedDefault(localStateRaw, sourceProfile),+ 'utf8',+ );+ filesCopied.push('Local State');++ for (const relative of AUTH_DB_RELATIVE_PATHS) {+ const src = path.join(sourceProfileDir, relative);+ if (!fs.existsSync(src)) continue;+ const dest = path.join(stagingProfileDir, relative);+ try {+ await copyAuthFile(src, dest, true);+ filesCopied.push(path.join('Default', relative));+ copiedRelative.add(relative);+ authDbCopied += 1;+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (isPermissionDenied(err) && platform !== 'win32') throwReadDenied();+ if (platform === 'win32' && (code === 'EPERM' || code === 'EBUSY' || code === 'EACCES')) {+ throw new RealProfileError(+ 'PROFILE_LOCKED',+ 'Chrome is locking its cookie database. Quit Chrome completely and try again.',+ );+ }+ throw new RealProfileError(+ 'COPY_FAILED',+ `Failed to copy ${relative} from the system browser profile.`,+ );+ }+ }++ const copiedCookie =+ copiedRelative.has('Cookies') || copiedRelative.has(path.join('Network', 'Cookies'));+ if (!copiedCookie || authDbCopied === 0) {+ throw new RealProfileError(+ 'NO_AUTH_DB',+ 'Could not copy cookie or login databases from the system browser profile.',+ );+ }++ for (const relative of PLAIN_PROFILE_FILES) {+ const src = path.join(sourceProfileDir, relative);+ if (!fs.existsSync(src)) continue;+ const dest = path.join(stagingProfileDir, relative);+ await fs.promises.copyFile(src, dest);+ filesCopied.push(path.join('Default', relative));+ copiedRelative.add(relative);+ }++ publishStagedSnapshot({ stagingDir, destDir, copiedRelative });++ await fs.promises.writeFile(+ path.join(destDir, COMPLETE_MARKER),+ JSON.stringify({ sourceProfile, sourceKind: options.source.kind }),+ 'utf8',+ );++ return {+ destDir,+ sourceKind: options.source.kind,+ sourceProfile,+ filesCopied,+ };+ } catch (err) {+ if (stagingDir) fs.rmSync(stagingDir, { recursive: true, force: true });+ throw err;+ }+}++function completeMarkerPath(destDir: string): string {+ return path.join(destDir, COMPLETE_MARKER);+}++function isManagedCdpPort(port: unknown): port is number {+ return (+ typeof port === 'number' &&+ Number.isInteger(port) &&+ port >= MANAGED_CDP_PORT &&+ port < MANAGED_CDP_PORT + 20+ );+}++/** CDP port last used for Cindy-real, stored on the existing complete marker. */+export function readCopiedLoginsCdpPort(runtimeDir: string): number | null {+ if (!runtimeDir) return null;+ try {+ const parsed = JSON.parse(+ fs.readFileSync(completeMarkerPath(realProfileDestDir(runtimeDir)), 'utf8'),+ ) as {+ cdpPort?: unknown;+ };+ return isManagedCdpPort(parsed.cdpPort) ? parsed.cdpPort : null;+ } catch {+ return null;+ }+}++export function rememberCopiedLoginsCdpPort(runtimeDir: string, port: number): void {+ if (!runtimeDir || !isManagedCdpPort(port)) return;+ const file = completeMarkerPath(realProfileDestDir(runtimeDir));+ if (!fs.existsSync(file)) return;+ let parsed: Record<string, unknown> = {};+ try {+ parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Record<string, unknown>;+ } catch {+ parsed = {};+ }+ fs.writeFileSync(file, JSON.stringify({ ...parsed, cdpPort: port }), 'utf8');+}++export function cleanupRealProfileSnapshots(runtimeDir: string): void {+ const profileDir = realProfileProfileDir(runtimeDir);+ if (path.basename(profileDir) !== REAL_MANAGED_PROFILE) return;+ if (!fs.existsSync(profileDir)) return;+ fs.rmSync(profileDir, { recursive: true, force: true });+}++/**+ * Delete the Cindy-real copy, then run `then`. If delete throws, `then` does+ * not run — Settings must keep consent on so the user can retry.+ */+export function cleanupCopiedLoginsThen(runtimeDir: string | null, then: () => void): void {+ if (runtimeDir) cleanupRealProfileSnapshots(runtimeDir);+ then();+}diff --git a/apps/desktop/src/main/mcp-integrations/browser-real-profile/source.ts b/apps/desktop/src/main/mcp-integrations/browser-real-profile/source.tsnew file mode 100644index 0000000000..2859948de5--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/source.ts@@ -0,0 +1,361 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { execFileSync } from 'node:child_process';++import {+ CHROMIUM_KINDS,+ RealProfileError,+ type ChromiumKind,+ type DefaultBrowserKind,+ type InstalledChromium,+} from './types.js';++const BUNDLE_ID_TO_KIND: Record<string, ChromiumKind | 'other'> = {+ 'com.google.chrome': 'chrome',+ 'com.google.chrome.canary': 'other',+ 'com.google.chrome.beta': 'other',+ 'com.google.chrome.dev': 'other',+ 'com.microsoft.edgemac': 'edge',+ 'com.microsoft.edgemac.beta': 'other',+ 'com.microsoft.edgemac.dev': 'other',+ 'com.microsoft.edgemac.canary': 'other',+ 'com.brave.browser': 'brave',+ 'com.brave.browser.beta': 'other',+ 'com.brave.browser.nightly': 'other',+ 'org.chromium.chromium': 'chromium',+ 'com.apple.safari': 'other',+ 'org.mozilla.firefox': 'other',+};++const PROGID_TO_KIND: Record<string, ChromiumKind | 'other'> = {+ chromehtml: 'chrome',+ chromebhtml: 'other',+ chromedhtml: 'other',+ msedgehtm: 'edge',+ msedgebhtm: 'other',+ bravehtml: 'brave',+ firefoxurl: 'other',+ firefoxhtml: 'other',+};++const DESKTOP_TO_KIND: Record<string, ChromiumKind | 'other'> = {+ 'google-chrome.desktop': 'chrome',+ 'google-chrome-stable.desktop': 'chrome',+ 'google-chrome-beta.desktop': 'other',+ 'microsoft-edge.desktop': 'edge',+ 'microsoft-edge-stable.desktop': 'edge',+ 'brave-browser.desktop': 'brave',+ 'chromium-browser.desktop': 'chromium',+ 'chromium.desktop': 'chromium',+ 'firefox.desktop': 'other',+ 'org.mozilla.firefox.desktop': 'other',+};++function pathFor(platform: NodeJS.Platform) {+ return platform === 'win32' ? path.win32 : path.posix;+}++function snapUserDataDir(+ kind: ChromiumKind,+ home: string,+ executablePath: string | undefined,+): string | null {+ if (!executablePath?.startsWith('/snap/bin/')) return null;+ const binary = executablePath.slice('/snap/bin/'.length);+ if (!binary || binary.includes('/')) return null;+ const osPath = path.posix;+ switch (kind) {+ case 'chrome':+ if (binary !== 'google-chrome' && binary !== 'chrome') return null;+ return osPath.join(home, 'snap', 'google-chrome', 'current', '.config', 'google-chrome');+ case 'brave':+ if (binary !== 'brave') return null;+ return osPath.join(+ home,+ 'snap',+ 'brave',+ 'current',+ '.config',+ 'BraveSoftware',+ 'Brave-Browser',+ );+ case 'chromium':+ if (binary !== 'chromium') return null;+ return osPath.join(home, 'snap', 'chromium', 'common', 'chromium');+ case 'edge':+ return null;+ }+}++export function userDataDirFor(+ kind: ChromiumKind,+ platform: NodeJS.Platform,+ home: string,+ env: NodeJS.ProcessEnv = process.env,+ executablePath?: string,+): string {+ const snapDir = snapUserDataDir(kind, home, executablePath);+ if (snapDir) return snapDir;+ const osPath = pathFor(platform);+ if (platform === 'darwin') {+ const support = osPath.join(home, 'Library', 'Application Support');+ switch (kind) {+ case 'chrome':+ return osPath.join(support, 'Google', 'Chrome');+ case 'edge':+ return osPath.join(support, 'Microsoft Edge');+ case 'brave':+ return osPath.join(support, 'BraveSoftware', 'Brave-Browser');+ case 'chromium':+ return osPath.join(support, 'Chromium');+ }+ }+ if (platform === 'win32') {+ const local = env.LOCALAPPDATA || osPath.join(home, 'AppData', 'Local');+ switch (kind) {+ case 'chrome':+ return osPath.join(local, 'Google', 'Chrome', 'User Data');+ case 'edge':+ return osPath.join(local, 'Microsoft', 'Edge', 'User Data');+ case 'brave':+ return osPath.join(local, 'BraveSoftware', 'Brave-Browser', 'User Data');+ case 'chromium':+ return osPath.join(local, 'Chromium', 'User Data');+ }+ }+ switch (kind) {+ case 'chrome':+ return osPath.join(home, '.config', 'google-chrome');+ case 'edge':+ return osPath.join(home, '.config', 'microsoft-edge');+ case 'brave':+ return osPath.join(home, '.config', 'BraveSoftware', 'Brave-Browser');+ case 'chromium':+ return osPath.join(home, '.config', 'chromium');+ }+}++export function executableCandidates(+ kind: ChromiumKind,+ platform: NodeJS.Platform,+ env: NodeJS.ProcessEnv = process.env,+ home = os.homedir(),+): string[] {+ if (platform === 'darwin') {+ const macApp = (appName: string, binary: string): string[] => {+ const bundle = `${appName}.app/Contents/MacOS/${binary}`;+ return [`/Applications/${bundle}`, path.posix.join(home, 'Applications', bundle)];+ };+ switch (kind) {+ case 'chrome':+ return macApp('Google Chrome', 'Google Chrome');+ case 'edge':+ return macApp('Microsoft Edge', 'Microsoft Edge');+ case 'brave':+ return macApp('Brave Browser', 'Brave Browser');+ case 'chromium':+ return macApp('Chromium', 'Chromium');+ }+ }+ if (platform === 'win32') {+ const pf = env['PROGRAMFILES'] || 'C:\\Program Files';+ const pf86 = env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)';+ const local = env.LOCALAPPDATA || '';+ switch (kind) {+ case 'chrome':+ return [+ path.join(pf, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ path.join(pf86, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ path.join(local, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ ];+ case 'edge':+ return [+ path.join(pf, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),+ path.join(pf86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),+ path.join(local, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),+ ];+ case 'brave':+ return [+ path.join(pf, 'BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'),+ path.join(local, 'BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'),+ ];+ case 'chromium':+ return [path.join(local, 'Chromium', 'Application', 'chrome.exe')];+ }+ }+ switch (kind) {+ case 'chrome':+ return [+ '/usr/bin/google-chrome-stable',+ '/usr/bin/google-chrome',+ '/usr/bin/chrome',+ '/opt/google/chrome/chrome',+ '/snap/bin/google-chrome',+ ];+ case 'edge':+ return ['/usr/bin/microsoft-edge', '/usr/bin/microsoft-edge-stable'];+ case 'brave':+ return [+ '/usr/bin/brave-browser',+ '/usr/bin/brave-browser-stable',+ '/usr/bin/brave',+ '/opt/brave.com/brave/brave-browser',+ '/snap/bin/brave',+ ];+ case 'chromium':+ return [+ '/usr/bin/chromium-browser',+ '/usr/bin/chromium',+ '/usr/lib/chromium/chromium',+ '/usr/lib/chromium-browser/chromium-browser',+ '/snap/bin/chromium',+ ];+ }+}++export function parseDefaultHandler(+ platform: NodeJS.Platform,+ raw: string | null | undefined,+): DefaultBrowserKind {+ if (!raw) return null;+ const text = raw.trim();+ if (!text) return null;++ if (platform === 'darwin') {+ const blocks = [...text.matchAll(/\{[\s\S]*?\}/g)].map((m) => m[0]);+ let last: DefaultBrowserKind = null;+ for (const block of blocks) {+ if (!/LSHandlerURLScheme\s*=\s*"?https"?/i.test(block)) continue;+ const idMatch = block.match(/LSHandlerRoleAll\s*=\s*"?([^";\s]+)"?/i);+ if (!idMatch) continue;+ last = mapBundleId(idMatch[1]);+ }+ if (last) return last;+ return mapBundleId(text);+ }++ if (platform === 'win32') {+ const match = text.match(/ProgId\s+REG_SZ\s+(\S+)/i) ?? text.match(/^\s*(\S+)\s*$/m);+ return mapProgId(match?.[1] ?? text);+ }++ const desktop = text.split('/').pop()?.toLowerCase() ?? text.toLowerCase();+ return DESKTOP_TO_KIND[desktop] ?? 'other';+}++function mapBundleId(id: string): DefaultBrowserKind {+ return BUNDLE_ID_TO_KIND[id.trim().toLowerCase()] ?? 'other';+}++function mapProgId(id: string): DefaultBrowserKind {+ const normalized = id.trim().toLowerCase().replace(/-\S+$/, '');+ for (const [key, kind] of Object.entries(PROGID_TO_KIND)) {+ if (normalized.startsWith(key)) return kind;+ }+ return 'other';+}++export function listInstalledChromium(options: {+ platform: NodeJS.Platform;+ home: string;+ env?: NodeJS.ProcessEnv;+ exists?: (filePath: string) => boolean;+}): InstalledChromium[] {+ const exists = options.exists ?? ((filePath) => fs.existsSync(filePath));+ const env = options.env ?? process.env;+ const found: InstalledChromium[] = [];+ for (const kind of CHROMIUM_KINDS) {+ const executablePath = executableCandidates(kind, options.platform, env, options.home).find(+ exists,+ );+ if (!executablePath) continue;+ found.push({+ kind,+ executablePath,+ userDataDir: userDataDirFor(kind, options.platform, options.home, env, executablePath),+ });+ }+ return found;+}++export function resolveSourceBrowser(options: {+ defaultKind: DefaultBrowserKind;+ installed: InstalledChromium[];+}): InstalledChromium {+ const { defaultKind, installed } = options;+ if (defaultKind && defaultKind !== 'other') {+ const match = installed.find((item) => item.kind === defaultKind);+ if (match) return match;+ }+ for (const kind of CHROMIUM_KINDS) {+ const match = installed.find((item) => item.kind === kind);+ if (match) return match;+ }+ throw new RealProfileError(+ 'NO_CHROMIUM',+ 'No Chrome, Edge, or Brave install found to copy logins from.',+ );+}++export function detectDefaultHandlerFromOs(options?: {+ platform?: NodeJS.Platform;+ run?: (command: string, args: string[]) => string | null;+}): DefaultBrowserKind {+ const platform = options?.platform ?? process.platform;+ const run =+ options?.run ??+ ((command, args) => {+ try {+ return execFileSync(command, args, {+ encoding: 'utf8',+ timeout: 4000,+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ } catch {+ return null;+ }+ });++ if (platform === 'darwin') {+ return parseDefaultHandler(+ platform,+ run('defaults', [+ 'read',+ 'com.apple.LaunchServices/com.apple.launchservices.secure',+ 'LSHandlers',+ ]),+ );+ }+ if (platform === 'win32') {+ return parseDefaultHandler(+ platform,+ run('reg', [+ 'query',+ 'HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice',+ '/v',+ 'ProgId',+ ]),+ );+ }+ return parseDefaultHandler(platform, run('xdg-settings', ['get', 'default-web-browser']));+}++export function resolveSourceBrowserFromOs(options?: {+ platform?: NodeJS.Platform;+ home?: string;+ env?: NodeJS.ProcessEnv;+ exists?: (filePath: string) => boolean;+ run?: (command: string, args: string[]) => string | null;+}): InstalledChromium {+ const platform = options?.platform ?? process.platform;+ const home = options?.home ?? os.homedir();+ const installed = listInstalledChromium({+ platform,+ home,+ env: options?.env,+ exists: options?.exists,+ });+ const defaultKind = detectDefaultHandlerFromOs({ platform, run: options?.run });+ return resolveSourceBrowser({ defaultKind, installed });+}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.tsnew file mode 100644index 0000000000..c3963aaaa1--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/types.ts@@ -0,0 +1,52 @@+/**+ * Real-profile browsing: copy the user's Chromium-family login databases into a+ * Cindy-managed snapshot directory, then launch the same browser binary against+ * that copy. This is consent-gated convenience, not an isolation boundary.+ */++export type ChromiumKind = 'chrome' | 'edge' | 'brave' | 'chromium';++export const CHROMIUM_KINDS = ['chrome', 'edge', 'brave', 'chromium'] as const;++export type RealProfileErrorCode =+ | 'NO_CHROMIUM'+ | 'PROFILE_LOCKED'+ | 'NO_AUTH_DB'+ | 'HEADLESS_FORBIDDEN'+ | 'COPY_FAILED'+ | 'STOP_FAILED';++export class RealProfileError extends Error {+ readonly code: RealProfileErrorCode;++ constructor(code: RealProfileErrorCode, message: string) {+ super(message);+ this.name = 'RealProfileError';+ this.code = code;+ }+}++export function isRealProfileError(err: unknown): err is RealProfileError {+ return err instanceof RealProfileError;+}++export interface InstalledChromium {+ kind: ChromiumKind;+ executablePath: string;+ userDataDir: string;+}++export interface SnapshotResult {+ destDir: string;+ sourceKind: ChromiumKind;+ sourceProfile: string;+ filesCopied: string[];+}++export interface RealProfileStatusHint {+ enabled: boolean;+ applied: boolean;+ source: ChromiumKind | null;+}++export type DefaultBrowserKind = ChromiumKind | 'other' | null;diff --git a/apps/desktop/src/main/mcp-integrations/browser-runtime-env.ts b/apps/desktop/src/main/mcp-integrations/browser-runtime-env.tsindex 140797dadc..a623b8d326 100644--- a/apps/desktop/src/main/mcp-integrations/browser-runtime-env.ts+++ b/apps/desktop/src/main/mcp-integrations/browser-runtime-env.ts@@ -2,12 +2,11 @@* Side-effect module: set XDT_BROWSER_RUNTIME_DIR BEFORE @cindy/browser-control-runtime* is imported.*- * The runtime reads this env var into an EAGER module-level const (CONFIG_DIR, in- * `packages/browser-control-runtime/src/shim/_local/text-utils.ts`) at import time, so- * it must already be set — otherwise the runtime falls back to `~/.xdt-maker`.- * `browser.ts` imports this ABOVE the runtime import so the browser profile data lands- * under Electron userData (rule 15: a per-install location that's cleaned on uninstall)- * instead of a shared home-dir fallback.+ * The runtime reads this env var into CONFIG_DIR+ * (`packages/browser-control-runtime/src/shim/_local/text-utils.ts`). Vite's main+ * bundle require()s that module before `index.ts` body, so desktop also refreshes+ * the live binding after pinning. This module remains the fallback for tests that+ * import `browser.ts` without going through `index.ts`.*/import path from 'node:path';import { app } from 'electron';diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.tsindex 8b2e611c8b..46e5fe1ba6 100644--- a/apps/desktop/src/main/mcp-integrations/browser.ts+++ b/apps/desktop/src/main/mcp-integrations/browser.ts@@ -11,6 +11,7 @@ import nodePath from 'node:path';import { app, ipcMain } from 'electron';import {createBrowserControlRuntime,+ setBrowserControlRuntimeConfig,type BrowserControlRuntime,} from '@cindy/browser-control-runtime';@@ -30,6 +31,7 @@ import { getRsbBrowserBridge } from '../rsb-browser-bridge/index.js';import {readBrowserBackendSettings,writeBrowserBackendKind,+ writeBrowserUseRealProfile,resetBrowserBackendSettings,readBrowserBackendSettingsState,} from '../browser-backend-settings-store.js';@@ -39,8 +41,18 @@ import {} from '../rsb-browser-bridge/active-session.js';import { requireObject, optionalNullableString } from '../utils/ipcValidate.js';import { buildManagedConfig, MANAGED_PROFILE } from './browser-managed-config.js';+import {+ assertManagedBrowserStopped,+ cleanupCopiedLoginsThen,+ managedConfigPatchBeforeStop,+ FOREIGN_AGENT_BROWSER_ERROR,+ probeOsSourceProfileReadAccess,+ readCopiedLoginsCdpPort,+ wrapRuntimeWithRealProfile,+} from './browser-real-profile/index.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { createBrowserBackendIpcHandlers } from './browser-backend/settings-ipc.js';+import { raiseAgentBrowserWindow } from './raise-agent-browser-window.js';export { extractBrowserAvailability, type BrowserAvailability } from './browser-availability.js';@@ -64,7 +76,9 @@ function healLegacyManagedProfileDir(): void {const current = nodePath.join(runtimeDir, 'browser', MANAGED_PROFILE);if (fs.existsSync(legacy) && !fs.existsSync(current)) {fs.renameSync(legacy, current);- logger.info(`managed profile dir renamed in place: ${LEGACY_MANAGED_PROFILE} -> ${MANAGED_PROFILE}`);+ logger.info(+ `managed profile dir renamed in place: ${LEGACY_MANAGED_PROFILE} -> ${MANAGED_PROFILE}`,+ );}} catch (err) {logger.warn(`managed profile dir rename failed (fresh profile will be used): ${String(err)}`);@@ -72,6 +86,15 @@ function healLegacyManagedProfileDir(): void {}healLegacyManagedProfileDir();+function realProfileRuntimeDir(): string {+ return process.env.XDT_BROWSER_RUNTIME_DIR ?? '';+}++const initialUseRealProfile = readBrowserBackendSettings().useRealProfile;+const rememberedCopiedLoginsCdpPort = initialUseRealProfile+ ? readCopiedLoginsCdpPort(realProfileRuntimeDir())+ : null;+// Single shared runtime for the desktop process. Boots with the managed profile// (electron-free, safe at module-eval); logs route into the unified logger.//@@ -85,7 +108,10 @@ healLegacyManagedProfileDir();// Backend switching and recovery stay behind the process-wide controller.const vendoredRuntime = trackBrowserRuntimeUsage(createBrowserControlRuntime({- config: buildManagedConfig(),+ config: buildManagedConfig({+ useRealProfile: initialUseRealProfile,+ ...(rememberedCopiedLoginsCdpPort ? { cdpPort: rememberedCopiedLoginsCdpPort } : {}),+ }),logSink: (level, scope, args) => {// Bind to `logger`: the unified logger's methods rely on `this`, and calling// a detached `logger[level]` reference would lose it (undefined in strict@@ -96,15 +122,26 @@ const vendoredRuntime = trackBrowserRuntimeUsage(}),);-const externalBackend = new ExternalChromeBackend(vendoredRuntime, logger);+/**+ * Consent-gated snapshot wrapper sits *outside* usage tracking: a failed+ * copy must not count as "runtime used", or quit-time `stop` would boot+ * Playwright just to shut it down.+ */+const externalRuntime = wrapRuntimeWithRealProfile(vendoredRuntime, {+ isEnabled: () => readBrowserBackendSettings().useRealProfile,+ getRuntimeDir: realProfileRuntimeDir,+ applyConfig: (opts) => {+ setBrowserControlRuntimeConfig(buildManagedConfig(opts));+ },+});++const externalBackend = new ExternalChromeBackend(externalRuntime, logger);type SessionUploadRootResolver = (sessionId: string) => Promise<string[]>;let resolveSessionUploadRoots: SessionUploadRootResolver = async () => [];-export function setBrowserSessionUploadRootResolver(- resolver: SessionUploadRootResolver,-): void {+export function setBrowserSessionUploadRootResolver(resolver: SessionUploadRootResolver): void {resolveSessionUploadRoots = resolver;}@@ -169,10 +206,7 @@ const backendController = new BrowserBackendController({createRsbBackend,logger,});-const browserBackendHealthService = new BrowserBackendHealthService(- backendController,- logger,-);+const browserBackendHealthService = new BrowserBackendHealthService(backendController, logger);/*** Main-window webContents accessor — populated by bootstrap-electron via@@ -189,9 +223,7 @@ function readMainWindowForBackend(): Electron.WebContents | null {* Bootstrap hook. Called from `bootstrap-electron.ts` once `mainWindowRef` is* known. Idempotent re-binds are safe.*/-export function setMainWindowAccessorForBackend(- accessor: () => Electron.WebContents | null,-): void {+export function setMainWindowAccessorForBackend(accessor: () => Electron.WebContents | null): void {mainWindowAccessor = accessor;}@@ -242,6 +274,44 @@ export async function setActiveBrowserBackendKind(kind: BackendKind): Promise<vowriteBrowserBackendKind(kind);}+async function stopExternalRuntimeIfUsed(): Promise<void> {+ const useRealProfile = readBrowserBackendSettings().useRealProfile;+ const patch = managedConfigPatchBeforeStop({+ rememberedCdpPort: useRealProfile ? readCopiedLoginsCdpPort(realProfileRuntimeDir()) : null,+ });+ if (patch) {+ setBrowserControlRuntimeConfig(buildManagedConfig(patch));+ }+ const status = await vendoredRuntime.call({ action: 'status' });+ const running =+ status.ok &&+ status.data !== null &&+ typeof status.data === 'object' &&+ (status.data as { running?: unknown }).running === true;+ const stop = running ? await externalRuntime.call({ action: 'stop' }) : null;+ assertManagedBrowserStopped({ status, stop });+}++/**+ * Persist consent, stop the managed Chrome so the next start can switch+ * directories, and delete the snapshot when consent is revoked. Disable only+ * persists after the Cindy-real copy is gone; a cleanup failure keeps the+ * switch on so the user can retry. An unsuccessful or unverifiable stop also+ * aborts so POSIX open handles cannot keep copied cookies after unlink.+ */+export async function setBrowserUseRealProfile(enabled: boolean): Promise<boolean> {+ await stopExternalRuntimeIfUsed();+ if (!enabled) {+ cleanupCopiedLoginsThen(realProfileRuntimeDir(), () => {+ writeBrowserUseRealProfile(false);+ });+ } else {+ writeBrowserUseRealProfile(true);+ }+ setBrowserControlRuntimeConfig(buildManagedConfig({ useRealProfile: enabled }));+ return readBrowserBackendSettings().useRealProfile;+}+/*** Browser automation deps for cindy_browser MCP.*@@ -285,7 +355,7 @@ export function getBrowserMcpDeps(): {* backend selected, even on a machine with Chrome installed.*/export async function getBrowserAvailability(): Promise<BrowserAvailability> {- const res = await vendoredRuntime.call({ action: 'status' });+ const res = await externalRuntime.call({ action: 'status' });return extractBrowserAvailability(res.data);}@@ -319,6 +389,7 @@ export function getBrowserBackendHealth() {* - `browser-backend:reset` → clear user override, follow current default* - `browser-backend:get-health` → probe + one automatic embedded recovery* - `browser-backend:recover` → force a fresh embedded backend + verify+ * - `browser-backend:probe-source-read` → `{ readable }` only; skip FDA if true* - `rsb-browser-bridge:set-active-session` → renderer pushes the focused* sessionId; RsbWebviewBackend reads via getActiveRsbSessionId() at* action time (Phase 3 dependency).@@ -337,26 +408,37 @@ export function registerBrowserBackendIpc(): void {return {active: backendController.getCurrentBackendKind(),systemDefault: state.defaults.kind,- isOverride: state.isCustomized,+ isOverride: state.customizedKeys.includes('kind'),+ useRealProfile: state.value.useRealProfile,};},setKind: async (kind) => {await setActiveBrowserBackendKind(kind);return backendController.getCurrentBackendKind();},+ setUseRealProfile: async (enabled) => {+ return setBrowserUseRealProfile(enabled);+ },reset: async () => {+ const previous = readBrowserBackendSettings();const next = resetBrowserBackendSettings();+ if (previous.useRealProfile && !next.useRealProfile) {+ await setBrowserUseRealProfile(false);+ }await setActiveBrowserBackendKind(next.kind);return backendController.getCurrentBackendKind();},getHealth: getBrowserBackendHealth,recover: recoverActiveBrowserBackend,+ probeSourceRead: () => probeOsSourceProfileReadAccess(),});ipcMain.handle('browser-backend:get-state', handlers.getState);ipcMain.handle('browser-backend:set-kind', handlers.setKind);+ ipcMain.handle('browser-backend:set-use-real-profile', handlers.setUseRealProfile);ipcMain.handle('browser-backend:reset', handlers.reset);ipcMain.handle('browser-backend:get-health', handlers.getHealth);ipcMain.handle('browser-backend:recover', handlers.recover);+ ipcMain.handle('browser-backend:probe-source-read', handlers.probeSourceRead);ipcMain.handle('rsb-browser-bridge:set-active-session', (_e, payload: unknown) => {const obj = requireObject(payload, 'set-active-session payload');@@ -366,7 +448,7 @@ export function registerBrowserBackendIpc(): void {// surfacing the rare malformed-payload path as a hard error since the// semantic is "renderer no longer focused on any RSB session".const raw = optionalNullableString(obj.sessionId);- const sessionId: string | null = raw === null ? null : raw ?? null;+ const sessionId: string | null = raw === null ? null : (raw ?? null);setActiveRsbSessionId(sessionId);return { ok: true };});@@ -391,21 +473,19 @@ export async function openBrowserForLogin(): Promise<void> {// they don't need this button at all (logins go through the sidebar webview);// routing through the active controller would either no-op (rsb backend's `start` is a// no-op) or open the wrong thing.- const started = await vendoredRuntime.call({ action: 'start' });+ const started = await externalRuntime.call({ action: 'start' });if (!started.ok) {- throw new Error(started.message ?? `browser start failed (HTTP ${started.status ?? '?'})`);- }- // Best-effort raise: if the browser was already open, `start` is a no-op and its- // window stays behind ours — focus an existing tab to bring the OS window to front- // (no-op-safe on a fresh launch, which is already frontmost). Never opens a tab.- const tabsRes = await vendoredRuntime.call({ action: 'tabs' });- const tabs = (tabsRes.data as { tabs?: Array<{ targetId?: string; suggestedTargetId?: string }> } | undefined)- ?.tabs;- const first = Array.isArray(tabs) ? tabs[0] : undefined;- const targetId = first?.suggestedTargetId ?? first?.targetId;- if (tabsRes.ok && targetId) {- await vendoredRuntime.call({ action: 'focus', targetId });+ throw new Error(+ started.message === FOREIGN_AGENT_BROWSER_ERROR || started.message?.includes('Another Cindy')+ ? FOREIGN_AGENT_BROWSER_ERROR+ : (started.message ?? `browser start failed (HTTP ${started.status ?? '?'})`),+ );}+ // Occupancy is handled inside start (relocate CDP instead of attaching).+ // Do not re-probe status.running here: vendored `running` means "CDP is+ // reachable", and pid/userDataDir can still be missing or point at a+ // leftover Chrome on 18800 after a successful start of *this* window.+ await raiseAgentBrowserWindow(externalRuntime);}/**diff --git a/apps/desktop/src/main/mcp-integrations/raise-agent-browser-window.ts b/apps/desktop/src/main/mcp-integrations/raise-agent-browser-window.tsnew file mode 100644index 0000000000..1fd1a84047--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/raise-agent-browser-window.ts@@ -0,0 +1,39 @@+import type { BrowserControlRuntime } from '@cindy/browser-control-runtime';++const FOCUS_ATTEMPTS = 10;+const FOCUS_RETRY_MS = 150;++type RuntimeCall = Pick<BrowserControlRuntime, 'call'>;++/**+ * Bring the headed automation Chrome to the front after `start`.+ *+ * `start` already creates Chrome's initial tab. Cold-start `GET /tabs` returns+ * `{ running: false, tabs: [] }` until CDP is reachable, so an empty list is+ * "not ready yet", not "missing window". Opening `about:blank` after the poll+ * races that first tab (MAINTAINING pit #5).+ */+export async function raiseAgentBrowserWindow(+ runtime: RuntimeCall,+ options?: { sleep?: (ms: number) => Promise<void> },+): Promise<void> {+ const sleep = options?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));+ for (let attempt = 0; attempt < FOCUS_ATTEMPTS; attempt += 1) {+ const targetId = await firstTabId(runtime);+ if (targetId) {+ await runtime.call({ action: 'focus', targetId });+ return;+ }+ if (attempt < FOCUS_ATTEMPTS - 1) {+ await sleep(FOCUS_RETRY_MS);+ }+ }+}++export async function firstTabId(runtime: RuntimeCall): Promise<string | undefined> {+ const tabsRes = await runtime.call({ action: 'tabs' });+ const tabs = (tabsRes.data as { tabs?: Array<{ targetId?: string; suggestedTargetId?: string }> } | undefined)+ ?.tabs;+ const first = Array.isArray(tabs) ? tabs[0] : undefined;+ return first?.suggestedTargetId ?? first?.targetId;+}diff --git a/apps/desktop/src/main/utils/ipcValidate.ts b/apps/desktop/src/main/utils/ipcValidate.tsindex 33b2ba0267..60b5ccd25d 100644--- a/apps/desktop/src/main/utils/ipcValidate.ts+++ b/apps/desktop/src/main/utils/ipcValidate.ts@@ -53,6 +53,13 @@ export function requireNullableString(value: unknown, name: string): string | nureturn requireString(value, name);}+export function requireBoolean(value: unknown, name: string): boolean {+ if (typeof value !== 'boolean') {+ throwIpcError('INVALID_PARAMS', `${name} must be a boolean`);+ }+ return value;+}+export function requireEnum<T extends string>(value: unknown,allowed: readonly T[],diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex fad1390f6e..b6c23be5c8 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -5236,6 +5236,7 @@ contextBridge.exposeInMainWorld('electronAPI', {active: 'external' | 'rsb-webview';systemDefault: 'external' | 'rsb-webview';isOverride: boolean;+ useRealProfile: boolean;}> => ipcRenderer.invoke('browser-backend:get-state'),/** Swap the active backend AND persist as user override. */setKind: (kind: 'external' | 'rsb-webview'): Promise<unknown> =>@@ -5248,6 +5249,12 @@ contextBridge.exposeInMainWorld('electronAPI', {/** Force a fresh embedded backend instance and verify the new connection. */recover: (): Promise<BrowserBackendRecoveryResult> =>ipcRenderer.invoke('browser-backend:recover'),+ /** Consent to copy system Chrome/Edge/Brave logins into the agent browser. */+ setUseRealProfile: (enabled: boolean): Promise<unknown> =>+ ipcRenderer.invoke('browser-backend:set-use-real-profile', { enabled }),+ /** Open-only FDA probe. Returns `{ readable }` — never paths or cookie bytes. */+ probeSourceRead: (): Promise<{ readable: boolean }> =>+ ipcRenderer.invoke('browser-backend:probe-source-read'),},// electronAPI.codex.* 已退役 —— auth / agent status / usage 全部走 electronAPI.maker.*(agentKind),diff --git a/apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx b/apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsxindex c1fff55ce7..b323bbbd30 100644--- a/apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx@@ -1,8 +1,9 @@/*** 用户消息中自动识别出的 http(s) URL。*- * 左键遵循“链接打开方式”偏好;Cmd/Ctrl 点击与无会话上下文场景保留- * 系统浏览器 fallback。sidebar-embedded 场景通过可见会话 bucket 打开。+ * 左键遵循“链接打开方式”偏好(外部网页 / 内部网页两套默认);Cmd/Ctrl+ * 点击与无会话上下文场景保留系统浏览器 fallback。sidebar-embedded+ * 场景通过可见会话 bucket 打开。*/import type { MouseEvent } from 'react';diff --git a/apps/desktop/src/renderer/components/chat/__tests__/UserMessageUrlLink.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/UserMessageUrlLink.test.tsxindex c4a616a83b..c9e06c31f4 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/UserMessageUrlLink.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/UserMessageUrlLink.test.tsx@@ -39,16 +39,17 @@ import {import { UserMessageUrlLink } from '../UserMessageUrlLink';const URL = 'https://example.com/path';+const LOCAL_URL = 'http://localhost:3000/app';const openExternal = vi.fn(async (url: string) => {void url;return { success: true };});-function ExternalPreferenceButton() {- const { setPreference } = useLinkOpenPreference();+function WebPreferenceButton({ value }: { value: 'sidebar' | 'external' }) {+ const { setPreference } = useLinkOpenPreference('web');return (- <button type="button" onClick={() => setPreference('external')}>- use external+ <button type="button" onClick={() => setPreference(value)}>+ use {value}</button>);}@@ -64,7 +65,26 @@ describe('UserMessageUrlLink', () => {});});+ it('opens public web URLs in the system browser by default', async () => {+ render(<UserMessageUrlLink url={URL} sessionId="session-a" />);++ fireEvent.click(screen.getByRole('link'));++ await waitFor(() => expect(openExternal).toHaveBeenCalledWith(URL));+ expect(openUrlInSidebarBrowser).not.toHaveBeenCalled();+ });++ it('opens localhost URLs in the current session sidebar by default', async () => {+ render(<UserMessageUrlLink url={LOCAL_URL} sessionId="session-a" />);++ fireEvent.click(screen.getByRole('link'));++ await waitFor(() => expect(openUrlInSidebarBrowser).toHaveBeenCalledWith('session-a', LOCAL_URL));+ expect(openExternal).not.toHaveBeenCalled();+ });+it('opens the URL in the current session sidebar when sidebar is preferred', async () => {+ localStorage.setItem('chat.webLinkOpenPreference', 'sidebar');render(<UserMessageUrlLink url={URL} sessionId="session-a" />);fireEvent.click(screen.getByRole('link'));@@ -74,9 +94,10 @@ describe('UserMessageUrlLink', () => {});it('uses a newly selected external preference without remounting', async () => {+ localStorage.setItem('chat.webLinkOpenPreference', 'sidebar');render(<>- <ExternalPreferenceButton />+ <WebPreferenceButton value="external" /><UserMessageUrlLink url={URL} sessionId="session-a" /></>,);@@ -98,6 +119,7 @@ describe('UserMessageUrlLink', () => {});it('uses the visible session bucket for sidebar-embedded messages', async () => {+ localStorage.setItem('chat.webLinkOpenPreference', 'sidebar');render(<SessionNavigationModeProvider mode="sidebar-embedded" sidebarTargetSessionId="lead-a"><UserMessageUrlLink url={URL} sessionId="worker-a" />@@ -120,6 +142,7 @@ describe('UserMessageUrlLink', () => {});it('keeps Ctrl-click as a temporary external-browser override', async () => {+ localStorage.setItem('chat.webLinkOpenPreference', 'sidebar');render(<UserMessageUrlLink url={URL} sessionId="session-a" />);fireEvent.click(screen.getByRole('link'), { ctrlKey: true });diff --git a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsxindex 8335a30f22..6405f9f920 100644--- a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx+++ b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx@@ -4,6 +4,7 @@* 消息流里 http(s) 链接的**右键**「打开方式」菜单:在侧边栏浏览器中打开 /* 在默认浏览器中打开。左键不再弹菜单——由 openUrlByPreference /* openHtmlFileByPreference 按用户偏好(设置 → 个性化 → 链接打开方式)直开。+ * 外部网页与内部网页(本地 HTML / localhost)是两套默认,互不影响。** html 文件 chip 的右键不走本 hook——它们已有 useFileChipContextMenu* (复制 / 路径 / 目录 / 浏览器查看),「侧边栏打开 / 查看源文件」以可选项@@ -34,7 +35,10 @@ import {openUrlInSidebarBrowser,pathToFileUrl,} from '@/features/right-sidebar/lib/openInSidebarBrowser';-import { getLinkOpenPreference } from '@/hooks/useLinkOpenPreference';+import {+ getLinkOpenPreference,+ getLinkOpenPreferenceForUrl,+} from '@/hooks/useLinkOpenPreference';import { useSidebarTargetSessionId } from '@/features/cc-agent/embeddedSessionNavigation';/** 左键"按偏好直开"只对浏览器"作为页面渲染"有意义的 html 家族生效;其余本地@@ -54,13 +58,13 @@ async function openInSidebar(sessionId: string, url: string, t: TFunction): Prom}}-/** http(s) 链接左键:按用户偏好直开(sidebar → 内置新页签;external → 系统浏览器)。 */+/** http(s) / file 链接左键:按 URL 属于外部网页还是内部网页选对应偏好直开。 */export async function openUrlByPreference(sessionId: string,url: string,t: TFunction,): Promise<void> {- if (getLinkOpenPreference() === 'sidebar') {+ if (getLinkOpenPreferenceForUrl(url) === 'sidebar') {await openInSidebar(sessionId, url, t);return;}@@ -68,13 +72,13 @@ export async function openUrlByPreference(if (!res.success) toast.error(t('chat.markdownRenderer.openLinkFailed'));}-/** 本地 html 文件左键:按用户偏好直开(sidebar → file:// 进内置;external → 系统浏览器)。 */+/** 本地 html 文件左键:走内部网页偏好(sidebar → file:// 进内置;external → 系统浏览器)。 */export async function openHtmlFileByPreference(sessionId: string,absPath: string,t: TFunction,): Promise<void> {- if (getLinkOpenPreference() === 'sidebar') {+ if (getLinkOpenPreference('local') === 'sidebar') {await openInSidebar(sessionId, pathToFileUrl(absPath), t);return;}diff --git a/apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx b/apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsxnew file mode 100644index 0000000000..394609dbf5--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx@@ -0,0 +1,51 @@+/**+ * Consent switch for copying the user's Chromium logins into the agent browser.+ * Only meaningful for the standalone external backend.+ */++import { useTranslation } from 'react-i18next';++import { Switch } from '@/components/ui/switch';+import { cn } from '@/lib/utils';++interface BrowserRealProfileSubsectionProps {+ enabled: boolean;+ pending: boolean;+ available: boolean;+ onToggle: (enabled: boolean) => void;+}++export function BrowserRealProfileSubsection({+ enabled,+ pending,+ available,+ onToggle,+}: BrowserRealProfileSubsectionProps) {+ const { t } = useTranslation();+ // Embedded backend cannot copy logins, but an already-on switch must stay+ // revocable so the Cindy-real copy can still be deleted.+ const disabled = pending || (!available && !enabled);+ return (+ <div className="border-t border-[var(--settings-theme-card-border)]">+ <div className="flex items-start justify-between gap-3 px-4 py-[14px]">+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <p className="text-12 font-medium leading-[1.4] text-[var(--settings-section-title)]">+ {t('settings.computerUse.realProfile.title')}+ </p>+ <p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">+ {available+ ? t('settings.computerUse.realProfile.description')+ : t('settings.computerUse.realProfile.unavailableEmbedded')}+ </p>+ </div>+ <Switch+ checked={enabled}+ disabled={disabled}+ onCheckedChange={onToggle}+ aria-label={t('settings.computerUse.realProfile.toggleAria')}+ className={cn('mt-0.5 shrink-0', !available && !enabled && 'opacity-50')}+ />+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsxindex c0888e9819..a56b117c48 100644--- a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx@@ -35,6 +35,7 @@ import screenRecordingPermissionIcon from '@/assets/system-settings/screen-recorimport { toast } from '@/lib/toast';import { Switch } from '@/components/ui/switch';import { Spinner } from '@/components/ui/spinner';+import { useOptionalConfirmDialog } from '@/components/ui/confirm-dialog-provider';import {DropdownMenu,DropdownMenuContent,@@ -43,7 +44,12 @@ import {} from '@/components/ui/dropdown-menu';import { createLogger } from '@/lib/logger';import { BrowserBackendSubsection } from './BrowserBackendSubsection';-import type { BrowserBackendHealth } from '../../../shared/browserBackend';+import { BrowserRealProfileSubsection } from './BrowserRealProfileSubsection';+import {+ FOREIGN_AGENT_BROWSER_ERROR,+ REAL_PROFILE_READ_DENIED,+ type BrowserBackendHealth,+} from '../../../shared/browserBackend';import {androidDeviceLabel,androidStatusFallback,@@ -56,6 +62,10 @@ import {isComputerPermissionReady,shouldStartComputerPermissionGuide,} from './computerPermissionFlow';+import {+ confirmEnableRealProfile,+ guideFullDiskAccessAfterReadDenied,+} from './realProfilePermissionGuide';const log = createLogger('ComputerUseSection');@@ -410,6 +420,9 @@ export function ComputerUseSection({const [browserBackendPending, setBrowserBackendPending] = useState(false);const [browserBackendRecovering, setBrowserBackendRecovering] = useState(false);const [browserBackendHealth, setBrowserBackendHealth] = useState<BrowserBackendHealth | null>(null);+ const [useRealProfile, setUseRealProfile] = useState(false);+ const [useRealProfilePending, setUseRealProfilePending] = useState(false);+ const confirmDialog = useOptionalConfirmDialog();// Health can include an automatic embedded-browser recovery and therefore// take several seconds. Track the latest health owner so a late initial// probe cannot overwrite a newer user-initiated switch or recovery result.@@ -557,6 +570,7 @@ export function ComputerUseSection({// 让卡片整张瘫成内置态强。const activeBackend = backendState?.active ?? 'external';setBrowserBackendKind(activeBackend);+ setUseRealProfile(backendState?.useRealProfile === true);const { health: backendHealth, error: backendHealthError } = await backendHealthPromise;if (cancelled || browserBackendHealthSeqRef.current !== backendHealthSeq) return;setBrowserBackendHealth(@@ -608,6 +622,49 @@ export function ComputerUseSection({[browserBackendKind, browserBackendPending, t],);+ const handleToggleRealProfile = useCallback(+ async (next: boolean) => {+ if (useRealProfilePending) return;+ if (next) {+ const confirmed = await confirmEnableRealProfile({+ platform: window.electronAPI.platform,+ t,+ confirm: confirmDialog?.confirm,+ openExternal: window.electronAPI.openExternal,+ onOpenSettingsFailed: (result) => {+ log.warn('open Full Disk Access settings failed', result);+ },+ hasDiskAccess: async () => {+ try {+ const result = await window.electronAPI.browserBackend.probeSourceRead?.();+ return result?.readable === true;+ } catch (error) {+ log.warn('browserBackend.probeSourceRead failed', error);+ return false;+ }+ },+ });+ if (!confirmed) return;+ }+ setUseRealProfilePending(true);+ try {+ const res = await window.electronAPI.browserBackend.setUseRealProfile(next);+ setUseRealProfile(res.enabled);+ toast.success(+ res.enabled+ ? t('settings.computerUse.realProfile.toast.enabled')+ : t('settings.computerUse.realProfile.toast.disabled'),+ );+ } catch (err) {+ log.error('browserBackend.setUseRealProfile failed', err);+ toast.error(t('settings.computerUse.realProfile.toast.failed'));+ } finally {+ setUseRealProfilePending(false);+ }+ },+ [confirmDialog, t, useRealProfilePending],+ );+const handleRecoverBrowserBackend = useCallback(async () => {if (browserBackendPending || browserBackendRecovering) return;setBrowserBackendRecovering(true);@@ -812,10 +869,13 @@ export function ComputerUseSection({const handleToggleBrowser = useCallback(async (next: boolean) => {- if (!workingDir) return;setTogglePending(true);try {- await window.electronAPI.maker.plugins.setProjectEnabled(workingDir, BROWSER_PLUGIN_ID, next);+ if (workingDir) {+ await window.electronAPI.maker.plugins.setProjectEnabled(workingDir, BROWSER_PLUGIN_ID, next);+ } else {+ await window.electronAPI.maker.plugins.setEnabled(BROWSER_PLUGIN_ID, next);+ }setBrowserEnabled(next);toast.success(next@@ -823,7 +883,7 @@ export function ComputerUseSection({: t('settings.computerUse.browser.toast.disabled'),);} catch (err) {- log.warn('setProjectEnabled(browser) failed', err);+ log.warn('set browser plugin enabled failed', err);toast.error(t('settings.computerUse.browser.toast.toggleFailed'));} finally {setTogglePending(false);@@ -1057,9 +1117,29 @@ export function ComputerUseSection({toast.success(t('settings.computerUse.browser.toast.openedForLogin'));} catch (err) {log.warn('browser.openForLogin failed', err);+ const message = err instanceof Error ? err.message : String(err);+ if (message.includes(FOREIGN_AGENT_BROWSER_ERROR)) {+ toast.error(t('settings.computerUse.browser.toast.foreignInstance'));+ return;+ }+ if (message.includes(REAL_PROFILE_READ_DENIED)) {+ if (!confirmDialog) {+ toast.error(t('settings.computerUse.realProfile.readDeniedDescription'));+ }+ await guideFullDiskAccessAfterReadDenied({+ platform: window.electronAPI.platform,+ t,+ confirm: confirmDialog?.confirm,+ openExternal: window.electronAPI.openExternal,+ onOpenSettingsFailed: (result) => {+ log.warn('open Full Disk Access settings failed', result);+ },+ });+ return;+ }toast.error(t('settings.computerUse.browser.toast.openForLoginFailed'));}- }, [t]);+ }, [confirmDialog, t]);const handleOpenComputerPermission = useCallback(async (url: string, granted: boolean) => {@@ -1277,7 +1357,7 @@ export function ComputerUseSection({</div><Switchchecked={browserEnabled}- disabled={togglePending || !workingDir}+ disabled={togglePending}onCheckedChange={handleToggleBrowser}aria-label={t('settings.computerUse.browser.toggleAria')}/>@@ -1295,6 +1375,14 @@ export function ComputerUseSection({onRecover={() => void handleRecoverBrowserBackend()}/>) : null}+ {browserBackendKind !== null ? (+ <BrowserRealProfileSubsection+ enabled={useRealProfile}+ pending={useRealProfilePending}+ available={browserBackendKind === 'external'}+ onToggle={(next) => void handleToggleRealProfile(next)}+ />+ ) : null}{/* 只在 backend === 'external' 时展示 Chrome 探测 + 登录入口。内置 webviewbackend 用 Electron 自带 Chromium,这些 UI 对它都没有意义。 */}{browserBackendKind === 'external' ? (@@ -1310,7 +1398,6 @@ export function ComputerUseSection({<buttontype="button"onClick={handleOpenForLogin}- disabled={!browserEnabled}className={ACTION_BUTTON_CLASS}><LogIn size={12} className="shrink-0" />@@ -1332,9 +1419,7 @@ export function ComputerUseSection({</p>) : null}<p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">- {workingDir- ? t('settings.computerUse.browser.toggleHint')- : t('settings.computerUse.browser.noProjectHint')}+ {t('settings.computerUse.browser.toggleHint')}</p><div aria-hidden="true" className="h-px bg-[var(--settings-theme-card-border)]" />diff --git a/apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx b/apps/desktop/src/renderer/components/settings/LinkOpenSection.tsxindex d5ec9cc3dc..1705ab863f 100644--- a/apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx+++ b/apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx@@ -1,13 +1,16 @@/*** LinkOpenSection — Settings → 个性化 下的「链接打开方式」偏好。*- * 控制消息流里左键点击 http(s) 链接 / HTML 文件时的默认打开位置:- * - 内置侧边栏浏览器(系统默认)- * - 系统默认浏览器+ * 控制消息流里左键点击时的默认打开位置,拆成两个互不影响的开关:+ * - 外部网页:互联网链接。默认系统默认浏览器。+ * - 内部网页:本地硬盘 HTML 与本机地址(localhost)。默认内置侧边栏浏览器。* 右键菜单里始终两种都可临时选,本设置只决定左键直开走哪个。** 存储走 useLinkOpenPreference(localStorage 只存 override,选回默认即清除,- * 规则 20);「恢复默认」按钮复用 DefaultOverrideControls。+ * 规则 20);每个开关各自「恢复默认」,复用 DefaultOverrideControls。+ *+ * 版式跟 AgentResourceSection 同一套多行卡:一张卡、两行、控件贴右,+ * 避免两张独立卡把分段控件单独占一整行。*/import { useCallback } from 'react';@@ -16,7 +19,9 @@ import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';import { toast } from '@/lib/toast';import {+ LINK_OPEN_DEFAULTS,useLinkOpenPreference,+ type LinkOpenKind,type LinkOpenPreference,} from '@/hooks/useLinkOpenPreference';import { DefaultOverrideControls } from './DefaultOverrideControls';@@ -26,43 +31,42 @@ const OPTIONS: Array<{ value: LinkOpenPreference; labelKey: string }> = [{ value: 'external', labelKey: 'settings.linkOpen.options.external' },];-export function LinkOpenSection() {+/** 带分割线的多行卡片:卡片自身不留内边距,由每行 `px-4 py-4` 承担。 */+const CARD_CLASS = cn(+ 'flex flex-col rounded-xl',+ 'bg-[var(--settings-theme-card-bg)]',+ 'border border-[var(--settings-theme-card-border)]',+);+const ROW_CLASS = 'flex items-center justify-between gap-3 px-4 py-4';+const ROW_LABEL_CLASS = 'text-13 font-medium text-[var(--settings-section-sublabel)]';+const ROW_HINT_CLASS = 'text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70';+const DIVIDER_CLASS = 'mx-4 h-px bg-[var(--settings-theme-card-border)]';++function LinkOpenPreferenceRow({ kind }: { kind: LinkOpenKind }) {const { t } = useTranslation();- const { preference, isCustomized, setPreference } = useLinkOpenPreference();+ const { preference, isCustomized, setPreference } = useLinkOpenPreference(kind);const onReset = useCallback(() => {- setPreference('sidebar');+ setPreference(LINK_OPEN_DEFAULTS[kind]);toast.success(t('settings.defaults.restored'));- }, [setPreference, t]);+ }, [kind, setPreference, t]);return (- <div className="flex flex-col gap-[14px]">- <div className="flex flex-col gap-1">- <h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">- {t('settings.linkOpen.title')}- </h2>- <p className="text-13 leading-[1.5] text-[var(--settings-section-desc)]">- {t('settings.linkOpen.description')}+ <div className={ROW_CLASS}>+ <div className="flex min-w-0 flex-col gap-1">+ <p className={ROW_LABEL_CLASS} style={{ letterSpacing: '0.12px' }}>+ {t(`settings.linkOpen.${kind}.label`)}</p>+ <p className={ROW_HINT_CLASS}>{t(`settings.linkOpen.${kind}.description`)}</p></div>- <div className="flex flex-col gap-[14px] rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] p-4">- <div className="flex items-center justify-between gap-3">- <p className="text-14 font-medium leading-none text-[var(--text-primary)]">- {t('settings.linkOpen.card.label')}- </p>- <DefaultOverrideControls isCustomized={isCustomized} onReset={onReset} />- </div>-- <p className="text-12 leading-[1.5] text-[var(--text-secondary)]">- {t('settings.linkOpen.card.description')}- </p>-+ <div className="flex shrink-0 items-center gap-2">+ <DefaultOverrideControls isCustomized={isCustomized} onReset={onReset} />{/* 分段控件的 token 与外观分区「侧边栏卡片模式」完全同款(docs/design-rules/cindy-design-system.md 复用原则):选中态 chip 底 + 正文字色,未选中态次级字色 + hover 项底。 */}<divrole="radiogroup"- aria-label={t('settings.linkOpen.card.ariaLabel')}+ aria-label={t(`settings.linkOpen.${kind}.ariaLabel`)}className="flex w-fit shrink-0 items-center gap-0.5 rounded-full border border-[var(--settings-theme-card-border)] p-0.5">{OPTIONS.map((opt) => {@@ -90,3 +94,26 @@ export function LinkOpenSection() {</div>);}++export function LinkOpenSection() {+ const { t } = useTranslation();++ return (+ <div className="flex flex-col gap-[14px]">+ <div className="flex flex-col gap-1">+ <h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">+ {t('settings.linkOpen.title')}+ </h2>+ <p className="text-12 leading-[1.45] text-[var(--settings-section-desc)]">+ {t('settings.linkOpen.description')}+ </p>+ </div>++ <div className={CARD_CLASS}>+ <LinkOpenPreferenceRow kind="web" />+ <div className={DIVIDER_CLASS} />+ <LinkOpenPreferenceRow kind="local" />+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/__tests__/BrowserRealProfileSubsection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/BrowserRealProfileSubsection.test.tsxnew file mode 100644index 0000000000..4371318b2b--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/BrowserRealProfileSubsection.test.tsx@@ -0,0 +1,82 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/components/ui/switch', () => ({+ Switch: ({+ checked,+ disabled,+ onCheckedChange,+ 'aria-label': ariaLabel,+ }: {+ checked: boolean;+ disabled: boolean;+ onCheckedChange: (next: boolean) => void;+ 'aria-label': string;+ }) => (+ <button+ type="button"+ role="switch"+ aria-checked={checked}+ aria-label={ariaLabel}+ disabled={disabled}+ onClick={() => onCheckedChange(!checked)}+ />+ ),+}));++import { BrowserRealProfileSubsection } from '../BrowserRealProfileSubsection';++afterEach(cleanup);++describe('BrowserRealProfileSubsection', () => {+ it('explains that the sidebar backend cannot use copied logins', () => {+ render(+ <BrowserRealProfileSubsection+ enabled={false}+ pending={false}+ available={false}+ onToggle={vi.fn()}+ />,+ );+ expect(+ screen.getByText('settings.computerUse.realProfile.unavailableEmbedded'),+ ).toBeTruthy();+ expect(screen.getByRole('switch')).toHaveProperty('disabled', true);+ });++ it('lets the user turn the switch off when the embedded backend is active', () => {+ const onToggle = vi.fn();+ render(+ <BrowserRealProfileSubsection+ enabled+ pending={false}+ available={false}+ onToggle={onToggle}+ />,+ );+ const toggle = screen.getByRole('switch');+ expect(toggle).toHaveProperty('disabled', false);+ fireEvent.click(toggle);+ expect(onToggle).toHaveBeenCalledWith(false);+ });++ it('toggles on when the external backend is active', () => {+ const onToggle = vi.fn();+ render(+ <BrowserRealProfileSubsection+ enabled={false}+ pending={false}+ available+ onToggle={onToggle}+ />,+ );+ fireEvent.click(screen.getByRole('switch'));+ expect(onToggle).toHaveBeenCalledWith(true);+ });+});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 45b2029f03..ea48199ddf 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@@ -111,6 +111,7 @@ beforeEach(() => {getHealth: api.getBackendHealth,setKind: api.setBackendKind,recover: api.recoverBackend,+ setUseRealProfile: vi.fn(async (enabled: boolean) => ({ ok: true, enabled })),},},});diff --git a/apps/desktop/src/renderer/components/settings/__tests__/realProfilePermissionGuide.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/realProfilePermissionGuide.test.tsnew file mode 100644index 0000000000..2c3ca4dabc--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/realProfilePermissionGuide.test.ts@@ -0,0 +1,167 @@+import { describe, expect, it, vi } from 'vitest';++import {+ MAC_FULL_DISK_ACCESS_SETTINGS_URL,+ confirmEnableRealProfile,+ guideFullDiskAccessAfterReadDenied,+ realProfileEnableConfirmOptions,+ realProfileEnableDescriptionKey,+} from '../realProfilePermissionGuide';++const t = (key: string) => key;++describe('realProfilePermissionGuide', () => {+ it('names Full Disk Access in the first-enable confirm on macOS', () => {+ expect(realProfileEnableDescriptionKey('darwin')).toBe(+ 'settings.computerUse.realProfile.confirmDescriptionMac',+ );+ expect(realProfileEnableConfirmOptions('darwin', t).description).toBe(+ 'settings.computerUse.realProfile.confirmDescriptionMac',+ );+ });++ it('keeps the generic first-enable confirm off macOS', () => {+ expect(realProfileEnableDescriptionKey('win32')).toBe(+ 'settings.computerUse.realProfile.confirmDescription',+ );+ });++ it('opens Full Disk Access only after the dedicated action on macOS', async () => {+ const openExternal = vi.fn().mockResolvedValue({ success: true });+ const confirm = vi+ .fn()+ .mockResolvedValueOnce(true)+ .mockImplementationOnce(async (opts) => {+ expect(opts).toEqual(+ expect.objectContaining({+ title: 'settings.computerUse.realProfile.readDeniedTitle',+ confirmText: 'settings.computerUse.realProfile.openFullDiskAccess',+ }),+ );+ expect(openExternal).not.toHaveBeenCalled();+ return true;+ });+ await expect(+ confirmEnableRealProfile({+ platform: 'darwin',+ t,+ confirm,+ openExternal,+ }),+ ).resolves.toBe(true);+ expect(confirm).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ description: 'settings.computerUse.realProfile.confirmDescriptionMac',+ }),+ );+ expect(openExternal).toHaveBeenCalledTimes(1);+ expect(openExternal).toHaveBeenCalledWith(MAC_FULL_DISK_ACCESS_SETTINGS_URL);+ });++ it('does not open System Settings when the user cancels enable', async () => {+ const openExternal = vi.fn();+ await expect(+ confirmEnableRealProfile({+ platform: 'darwin',+ t,+ confirm: vi.fn().mockResolvedValue(false),+ openExternal,+ }),+ ).resolves.toBe(false);+ expect(openExternal).not.toHaveBeenCalled();+ });++ it('does not open Full Disk Access when enabling on other platforms', async () => {+ const openExternal = vi.fn();+ await expect(+ confirmEnableRealProfile({+ platform: 'linux',+ t,+ confirm: vi.fn().mockResolvedValue(true),+ openExternal,+ }),+ ).resolves.toBe(true);+ expect(openExternal).not.toHaveBeenCalled();+ });++ it('skips the Full Disk Access prompt when the source profile is already readable', async () => {+ const openExternal = vi.fn();+ const confirm = vi.fn().mockResolvedValue(true);+ await expect(+ confirmEnableRealProfile({+ platform: 'darwin',+ t,+ confirm,+ openExternal,+ hasDiskAccess: async () => true,+ }),+ ).resolves.toBe(true);+ expect(confirm).toHaveBeenCalledTimes(1);+ expect(confirm).toHaveBeenCalledWith(+ expect.objectContaining({+ description: 'settings.computerUse.realProfile.confirmDescriptionMac',+ }),+ );+ expect(openExternal).not.toHaveBeenCalled();+ });++ it('still shows Full Disk Access when the probe says not readable', async () => {+ const openExternal = vi.fn().mockResolvedValue({ success: true });+ const confirm = vi.fn().mockResolvedValue(true);+ await confirmEnableRealProfile({+ platform: 'darwin',+ t,+ confirm,+ openExternal,+ hasDiskAccess: async () => false,+ });+ expect(confirm).toHaveBeenCalledTimes(2);+ expect(confirm).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ title: 'settings.computerUse.realProfile.readDeniedTitle',+ }),+ );+ expect(openExternal).toHaveBeenCalledWith(MAC_FULL_DISK_ACCESS_SETTINGS_URL);+ });++ it('shows Full Disk Access when the probe throws', async () => {+ const openExternal = vi.fn().mockResolvedValue({ success: true });+ const confirm = vi.fn().mockResolvedValue(true);+ await confirmEnableRealProfile({+ platform: 'darwin',+ t,+ confirm,+ openExternal,+ hasDiskAccess: async () => {+ throw new Error('ipc down');+ },+ });+ expect(confirm).toHaveBeenCalledTimes(2);+ expect(openExternal).toHaveBeenCalledTimes(1);+ });++ it('does not open System Settings before the dedicated action', async () => {+ const openExternal = vi.fn().mockResolvedValue({ success: true });+ await guideFullDiskAccessAfterReadDenied({+ platform: 'darwin',+ t,+ confirm: vi.fn().mockResolvedValue(false),+ openExternal,+ });+ expect(openExternal).not.toHaveBeenCalled();+ });++ it('opens Full Disk Access when the user chooses the dedicated action', async () => {+ const openExternal = vi.fn().mockResolvedValue({ success: true });+ await guideFullDiskAccessAfterReadDenied({+ platform: 'darwin',+ t,+ confirm: vi.fn().mockResolvedValue(true),+ openExternal,+ });+ expect(openExternal).toHaveBeenCalledTimes(1);+ expect(openExternal).toHaveBeenCalledWith(MAC_FULL_DISK_ACCESS_SETTINGS_URL);+ });+});diff --git a/apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts b/apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.tsnew file mode 100644index 0000000000..2c341e505d--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts@@ -0,0 +1,97 @@+import type { ConfirmOptions } from '@/components/ui/confirm-dialog-provider';++export const MAC_FULL_DISK_ACCESS_SETTINGS_URL =+ 'x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles';++export const REAL_PROFILE_CONFIRM_TITLE_KEY = 'settings.computerUse.realProfile.confirmTitle';+export const REAL_PROFILE_CONFIRM_DESCRIPTION_KEY =+ 'settings.computerUse.realProfile.confirmDescription';+export const REAL_PROFILE_CONFIRM_DESCRIPTION_MAC_KEY =+ 'settings.computerUse.realProfile.confirmDescriptionMac';+export const REAL_PROFILE_CONFIRM_ACTION_KEY = 'settings.computerUse.realProfile.confirm';++type Translate = (key: string) => string;++type OpenExternal = (url: string) => Promise<{ success: boolean }>;++export function isMacFullDiskAccessPlatform(platform: string | undefined): boolean {+ return platform === 'darwin';+}++export function realProfileEnableDescriptionKey(+ platform: string | undefined,+): typeof REAL_PROFILE_CONFIRM_DESCRIPTION_MAC_KEY | typeof REAL_PROFILE_CONFIRM_DESCRIPTION_KEY {+ return isMacFullDiskAccessPlatform(platform)+ ? REAL_PROFILE_CONFIRM_DESCRIPTION_MAC_KEY+ : REAL_PROFILE_CONFIRM_DESCRIPTION_KEY;+}++export function realProfileEnableConfirmOptions(+ platform: string | undefined,+ t: Translate,+): ConfirmOptions {+ return {+ title: t(REAL_PROFILE_CONFIRM_TITLE_KEY),+ description: t(realProfileEnableDescriptionKey(platform)),+ confirmText: t(REAL_PROFILE_CONFIRM_ACTION_KEY),+ confirmVariant: 'destructive',+ };+}++export async function openMacFullDiskAccessSettings(+ openExternal: OpenExternal,+): Promise<boolean> {+ const opened = await openExternal(MAC_FULL_DISK_ACCESS_SETTINGS_URL);+ return opened.success === true;+}++/**+ * First-enable consent. On macOS the copy names Full Disk Access; the+ * System Settings pane opens only after the dedicated follow-up action,+ * and only if a source-profile probe says we cannot read it yet.+ */+export async function confirmEnableRealProfile(options: {+ platform: string | undefined;+ t: Translate;+ confirm?: (opts: ConfirmOptions) => Promise<boolean>;+ openExternal: OpenExternal;+ onOpenSettingsFailed?: (result: unknown) => void;+ hasDiskAccess?: () => Promise<boolean>;+}): Promise<boolean> {+ const confirmed = options.confirm+ ? await options.confirm(realProfileEnableConfirmOptions(options.platform, options.t))+ : true;+ if (!confirmed) return false;+ if (isMacFullDiskAccessPlatform(options.platform)) {+ const granted = options.hasDiskAccess+ ? await options.hasDiskAccess().catch(() => false)+ : false;+ if (!granted) {+ await guideFullDiskAccessAfterReadDenied(options);+ }+ }+ return true;+}++/** Fail-closed recovery when a later snapshot hits TCC. */+export async function guideFullDiskAccessAfterReadDenied(options: {+ platform: string | undefined;+ t: Translate;+ confirm?: (opts: ConfirmOptions) => Promise<boolean>;+ openExternal: OpenExternal;+ onOpenSettingsFailed?: (result: unknown) => void;+}): Promise<void> {+ const isMac = isMacFullDiskAccessPlatform(options.platform);+ const confirmed = options.confirm+ ? await options.confirm({+ title: options.t('settings.computerUse.realProfile.readDeniedTitle'),+ description: options.t('settings.computerUse.realProfile.readDeniedDescription'),+ confirmText: options.t('settings.computerUse.realProfile.openFullDiskAccess'),+ cancelText: options.t('settings.computerUse.realProfile.readDeniedLater'),+ autoFocusConfirm: true,+ })+ : true;+ if (!confirmed || !isMac) return;+ const opened = await openMacFullDiskAccessSettings(options.openExternal);+ if (!opened) options.onOpenSettingsFailed?.({ success: false });+}diff --git a/apps/desktop/src/renderer/hooks/__tests__/useLinkOpenPreference.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useLinkOpenPreference.test.tsindex cae83b20d4..b023124b2d 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useLinkOpenPreference.test.ts+++ b/apps/desktop/src/renderer/hooks/__tests__/useLinkOpenPreference.test.ts@@ -2,8 +2,9 @@/*** useLinkOpenPreference — 覆盖 override 语义(规则 20):- * - 默认 'sidebar';localStorage 只存 override- * - 选 'external' → 写入;选回 'sidebar' → 删除 key(清 override)+ * - web 默认 'external';local 默认 'sidebar';localStorage 只存 override+ * - 选回该开关默认 → 删除对应 key+ * - 旧统一 key 按"是否自定义"一次性迁到新开关* - 非法存储值回落默认*/@@ -13,10 +14,32 @@ import { act, renderHook } from '@testing-library/react';import {_resetLinkOpenPreferenceForTests,getLinkOpenPreference,+ getLinkOpenPreferenceForUrl,+ isLocalOpenUrl,useLinkOpenPreference,} from '../useLinkOpenPreference';-const KEY = 'chat.linkOpenPreference';+const LEGACY_KEY = 'chat.linkOpenPreference';+const WEB_KEY = 'chat.webLinkOpenPreference';+const LOCAL_KEY = 'chat.localLinkOpenPreference';++describe('isLocalOpenUrl', () => {+ it.each([+ ['https://example.com/path', false],+ ['http://192.168.1.8/admin', false],+ ['http://10.0.0.1/', false],+ ['http://localhost.example.com/', false],+ ['not a url', false],+ ['file:///tmp/report.html', true],+ ['http://localhost:3000/app', true],+ ['https://127.0.0.1:5173/', true],+ ['http://127.0.0.2/', true],+ ['http://[::1]/', true],+ ['http://foo.localhost/dev', true],+ ])('%s → %s', (url, expected) => {+ expect(isLocalOpenUrl(url)).toBe(expected);+ });+});describe('useLinkOpenPreference', () => {beforeEach(() => {@@ -24,34 +47,96 @@ describe('useLinkOpenPreference', () => {_resetLinkOpenPreferenceForTests();});- it('defaults to sidebar with no stored override', () => {- expect(getLinkOpenPreference()).toBe('sidebar');- const { result } = renderHook(() => useLinkOpenPreference());- expect(result.current.preference).toBe('sidebar');- expect(result.current.isCustomized).toBe(false);+ it('defaults web to external and local to sidebar with no stored override', () => {+ expect(getLinkOpenPreference('web')).toBe('external');+ expect(getLinkOpenPreference('local')).toBe('sidebar');+ const web = renderHook(() => useLinkOpenPreference('web'));+ const local = renderHook(() => useLinkOpenPreference('local'));+ expect(web.result.current.preference).toBe('external');+ expect(web.result.current.isCustomized).toBe(false);+ expect(local.result.current.preference).toBe('sidebar');+ expect(local.result.current.isCustomized).toBe(false);});- it('reads a stored external override', () => {- localStorage.setItem(KEY, 'external');- expect(getLinkOpenPreference()).toBe('external');- const { result } = renderHook(() => useLinkOpenPreference());+ it('reads a stored web sidebar override without touching local', () => {+ localStorage.setItem(WEB_KEY, 'sidebar');+ expect(getLinkOpenPreference('web')).toBe('sidebar');+ expect(getLinkOpenPreference('local')).toBe('sidebar');+ const { result } = renderHook(() => useLinkOpenPreference('web'));expect(result.current.isCustomized).toBe(true);+ expect(localStorage.getItem(LOCAL_KEY)).toBeNull();+ });++ it('falls back to each kind default on garbage stored value', () => {+ localStorage.setItem(WEB_KEY, 'whatever');+ localStorage.setItem(LOCAL_KEY, 'whatever');+ expect(getLinkOpenPreference('web')).toBe('external');+ expect(getLinkOpenPreference('local')).toBe('sidebar');});- it('falls back to default on garbage stored value', () => {- localStorage.setItem(KEY, 'whatever');- expect(getLinkOpenPreference()).toBe('sidebar');+ it('setting web to sidebar persists; setting back to external removes the key', () => {+ const { result } = renderHook(() => useLinkOpenPreference('web'));+ act(() => result.current.setPreference('sidebar'));+ expect(localStorage.getItem(WEB_KEY)).toBe('sidebar');+ expect(getLinkOpenPreference('web')).toBe('sidebar');++ act(() => result.current.setPreference('external'));+ expect(localStorage.getItem(WEB_KEY)).toBeNull();+ expect(getLinkOpenPreference('web')).toBe('external');+ expect(result.current.isCustomized).toBe(false);});- it('setting external persists override; setting back to sidebar removes the key', () => {- const { result } = renderHook(() => useLinkOpenPreference());+ it('setting local to external persists; setting back to sidebar removes the key', () => {+ const { result } = renderHook(() => useLinkOpenPreference('local'));act(() => result.current.setPreference('external'));- expect(localStorage.getItem(KEY)).toBe('external');- expect(getLinkOpenPreference()).toBe('external');+ expect(localStorage.getItem(LOCAL_KEY)).toBe('external');+ expect(getLinkOpenPreference('local')).toBe('external');act(() => result.current.setPreference('sidebar'));- expect(localStorage.getItem(KEY)).toBeNull();- expect(getLinkOpenPreference()).toBe('sidebar');+ expect(localStorage.getItem(LOCAL_KEY)).toBeNull();+ expect(getLinkOpenPreference('local')).toBe('sidebar');expect(result.current.isCustomized).toBe(false);});++ it('clears a stored value that equals the new default', () => {+ localStorage.setItem(WEB_KEY, 'external');+ expect(getLinkOpenPreference('web')).toBe('external');+ expect(localStorage.getItem(WEB_KEY)).toBeNull();+ });++ it('migrates a legacy external override onto local only', () => {+ localStorage.setItem(LEGACY_KEY, 'external');+ expect(getLinkOpenPreference('web')).toBe('external');+ expect(getLinkOpenPreference('local')).toBe('external');+ expect(localStorage.getItem(LEGACY_KEY)).toBeNull();+ expect(localStorage.getItem(WEB_KEY)).toBeNull();+ expect(localStorage.getItem(LOCAL_KEY)).toBe('external');+ });++ it('migrates a legacy sidebar override onto web only', () => {+ localStorage.setItem(LEGACY_KEY, 'sidebar');+ expect(getLinkOpenPreference('web')).toBe('sidebar');+ expect(getLinkOpenPreference('local')).toBe('sidebar');+ expect(localStorage.getItem(LEGACY_KEY)).toBeNull();+ expect(localStorage.getItem(WEB_KEY)).toBe('sidebar');+ expect(localStorage.getItem(LOCAL_KEY)).toBeNull();+ });++ it('does not overwrite an already-split custom key while dropping the legacy key', () => {+ localStorage.setItem(LEGACY_KEY, 'sidebar');+ localStorage.setItem(LOCAL_KEY, 'external');+ expect(getLinkOpenPreference('local')).toBe('external');+ expect(getLinkOpenPreference('web')).toBe('sidebar');+ expect(localStorage.getItem(LEGACY_KEY)).toBeNull();+ expect(localStorage.getItem(LOCAL_KEY)).toBe('external');+ expect(localStorage.getItem(WEB_KEY)).toBe('sidebar');+ });++ it('picks the matching preference for a URL', () => {+ localStorage.setItem(WEB_KEY, 'sidebar');+ localStorage.setItem(LOCAL_KEY, 'external');+ expect(getLinkOpenPreferenceForUrl('https://example.com')).toBe('sidebar');+ expect(getLinkOpenPreferenceForUrl('http://localhost:3000')).toBe('external');+ expect(getLinkOpenPreferenceForUrl('file:///tmp/a.html')).toBe('external');+ });});diff --git a/apps/desktop/src/renderer/hooks/useLinkOpenPreference.ts b/apps/desktop/src/renderer/hooks/useLinkOpenPreference.tsindex 7e1eae2e2f..1342169e1d 100644--- a/apps/desktop/src/renderer/hooks/useLinkOpenPreference.ts+++ b/apps/desktop/src/renderer/hooks/useLinkOpenPreference.ts@@ -1,91 +1,188 @@/**- * useLinkOpenPreference — 消息流链接 / HTML 文件左键的"默认打开方式"偏好。+ * useLinkOpenPreference — 消息流左键的"默认打开方式"偏好。* ---------------------------------------------------------------------------- * 两态:- * - 'sidebar' 内置侧边栏浏览器(系统默认值)。- * - 'external' 系统默认浏览器。+ * 拆成两个互不影响的开关(设置 → 个性化 → 链接打开方式):+ * - web 外部网页。默认 'external'(系统默认浏览器)。+ * - local 内部网页:本地硬盘 HTML 与本机地址(localhost / loopback)。+ * 默认 'sidebar'(内置侧边栏浏览器)。*- * 规则 20(配置默认值 vs override)落法:localStorage 只存 override——- * 用户选回 'sidebar'(= 当前系统默认)时**删除** key 而不是写入,这样未自定义- * 的用户未来能自动跟随新版本默认值;isCustomized 即 "存在 override"。+ * 规则 20:localStorage 只存 override。选回该开关当前系统默认时**删除**+ * 对应 key,未自定义的用户跟随新版本默认值;isCustomized 即"存在 override"。*- * 模块级内存值做跨实例 SoT + `storage` 事件跨窗口同步,模式与- * useSidebarCardMode 完全一致(localStorage 写失败时切换不静默回跳)。- * 消息流点击 handler 走同步读 getLinkOpenPreference(),不需要订阅重渲。+ * 旧单 key `chat.linkOpenPreference` 的一次性迁移基于"是否自定义":+ * key 仍在 = 用户对旧统一开关做过选择。把该显式选择写到新开关上**仅当**+ * 它不同于新默认;等于新默认的不落盘。不根据旧值猜测意图。+ *+ * 模块级内存 SoT + `storage` 事件跨窗口同步。消息流点击 handler 走同步读+ * getLinkOpenPreference / getLinkOpenPreferenceForUrl,不需要订阅重渲。*/import { useCallback, useEffect, useState } from 'react';export type LinkOpenPreference = 'sidebar' | 'external';+export type LinkOpenKind = 'web' | 'local';++const LEGACY_STORAGE_KEY = 'chat.linkOpenPreference';++const STORAGE_KEYS: Record<LinkOpenKind, string> = {+ web: 'chat.webLinkOpenPreference',+ local: 'chat.localLinkOpenPreference',+};-const STORAGE_KEY = 'chat.linkOpenPreference';-const DEFAULT_PREFERENCE: LinkOpenPreference = 'sidebar';+export const LINK_OPEN_DEFAULTS: Record<LinkOpenKind, LinkOpenPreference> = {+ web: 'external',+ local: 'sidebar',+};function parsePreference(raw: string | null): LinkOpenPreference | null {return raw === 'sidebar' || raw === 'external' ? raw : null;}+function hostnameOf(url: URL): string {+ return url.hostname.replace(/^\[|\]$/g, '').replace(/\.$/, '').toLowerCase();+}++function isIPv4Loopback(host: string): boolean {+ const match = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);+ if (!match) return false;+ return match.slice(1).every((octet) => Number(octet) <= 255);+}++/** 本地硬盘(file:)或本机 loopback(localhost / 127/8 / ::1)。不含局域网地址。 */+export function isLocalOpenUrl(url: string): boolean {+ try {+ const parsed = new URL(url);+ if (parsed.protocol === 'file:') return true;+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;+ const host = hostnameOf(parsed);+ if (host === 'localhost' || host.endsWith('.localhost')) return true;+ if (host === '::1') return true;+ return isIPv4Loopback(host);+ } catch {+ return false;+ }+}+/** 模块级内存 SoT;null = 尚未被本窗口读定/写定。 */-let memoryValue: LinkOpenPreference | null = null;+const memoryValue: Record<LinkOpenKind, LinkOpenPreference | null> = {+ web: null,+ local: null,+};++let legacyMigrated = false;++function migrateLegacyIfNeeded(): void {+ if (legacyMigrated) return;+ legacyMigrated = true;+ try {+ const legacy = parsePreference(localStorage.getItem(LEGACY_STORAGE_KEY));+ if (!legacy) return;+ (['web', 'local'] as const).forEach((kind) => {+ if (localStorage.getItem(STORAGE_KEYS[kind])) return;+ if (legacy !== LINK_OPEN_DEFAULTS[kind]) {+ localStorage.setItem(STORAGE_KEYS[kind], legacy);+ }+ });+ localStorage.removeItem(LEGACY_STORAGE_KEY);+ } catch {+ // localStorage 不可用——保持新默认,不落定内存。+ }+}++function clearDefaultOverride(kind: LinkOpenKind): void {+ try {+ localStorage.removeItem(STORAGE_KEYS[kind]);+ } catch {+ // localStorage 不可用——保留内存中的默认值即可。+ }+}/** 同步读——给消息流点击 handler 等非 hook 路径用。 */-export function getLinkOpenPreference(): LinkOpenPreference {- if (memoryValue !== null) return memoryValue;+export function getLinkOpenPreference(kind: LinkOpenKind): LinkOpenPreference {+ migrateLegacyIfNeeded();+ if (memoryValue[kind] !== null) return memoryValue[kind];try {- const parsed = parsePreference(localStorage.getItem(STORAGE_KEY));- if (parsed) return (memoryValue = parsed);+ const parsed = parsePreference(localStorage.getItem(STORAGE_KEYS[kind]));+ if (parsed === LINK_OPEN_DEFAULTS[kind]) {+ // 清掉误写入的默认值,避免阻断未来默认值迁移。+ clearDefaultOverride(kind);+ return (memoryValue[kind] = parsed);+ }+ if (parsed) return (memoryValue[kind] = parsed);} catch {// localStorage 不可用——退回默认(不落定内存,留待后续写入)。}- return DEFAULT_PREFERENCE;+ return LINK_OPEN_DEFAULTS[kind];+}++export function getLinkOpenPreferenceForUrl(url: string): LinkOpenPreference {+ return getLinkOpenPreference(isLocalOpenUrl(url) ? 'local' : 'web');}const listeners = new Set<() => void>();-export function useLinkOpenPreference(): {+function notifyListeners(): void {+ listeners.forEach((fn) => fn());+}++export function useLinkOpenPreference(kind: LinkOpenKind): {preference: LinkOpenPreference;- /** 是否存在用户 override(≠ 系统默认)。设置页据此显示「恢复默认」。 */+ /** 是否存在用户 override(≠ 该开关当前系统默认)。设置页据此显示「恢复默认」。 */isCustomized: boolean;setPreference: (next: LinkOpenPreference) => void;} {- const [preference, setState] = useState<LinkOpenPreference>(getLinkOpenPreference);-- const setPreference = useCallback((next: LinkOpenPreference) => {- memoryValue = next;- setState(next);- try {- if (next === DEFAULT_PREFERENCE) {- // 选回默认 = 清除 override(而非写入默认值快照)。- localStorage.removeItem(STORAGE_KEY);- } else {- localStorage.setItem(STORAGE_KEY, next);+ const [preference, setState] = useState<LinkOpenPreference>(() => getLinkOpenPreference(kind));++ const setPreference = useCallback(+ (next: LinkOpenPreference) => {+ memoryValue[kind] = next;+ setState(next);+ try {+ if (next === LINK_OPEN_DEFAULTS[kind]) {+ localStorage.removeItem(STORAGE_KEYS[kind]);+ } else {+ localStorage.setItem(STORAGE_KEYS[kind], next);+ }+ } catch {+ // localStorage 不可用——内存 SoT 已生效;仅跨窗口同步缺失。}- } catch {- // localStorage 不可用——内存 SoT 已生效;仅跨窗口同步缺失。- }- listeners.forEach((fn) => fn());- }, []);+ notifyListeners();+ },+ [kind],+ );useEffect(() => {- const sync = () => setState(getLinkOpenPreference());+ const sync = () => setState(getLinkOpenPreference(kind));listeners.add(sync);const onStorage = (e: StorageEvent) => {- if (e.key !== STORAGE_KEY) return;- memoryValue = parsePreference(e.newValue) ?? DEFAULT_PREFERENCE;- sync();+ if (e.key === STORAGE_KEYS.web) {+ memoryValue.web = parsePreference(e.newValue) ?? LINK_OPEN_DEFAULTS.web;+ notifyListeners();+ return;+ }+ if (e.key === STORAGE_KEYS.local) {+ memoryValue.local = parsePreference(e.newValue) ?? LINK_OPEN_DEFAULTS.local;+ notifyListeners();+ }};window.addEventListener('storage', onStorage);return () => {listeners.delete(sync);window.removeEventListener('storage', onStorage);};- }, []);+ }, [kind]);- return { preference, isCustomized: preference !== DEFAULT_PREFERENCE, setPreference };+ return {+ preference,+ isCustomized: preference !== LINK_OPEN_DEFAULTS[kind],+ setPreference,+ };}/** 测试专用:清空内存 SoT,让下一次读回落 localStorage / 默认值。 */export function _resetLinkOpenPreferenceForTests(): void {- memoryValue = null;+ memoryValue.web = null;+ memoryValue.local = null;+ legacyMigrated = false;listeners.clear();}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7395c7b904..61b826b7d6 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2770,11 +2770,16 @@},"linkOpen": {"title": "Link open behavior",- "description": "Where web links and HTML files in messages open on left click.",- "card": {- "label": "Default open target",- "description": "Right-click a link anytime to pick the other option for a single open.",- "ariaLabel": "Select default link open target"+ "description": "Where message links open on left click. Right-click still lets you pick the other option once.",+ "web": {+ "label": "Web pages",+ "description": "Links on the public internet.",+ "ariaLabel": "Choose where web pages open"+ },+ "local": {+ "label": "Local pages",+ "description": "HTML files on this computer, and localhost addresses.",+ "ariaLabel": "Choose where local pages open"},"options": {"sidebar": "Sidebar browser",@@ -2975,11 +2980,31 @@"disabled": "Browser automation disabled","toggleFailed": "Failed to toggle browser automation","openedForLogin": "Automation browser opened — sign into the sites you need",- "openForLoginFailed": "Failed to open the browser"+ "openForLoginFailed": "Failed to open the browser",+ "foreignInstance": "Another Cindy window is already using the agent browser. Quit the other instance and try again."},"openForLogin": "Open agent browser","openForLoginHint": "This is a dedicated browser for agents: it runs on your installed Chrome but with a separate profile (shown as “Cindy”), so it never touches your everyday Chrome's tabs, bookmarks, or logins. Agents open pages, read, click, and take screenshots here on your behalf. For sites that need a login, click “Open agent browser” above and sign in once — your session is kept, so the agent can keep acting as you afterward."},+ "realProfile": {+ "title": "Use my browser logins",+ "description": "The agent will open sites with your signed-in Chrome, Edge, or Brave accounts.",+ "toggleAria": "Use my browser logins",+ "unavailableEmbedded": "Only available with the standalone external browser. The sidebar browser cannot load Chrome’s login files.",+ "confirmTitle": "Let the agent use your browser logins?",+ "confirmDescription": "The agent will be able to open sites with your signed-in accounts, including email, cloud drives, and work consoles. You can turn it off anytime; the copy will be deleted.",+ "confirmDescriptionMac": "The agent will be able to open sites with your signed-in accounts, including email, cloud drives, and work consoles. Reading Chrome’s login files also needs Full Disk Access. You can turn this off anytime; the copy will be deleted.",+ "confirm": "Use my logins",+ "readDeniedTitle": "Full Disk Access Needed",+ "readDeniedDescription": "Cindy needs this permission to read Chrome’s login files. Turn on Cindy under Privacy & Security → Full Disk Access, then try again.",+ "openFullDiskAccess": "Open System Settings",+ "readDeniedLater": "Not Now",+ "toast": {+ "enabled": "Agent browser will use your Chrome logins",+ "disabled": "Copied logins removed. Agent browser is isolated again.",+ "failed": "Failed to update browser login setting"+ }+ },"browserBackend": {"title": "Automation browser target","description": "Pick which browser the agent actually drives during automation. Login state is independent between the two modes.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2ff6bca91d..d22cfa5ef9 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2769,11 +2769,16 @@},"linkOpen": {"title": "リンクの開き方",- "description": "メッセージ内のリンクや HTML ファイルを左クリックしたときの既定の開き先です。",- "card": {- "label": "既定の開き先",- "description": "リンクを右クリックすると、その場でもう一方の開き方を選べます。",- "ariaLabel": "リンクの既定の開き先を選択"+ "description": "メッセージ内のウェブやローカルのリンクを左クリックしたときの既定の開き先です。右クリックでその場でもう一方も選べます。",+ "web": {+ "label": "外部ウェブ",+ "description": "インターネット上のウェブページです。",+ "ariaLabel": "外部ウェブの既定の開き先を選択"+ },+ "local": {+ "label": "内部ウェブ",+ "description": "このコンピュータ上の HTML ファイルと、localhost アドレスです。",+ "ariaLabel": "内部ウェブの既定の開き先を選択"},"options": {"sidebar": "サイドバーブラウザ",@@ -2974,11 +2979,31 @@"disabled": "ブラウザ自動操作を無効にしました","toggleFailed": "ブラウザ自動操作の切り替えに失敗しました","openedForLogin": "自動操作ブラウザを開きました。必要なサイトにログインしてください",- "openForLoginFailed": "ブラウザを開けませんでした"+ "openForLoginFailed": "ブラウザを開けませんでした",+ "foreignInstance": "別の Cindy が Agent 専用ブラウザを使用中です。先にそのウィンドウを終了してください。"},"openForLogin": "Agent 専用ブラウザを開く","openForLoginHint": "これはエージェント専用の独立したブラウザです。お使いの Chrome を利用しますが、プロファイルは完全に独立しており(右上に「Cindy」と表示)、普段の Chrome のタブ・ブックマーク・ログイン状態には一切影響しません。エージェントはこのブラウザであなたの代わりにページを開き、読み、クリックし、スクリーンショットを撮ります。ログインが必要なサイトは、上の「Agent 専用ブラウザを開く」から一度ログインすれば、ログイン状態が保持され、以降はエージェントがあなたとして操作を続けられます。"},+ "realProfile": {+ "title": "ブラウザのログイン状態を使う",+ "description": "Chrome、Edge、Brave でログイン済みのアカウントとしてサイトを開きます。",+ "toggleAria": "ブラウザのログイン状態を使う",+ "unavailableEmbedded": "スタンドアロンの外部ブラウザでのみ利用できます。サイドバーの内蔵ブラウザは Chrome のログインファイルを読めません。",+ "confirmTitle": "Agent にブラウザのログイン状態を使わせますか?",+ "confirmDescription": "Agent はメール、クラウド、社内コンソールなど、すでにログインしているサイトであなたとして操作できます。いつでもオフにでき、コピーは削除されます。",+ "confirmDescriptionMac": "Agent はメール、クラウド、社内コンソールなど、すでにログインしているサイトであなたとして操作できます。Chrome のログインファイルを読むには「フルディスクアクセス」も必要です。いつでもオフにでき、コピーは削除されます。",+ "confirm": "ログイン状態を使う",+ "readDeniedTitle": "フルディスクアクセスが必要です",+ "readDeniedDescription": "Chrome のログインファイルを読むには、システムが Cindy を許可する必要があります。「プライバシーとセキュリティ → フルディスクアクセス」で Cindy をオンにしてから、もう一度お試しください。",+ "openFullDiskAccess": "システム設定を開く",+ "readDeniedLater": "あとで",+ "toast": {+ "enabled": "Agent 専用ブラウザが Chrome のログイン状態を使います",+ "disabled": "コピーしたログインを削除し、隔離された Agent ブラウザに戻しました",+ "failed": "ブラウザのログイン設定を更新できませんでした"+ }+ },"browserBackend": {"title": "自動操作のブラウザ対象","description": "エージェントが実際に操作するブラウザを選択します。ログイン状態は 2 つのモード間で独立しています。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 7d996d8ea9..21a960174b 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2769,11 +2769,16 @@},"linkOpen": {"title": "링크 열기 방식",- "description": "메시지의 링크나 HTML 파일을 왼쪽 클릭했을 때 기본으로 여는 위치입니다.",- "card": {- "label": "기본 열기 위치",- "description": "링크를 마우스 오른쪽 버튼으로 클릭하면 언제든 다른 방식을 선택할 수 있습니다.",- "ariaLabel": "링크 기본 열기 위치 선택"+ "description": "메시지에서 웹이나 로컬 링크를 왼쪽 클릭했을 때 기본으로 여는 위치입니다. 오른쪽 클릭으로 다른 방식도 고를 수 있습니다.",+ "web": {+ "label": "외부 웹페이지",+ "description": "인터넷상의 웹 링크입니다.",+ "ariaLabel": "외부 웹페이지 기본 열기 위치 선택"+ },+ "local": {+ "label": "내부 웹페이지",+ "description": "이 컴퓨터의 HTML 파일과 localhost 주소입니다.",+ "ariaLabel": "내부 웹페이지 기본 열기 위치 선택"},"options": {"sidebar": "내장 사이드바 브라우저",@@ -2974,11 +2979,31 @@"disabled": "브라우저 자동화 비활성화됨","toggleFailed": "브라우저 자동화 전환 실패","openedForLogin": "자동화 브라우저를 열었습니다. 필요한 사이트에 로그인하세요",- "openForLoginFailed": "브라우저를 열지 못했습니다"+ "openForLoginFailed": "브라우저를 열지 못했습니다",+ "foreignInstance": "다른 Cindy 창이 이미 Agent 전용 브라우저를 사용 중입니다. 그 창을 종료한 뒤 다시 시도하세요."},"openForLogin": "Agent 전용 브라우저 열기","openForLoginHint": "에이전트 전용 독립 브라우저입니다. 설치된 Chrome을 사용하지만 프로필이 완전히 분리되어 있어(오른쪽 위에 “Cindy”로 표시) 평소 Chrome의 탭·북마크·로그인 상태에 전혀 영향을 주지 않습니다. 에이전트가 이 브라우저에서 사용자를 대신해 페이지를 열고 읽고 클릭하고 스크린샷을 찍습니다. 로그인이 필요한 사이트는 위의 “Agent 전용 브라우저 열기”에서 한 번 로그인하면 로그인 상태가 유지되어, 이후 에이전트가 사용자 명의로 계속 작업할 수 있습니다."},+ "realProfile": {+ "title": "내 브라우저 로그인 사용",+ "description": "Chrome, Edge, Brave에 로그인한 계정으로 사이트에 접근합니다.",+ "toggleAria": "내 브라우저 로그인 사용",+ "unavailableEmbedded": "독립 외부 브라우저에서만 사용할 수 있습니다. 사이드바 내장 브라우저는 Chrome 로그인 파일을 읽지 못합니다.",+ "confirmTitle": "Agent가 브라우저 로그인을 사용하도록 할까요?",+ "confirmDescription": "Agent가 이메일, 클라우드, 업무 콘솔 등 이미 로그인한 사이트에서 사용자 계정으로 동작할 수 있습니다. 언제든 끌 수 있으며 복사본은 삭제됩니다.",+ "confirmDescriptionMac": "Agent가 이메일, 클라우드, 업무 콘솔 등 이미 로그인한 사이트에서 사용자 계정으로 동작할 수 있습니다. Chrome 로그인 파일을 읽으려면 ‘전체 디스크 접근 권한’도 필요합니다. 언제든 끌 수 있으며, 복사본은 삭제됩니다.",+ "confirm": "내 로그인 사용",+ "readDeniedTitle": "전체 디스크 접근 권한이 필요합니다",+ "readDeniedDescription": "Chrome 로그인 파일을 읽으려면 시스템이 Cindy를 허용해야 합니다. 개인 정보 보호 및 보안 → 전체 디스크 접근 권한에서 Cindy를 켠 다음 다시 시도하세요.",+ "openFullDiskAccess": "시스템 설정 열기",+ "readDeniedLater": "나중에",+ "toast": {+ "enabled": "Agent 전용 브라우저가 Chrome 로그인을 사용합니다",+ "disabled": "복사한 로그인을 삭제했고 Agent 브라우저는 다시 격리됩니다",+ "failed": "브라우저 로그인 설정을 바꾸지 못했습니다"+ }+ },"browserBackend": {"title": "자동화 브라우저 대상","description": "에이전트가 실제로 제어할 브라우저를 선택합니다. 두 모드는 로그인 상태가 서로 독립적입니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex b8725cfd7a..7484610d88 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2695,11 +2695,16 @@},"linkOpen": {"title": "链接打开方式",- "description": "消息里左键点击网页链接或 HTML 文件时的默认打开位置。",- "card": {- "label": "默认打开位置",- "description": "右键点击链接可随时临时选择另一种打开方式。",- "ariaLabel": "选择链接默认打开位置"+ "description": "消息里左键点击网页或本机链接时的默认打开位置。右键仍可临时选择另一种方式。",+ "web": {+ "label": "外部网页",+ "description": "互联网上的网页链接。",+ "ariaLabel": "选择外部网页的默认打开位置"+ },+ "local": {+ "label": "内部网页",+ "description": "本地硬盘上的 HTML 文件,以及本机地址(localhost)。",+ "ariaLabel": "选择内部网页的默认打开位置"},"options": {"sidebar": "内置侧边栏浏览器",@@ -2966,11 +2971,31 @@"disabled": "已禁用浏览器自动化","toggleFailed": "切换浏览器自动化失败","openedForLogin": "已打开自动化浏览器,请在其中登录需要的网站",- "openForLoginFailed": "打开浏览器失败"+ "openForLoginFailed": "打开浏览器失败",+ "foreignInstance": "本机已有另一个 Cindy 占用了 Agent 专用浏览器。请先退出其它 Cindy 窗口再试。"},"openForLogin": "打开 Agent 专用浏览器","openForLoginHint": "这是 Agent 专用的独立浏览器:基于你本机的 Chrome,但用一份独立配置(右上角显示为 Cindy),不会动你日常 Chrome 的标签页、书签和登录态。Agent 会在这里替你打开网页、阅读内容、点击和截图。需要登录的网站,点上面「打开 Agent 专用浏览器」手动登录一次即可——登录态会长期保留,之后 Agent 就能以你的身份继续操作。"},+ "realProfile": {+ "title": "使用我的浏览器登录态",+ "description": "Agent 会用你在 Chrome、Edge 或 Brave 里已登录的身份访问网站。",+ "toggleAria": "使用我的浏览器登录态",+ "unavailableEmbedded": "仅独立外置浏览器可用。侧边栏内置浏览器无法读取 Chrome 的登录文件。",+ "confirmTitle": "允许 Agent 使用你的浏览器登录态?",+ "confirmDescription": "Agent 将能以你已登录的身份打开网页,包括邮箱、网盘和公司后台。可以随时关掉,拷贝会被删除。",+ "confirmDescriptionMac": "Agent 将能以你已登录的身份打开网页,包括邮箱、网盘和公司后台。读取 Chrome 登录文件还需要「完全磁盘访问权限」。可以随时关掉,拷贝会被删除。",+ "confirm": "使用我的登录态",+ "readDeniedTitle": "需要完全磁盘访问权限",+ "readDeniedDescription": "读取 Chrome 登录文件需要系统允许 Cindy。请在「隐私与安全性 → 完全磁盘访问权限」中打开 Cindy,然后回到这里再试。",+ "openFullDiskAccess": "打开系统设置",+ "readDeniedLater": "稍后再说",+ "toast": {+ "enabled": "Agent 专用浏览器将使用你的 Chrome 登录态",+ "disabled": "已删除拷贝的登录态,Agent 浏览器恢复为隔离身份",+ "failed": "更新浏览器登录态设置失败"+ }+ },"browserBackend": {"title": "浏览器自动化目标","description": "选择 Agent 自动化操作时实际控制哪个浏览器。两种模式登录态相互独立。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex ad93c1dc9b..48273a12ea 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -2695,11 +2695,16 @@},"linkOpen": {"title": "連結開啟方式",- "description": "訊息裡左鍵點選網頁連結或 HTML 檔案時的預設開啟位置。",- "card": {- "label": "預設開啟位置",- "description": "右鍵點選連結可隨時臨時選擇另一種開啟方式。",- "ariaLabel": "選擇連結預設開啟位置"+ "description": "訊息裡左鍵點選網頁或本機連結時的預設開啟位置。右鍵仍可臨時選擇另一種方式。",+ "web": {+ "label": "外部網頁",+ "description": "網際網路上的網頁連結。",+ "ariaLabel": "選擇外部網頁的預設開啟位置"+ },+ "local": {+ "label": "內部網頁",+ "description": "本機硬碟上的 HTML 檔案,以及本機位址(localhost)。",+ "ariaLabel": "選擇內部網頁的預設開啟位置"},"options": {"sidebar": "內建側邊欄瀏覽器",@@ -2966,11 +2971,31 @@"disabled": "已停用瀏覽器自動化","toggleFailed": "切換瀏覽器自動化失敗","openedForLogin": "已開啟自動化瀏覽器,請在其中登入需要的網站",- "openForLoginFailed": "開啟瀏覽器失敗"+ "openForLoginFailed": "開啟瀏覽器失敗",+ "foreignInstance": "本機已有另一個 Cindy 占用了 Agent 專用瀏覽器。請先退出其它 Cindy 視窗再試。"},"openForLogin": "開啟 Agent 專用瀏覽器","openForLoginHint": "這是 Agent 專用的獨立瀏覽器:基於你本機的 Chrome,但用一份獨立配置(右上角顯示為 Cindy),不會動你日常 Chrome 的標籤頁、書籤和登入態。Agent 會在這裡替你開啟網頁、閱讀內容、點選和截圖。需要登入的網站,點上面「開啟 Agent 專用瀏覽器」手動登入一次即可——登入態會長期保留,之後 Agent 就能以你的身份繼續操作。"},+ "realProfile": {+ "title": "使用我的瀏覽器登入態",+ "description": "Agent 會用你在 Chrome、Edge 或 Brave 裡已登入的身分造訪網站。",+ "toggleAria": "使用我的瀏覽器登入態",+ "unavailableEmbedded": "僅獨立外置瀏覽器可用。側邊欄內建瀏覽器無法讀取 Chrome 的登入檔。",+ "confirmTitle": "允許 Agent 使用你的瀏覽器登入態?",+ "confirmDescription": "Agent 將能以你已登入的身分開啟網頁,包括信箱、雲端硬碟和公司後台。可以隨時關掉,拷貝會被刪除。",+ "confirmDescriptionMac": "Agent 將能以你已登入的身分開啟網頁,包括信箱、雲端硬碟和公司後台。讀取 Chrome 登入檔還需要「完全磁碟存取權」。可以隨時關掉,拷貝會被刪除。",+ "confirm": "使用我的登入態",+ "readDeniedTitle": "需要完全磁碟存取權",+ "readDeniedDescription": "讀取 Chrome 登入檔需要系統允許 Cindy。請在「隱私權與安全性 → 完全磁碟存取權」中打開 Cindy,然後回到這裡再試。",+ "openFullDiskAccess": "打開系統設定",+ "readDeniedLater": "稍後再說",+ "toast": {+ "enabled": "Agent 專用瀏覽器將使用你的 Chrome 登入態",+ "disabled": "已刪除拷貝的登入態,Agent 瀏覽器恢復為隔離身分",+ "failed": "更新瀏覽器登入態設定失敗"+ }+ },"browserBackend": {"title": "瀏覽器自動化目標","description": "選擇 Agent 自動化操作時實際控制哪個瀏覽器。兩種模式登入態相互獨立。",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex de19fc55b3..d58770e914 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -54,6 +54,7 @@ type ProviderRoutingPayload = import('@cindy/model-providers').Provider['routingtype MakerSessionTreeSnapshot = import('@cindy/maker-core').SessionTreeSnapshot;type BrowserBackendHealth = import('../shared/browserBackend').BrowserBackendHealth;type BrowserBackendRecoveryResult = import('../shared/browserBackend').BrowserBackendRecoveryResult;+type BrowserBackendSourceReadAccess = import('../shared/browserBackend').BrowserBackendSourceReadAccess;type DesktopAccountDeletionConfirmInput =import('../shared/authIpc').DesktopAccountDeletionConfirmInput;type DesktopAccountDeletionAvailabilityResult =@@ -4724,6 +4725,7 @@ interface ElectronAPI {active: 'external' | 'rsb-webview';systemDefault: 'external' | 'rsb-webview';isOverride: boolean;+ useRealProfile: boolean;}>;setKind: (kind: 'external' | 'rsb-webview') => Promise<{ok: true;@@ -4732,6 +4734,8 @@ interface ElectronAPI {reset: () => Promise<{ ok: true; active: 'external' | 'rsb-webview' }>;getHealth: () => Promise<BrowserBackendHealth>;recover: () => Promise<BrowserBackendRecoveryResult>;+ setUseRealProfile: (enabled: boolean) => Promise<{ ok: true; enabled: boolean }>;+ probeSourceRead: () => Promise<BrowserBackendSourceReadAccess>;};// ── Dialog(v0.6 新增) ────────────────────────────────────────────────────diff --git a/apps/desktop/src/shared/browserBackend.ts b/apps/desktop/src/shared/browserBackend.tsindex b0b3975ebd..01bd7db446 100644--- a/apps/desktop/src/shared/browserBackend.ts+++ b/apps/desktop/src/shared/browserBackend.ts@@ -1,5 +1,11 @@export type BrowserBackendKind = 'external' | 'rsb-webview';+/** Thrown when start/open would attach to another Cindy instance's Chrome on CDP 18800. */+export const FOREIGN_AGENT_BROWSER_ERROR = 'FOREIGN_AGENT_BROWSER';++/** Thrown when macOS TCC / file permissions block reading the system Chrome profile. */+export const REAL_PROFILE_READ_DENIED = 'REAL_PROFILE_READ_DENIED';+export type BrowserBackendHealthReason =| 'disposing'| 'host-unavailable'@@ -19,3 +25,8 @@ export interface BrowserBackendRecoveryResult {ok: boolean;health: BrowserBackendHealth;}++/** Whether the OS Chromium profile can be opened. Never includes paths. */+export interface BrowserBackendSourceReadAccess {+ readable: boolean;+}diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex a5ef946c37..73911db677 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -369,6 +369,10 @@ macOS TCC 的 kTCCServiceListenEvent(系统设置里叫「输入监控」)在 Ci客户端日志上报后返回给用户的短标识, 用户报障时口述给我们。zh-CN 取「编号」而不是「码」——它是一次上报的检索标识, 不是验证码或错误码, 「上传码」容易被读成验证码。proposed: 日志上报是新链路, 等实际排障流程跑一段后再固化。+### Use my browser logins++设置 → 自动操作里,把系统 Chrome / Edge / Brave 当前 profile 的 cookie 与保存的密码快照到 Agent 专用浏览器。不是接管日常窗口。不要译成 real profile / 真实配置文件。+### Vision Bridge让纯文本模型获得看图能力的能力名:把图片交给外部多模态后端转成文字描述,再喂给文本模型。zh-CN 取「视觉桥」而非「视觉桥梁/图像转文字」——「桥」强调其桥接定位,且与英文 Vision Bridge 一一对应。设置页 visionBridge 分节、docs/vision-bridge-design.md、日志 note 使用。先登记为 proposed,待产品术语评审后固化。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 12758275b2..0a107a5a1b 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -25,6 +25,18 @@},"note": "Cindy AI 个人账号的免费会员身份标签。只在服务端明确下发 accountTier=free 时显示;paid、not_applicable 与未知状态不显示标签。"},+ {+ "id": "use-my-browser-logins",+ "status": "proposed",+ "en": "Use my browser logins",+ "translations": {+ "zh-CN": "使用我的浏览器登录态",+ "zh-TW": "使用我的瀏覽器登入態",+ "ja": "ブラウザのログイン状態を使う",+ "ko": "내 브라우저 로그인 사용"+ },+ "note": "设置 → 自动操作里,把系统 Chrome / Edge / Brave 当前 profile 的 cookie 与保存的密码快照到 Agent 专用浏览器。不是接管日常窗口。不要译成 real profile / 真实配置文件。"+ },{"id": "harness","status": "proposed",diff --git a/packages/browser-control-runtime/package.json b/packages/browser-control-runtime/package.jsonindex 4ef5281e8e..f4695a75d6 100644--- a/packages/browser-control-runtime/package.json+++ b/packages/browser-control-runtime/package.json@@ -8,6 +8,7 @@"types": "./src/index.ts","exports": {".": "./src/index.ts",+ "./config-dir": "./src/shim/_local/text-utils.ts","./ssrf-runtime": "./src/shim/ssrf-runtime.ts"},"scripts": {diff --git a/packages/browser-control-runtime/src/__tests__/config-dir-refresh.test.ts b/packages/browser-control-runtime/src/__tests__/config-dir-refresh.test.tsnew file mode 100644index 0000000000..74003d5780--- /dev/null+++ b/packages/browser-control-runtime/src/__tests__/config-dir-refresh.test.ts@@ -0,0 +1,25 @@+import os from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';++import * as textUtils from '../shim/_local/text-utils.js';++const originalEnv = process.env.XDT_BROWSER_RUNTIME_DIR;++afterEach(() => {+ if (originalEnv === undefined) {+ delete process.env.XDT_BROWSER_RUNTIME_DIR;+ } else {+ process.env.XDT_BROWSER_RUNTIME_DIR = originalEnv;+ }+ textUtils.refreshBrowserRuntimeConfigDir();+});++describe('refreshBrowserRuntimeConfigDir', () => {+ it('re-reads XDT_BROWSER_RUNTIME_DIR so Chrome launch can pick up a late pin', () => {+ const pinned = path.join(os.tmpdir(), 'cindy-browser-runtime-pin');+ process.env.XDT_BROWSER_RUNTIME_DIR = pinned;+ textUtils.refreshBrowserRuntimeConfigDir();+ expect(textUtils.CONFIG_DIR).toBe(pinned);+ });+});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 6670bcb5d5..29537960de 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@@ -936,9 +936,14 @@ export async function launchOpenClawChrome(fs.mkdirSync(userDataDir, { recursive: true });await ensureOutputDirectory(DEFAULT_DOWNLOAD_DIR);+ // LOCAL PATCH (Cindy, via sync.mjs): Chrome chip follows host displayName+ // when set so the disk key (Cindy-real) never leaks into the profile button.+ const chipName =+ normalizeOptionalString(resolved.profiles[profile.name]?.displayName) ?? profile.name;+const needsDecorate = !isProfileDecorated(userDataDir,- profile.name,+ chipName,(profile.color ?? DEFAULT_OPENCLAW_BROWSER_COLOR).toUpperCase(),DEFAULT_DOWNLOAD_DIR,);@@ -1012,7 +1017,7 @@ export async function launchOpenClawChrome(if (needsDecorate) {try {decorateOpenClawProfile(userDataDir, {- name: profile.name,+ name: chipName,color: profile.color,downloadDir: DEFAULT_DOWNLOAD_DIR,});diff --git a/packages/browser-control-runtime/src/index.ts b/packages/browser-control-runtime/src/index.tsindex f2302d7bb7..dcc1e8033b 100644--- a/packages/browser-control-runtime/src/index.ts+++ b/packages/browser-control-runtime/src/index.ts@@ -24,6 +24,7 @@ export {// default profile between managed and real-Chrome takeover) WITHOUT recreating// the runtime — config reads hot-reload per request inside the dispatcher.export { setBrowserRuntimeConfig as setBrowserControlRuntimeConfig } from './shim/runtime-config-snapshot.js';+export { refreshBrowserRuntimeConfigDir } from './shim/_local/text-utils.js';export { isPublicHttpResourceUrl } from './resource-url-policy.js';// Re-export the effective-config type under a neutral name so host code stays// free of the vendored type's product-specific identifier.diff --git a/packages/browser-control-runtime/src/shim/_local/config-types-browser.ts b/packages/browser-control-runtime/src/shim/_local/config-types-browser.tsindex 375a8ab233..4dd1d3f497 100644--- a/packages/browser-control-runtime/src/shim/_local/config-types-browser.ts+++ b/packages/browser-control-runtime/src/shim/_local/config-types-browser.ts@@ -20,6 +20,11 @@ export type BrowserProfileConfig = {attachOnly?: boolean;/** Profile color (hex). Auto-assigned at creation. */color: string;+ /**+ * Chrome profile-chip label. Optional host extension (not upstream): the map+ * key is still the on-disk folder under `browser/<key>/user-data`.+ */+ displayName?: string;};export type BrowserSnapshotDefaults = {/** Default snapshot mode (applies when mode is not provided). */diff --git a/packages/browser-control-runtime/src/shim/_local/text-utils.ts b/packages/browser-control-runtime/src/shim/_local/text-utils.tsindex 77bbf6627c..10247de098 100644--- a/packages/browser-control-runtime/src/shim/_local/text-utils.ts+++ b/packages/browser-control-runtime/src/shim/_local/text-utils.ts@@ -39,10 +39,24 @@ export function shortenHomePath(input: string): string {return input;}+function defaultBrowserRuntimeConfigDir(): string {+ return path.join(os.homedir(), '.xdt-maker', 'browser-runtime');+}+/*** Scratch/config directory for browser runtime state. Neutral, overridable.* Not tied to any product config layout.+ *+ * Vendored Chrome launch joins this with `browser/<profile>/user-data` at call+ * time. Vite's main bundle `require()`s this module before `index.ts` can pin+ * `XDT_BROWSER_RUNTIME_DIR`, so the value must be refreshable after that pin.*/-export const CONFIG_DIR: string =- process.env.XDT_BROWSER_RUNTIME_DIR?.trim() ||- path.join(os.homedir(), '.xdt-maker', 'browser-runtime');+export function resolveBrowserRuntimeConfigDir(): string {+ return process.env.XDT_BROWSER_RUNTIME_DIR?.trim() || defaultBrowserRuntimeConfigDir();+}++export let CONFIG_DIR: string = resolveBrowserRuntimeConfigDir();++export function refreshBrowserRuntimeConfigDir(): void {+ CONFIG_DIR = resolveBrowserRuntimeConfigDir();+}diff --git a/packages/browser-control-runtime/src/shim/config-contracts.ts b/packages/browser-control-runtime/src/shim/config-contracts.tsindex 5317ba90c6..b0d091ca50 100644--- a/packages/browser-control-runtime/src/shim/config-contracts.ts+++ b/packages/browser-control-runtime/src/shim/config-contracts.ts@@ -1,10 +1,11 @@/*** Shim: openclaw/plugin-sdk/config-contracts.*- * BrowserConfig / BrowserProfileConfig are ported verbatim from upstream- * `config/types.browser.ts` (self-contained type-only). OpenClawConfig is the- * app root config in upstream; the browser core only ever reads its `browser`- * slice, so we model it as a minimal envelope carrying that slice.+ * BrowserConfig / BrowserProfileConfig are ported from upstream+ * `config/types.browser.ts` (self-contained type-only). `displayName` is a+ * host-only extension: the map key stays the on-disk folder. OpenClawConfig is+ * the app root config in upstream; the browser core only ever reads its+ * `browser` slice, so we model it as a minimal envelope carrying that slice.*/export type { BrowserConfig, BrowserProfileConfig } from './_local/config-types-browser.js';import type { BrowserConfig } from './_local/config-types-browser.js';diff --git a/packages/browser-control-runtime/src/shim/media-runtime.ts b/packages/browser-control-runtime/src/shim/media-runtime.tsindex af5e74cd05..579f5507ef 100644--- a/packages/browser-control-runtime/src/shim/media-runtime.ts+++ b/packages/browser-control-runtime/src/shim/media-runtime.ts@@ -77,12 +77,15 @@ export async function resizeToJpeg(params: ResizeToJpegParams): Promise<Buffer>}}-const MEDIA_ROOT = path.join(CONFIG_DIR, 'media');+function mediaRoot(): string {+ return path.join(CONFIG_DIR, 'media');+}/** Ensure the media scratch root exists. */export async function ensureMediaDir(): Promise<string> {- await fs.mkdir(MEDIA_ROOT, { recursive: true, mode: 0o700 });- return MEDIA_ROOT;+ const root = mediaRoot();+ await fs.mkdir(root, { recursive: true, mode: 0o700 });+ return root;}export interface SavedMedia {@@ -109,7 +112,7 @@ export async function saveMediaBuffer(if (buffer.byteLength > maxBytes) {throw new Error(`Media exceeds ${Math.round(maxBytes / (1024 * 1024))}MB limit`);}- const dir = path.join(MEDIA_ROOT, subdir);+ const dir = path.join(mediaRoot(), subdir);await fs.mkdir(dir, { recursive: true, mode: 0o700 });const hash = createHash('sha256').update(buffer).digest('hex').slice(0, 16);const file = path.join(dir, `${hash}.${extForContentType(contentType)}`);diff --git a/packages/browser-control-runtime/src/shim/text-utility-runtime.ts b/packages/browser-control-runtime/src/shim/text-utility-runtime.tsindex 0834f000da..57b26fd301 100644--- a/packages/browser-control-runtime/src/shim/text-utility-runtime.ts+++ b/packages/browser-control-runtime/src/shim/text-utility-runtime.ts@@ -1,2 +1,9 @@// Shim: openclaw/plugin-sdk/text-utility-runtime → self-contained text/path helpers.-export { CONFIG_DIR, escapeRegExp, resolveUserPath, shortenHomePath } from './_local/text-utils.js';+export {+ CONFIG_DIR,+ escapeRegExp,+ refreshBrowserRuntimeConfigDir,+ resolveBrowserRuntimeConfigDir,+ resolveUserPath,+ shortenHomePath,+} from './_local/text-utils.js';diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.mdindex 6b3ae9d39d..09379a2eff 100644--- a/packages/browser-control-runtime/upstream/MAINTAINING.md+++ b/packages/browser-control-runtime/upstream/MAINTAINING.md@@ -9,6 +9,8 @@默认行为:启动**一个专属、持久、headed 的自动化浏览器**(profile 名 "Cindy"),登录态长期保留,与用户日常 Chrome 互不影响。+用户可在设置 → 自动操作打开「使用我的浏览器登录态」(默认关)。打开后,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。+## 2. 三层架构 + 文件清单```@@ -46,13 +48,16 @@ host 在 `browser-managed-config.ts` 用 `buildManagedConfig()` 造出 `{ browse| # | 症状 | 根因 | 铁律 ||---|---|---|---|| 1 | config 不生效 / profile 显示上游默认名 | 见 §3,`getRuntimeConfigSourceSnapshot` 返回了 wrapper | 该 shim 必须返回 `OpenClawConfig \| null` |-| 2 | 数据目录落到 `~/.xdt-maker` 而非 Electron `userData` | `CONFIG_DIR` 是 `shim/_local/text-utils.ts` 里**模块加载即求值**的 const,读 `XDT_BROWSER_RUNTIME_DIR` | 必须在 **import runtime 之前**设好 env——靠 `browser.ts` 顶部 `import './browser-runtime-env.js'` 保持**第一行**,别重排 import(无 import-order autofix) |+| 2 | 数据目录落到 `~/.xdt-maker` 而非 Electron `userData` | Vite 把 `@cindy/browser-control-runtime` `require()` 进 main 入口 chunk 顶部,`CONFIG_DIR` 在 `index.ts` 设置 `XDT_BROWSER_RUNTIME_DIR` **之前**就求值成 `~/.xdt-maker`。从包入口 barrel 引入刷新函数还会提前求值 `paths.ts`,`DEFAULT_INBOUND_MEDIA_DIR` 冻在旧根,随后 `saveMediaBuffer` 写到刷新后的目录、上传校验按旧 inbound root 拒绝 | `index.ts` 在最后一次 `app.setPath('userData')` 之后 pin env,并从 **`@cindy/browser-control-runtime/config-dir`** 调用 `refreshBrowserRuntimeConfigDir()`(不要从包入口 barrel 引入,那会把 generated `paths.ts` 拉进入口 chunk)。单测 `browserRuntimeDirStartup.test.ts` 锁顺序与 import 路径。`browser.ts` 顶部 `import './browser-runtime-env.js'` 仍是 vitest/非打包路径的兜底,别重排 || 3 | `profile must define cdpPort or cdpUrl` | vendored 只给"名叫上游默认名"的 profile 自动分配 CDP 端口;自定义名的托管 profile 不会 | 自定义托管 profile 必须显式给 `cdpPort`(现用 18800,vendored 端口段起点) || 4 | 明明给了中性/白色,Chrome 工具栏却是浑浊蓝绿 | Chrome 把 profile `color` 当 **Material-You 种子色**生成色板,不是字面色;中性/近黑种子被它和成灰蓝 | 用**高饱和**色做种子(现 `#00D9C5` TapTap teal);想要纯灰度做不到(灰度开关在不可改的 vendored decorate 里) |-| 5 | 「打开 Agent 专用浏览器」每次开两个标签页 | `start` 本身已带初始标签页,再 `open` 在冷启动时会和它抢 | `openBrowserForLogin` 只 `start` + 尽力 `focus`,**绝不** `open` |+| 5 | 「打开 Agent 专用浏览器」每次开两个标签页 | `start` 本身已带初始标签页;冷启动 `GET /tabs` 在 CDP 未就绪时返回 empty,再 `open` 就会和 Chrome 自己的第一页抢 | `openBrowserForLogin` 只 `start` + 尽力 `focus`,**绝不** `open`。空 tabs 是「还没连上 CDP」,不是缺窗口 || 6 | profile 没有自定义头像 | Chrome 只认内置头像 / Google 账号头像,不能塞本地图 | 已知限制,接受;别为它改 vendored decorate || 7 | 改了 `browser-workflow.md` 但 agent 还按旧文案 | 这份 md 经 `?raw` 静态打进**进程内** MCP server;且 agent 只在调 `list_tools` 时读 rules | 改完要 **(a) 重启桌面端**(main/package 改动不热更)+ **(b) 开新 agent 会话**(老会话 context 里是旧 rules) || 8 | 远端 Codex 会话里浏览器不可用 | lizi MCP 桥接只对**本地** Codex 生效(见 §7) | 不是 bug;所有 `lizi_*` 工具对远端 Codex 都一样 |+| 9 | 开了「使用我的浏览器登录态」但窗口仍是登出 | 快照把 `last_used` 的 cookie 放进 dest `Default`,却原样拷了 `Local State`;Chrome 按 `last_used` 打开空的 `Profile N` | 写入 dest `Local State` 时必须把 `last_used` / `last_active_profiles` / `profiles_order` 改成 `Default`,`info_cache` 只留 Default(元数据从源 last_used 挪过来),并删掉 dest 里其它 `Profile N` |+| 10 | Chrome 右上角 chip 显示 `Cindy-real` / 源 profile 名 | 磁盘 key 必须是 `Cindy-real`;vendored decorate 默认用 `profile.name`(map key)。host 只改 Local State 不够,下次 launch 会盖回去 | `profiles[Cindy-real].displayName = "Cindy"`;`launchOpenClawChrome` 用 `displayName ?? name` decorate。快照写入时也把 `info_cache.Default.name` 写成 `Cindy` |+| 11 | 已有完全磁盘访问仍弹「需要完全磁盘访问权限」 | 第一次 enable 在 macOS 无条件跑 `guideFullDiskAccessAfterReadDenied` | 同意拷贝之后先 `probeSourceRead`(只 open 源 Local State / Cookies,不拷贝、不回路径);`readable: true` 就跳过。真正快照 `REAL_PROFILE_READ_DENIED` 仍弹。不自动打开系统设置 |## 5. UI 开关模型(设置 →「自动操作」)@@ -81,7 +86,7 @@ pnpm --filter @cindy/browser-control-runtime test # 契约 + SSRF guard```- 版本锁:`upstream/browser-runtime.lock.json`(pinned commit + fs-safe 版本 + content hash)。-- `_generated/**` 整体重生成,**永不手改**;要改行为改 `src/shim/*` 或 `sync.mjs`(vendor 集合 / import 重写)。+- `_generated/**` 整体重生成,**永不手改**;要改行为改 `src/shim/*` 或 `sync.mjs`(vendor 集合 / import 重写 / `LOCAL_PATCHES`)。chip `displayName` 就是这种 LOCAL_PATCH,下次 sync 会按 `sync.mjs` 重新打上。- shim 导出契约在 `upstream/shim-spec.md`;sync 后若多出新的 `openclaw/plugin-sdk/*` import,补对应 shim。- 安全:SSRF / 路径包含的**决策逻辑是 vendored 的**,`src/shim/ssrf-runtime.ts` 只重写了组合这些原语的 fetch 外壳;`ssrf-guard.test.ts` 断言拦截 cloud-metadata / 私网 IP 的"牙齿"还在,削弱会挂 CI。- 同步后回归一遍 §4 的坑(尤其 #1 配置应用、#3 cdpPort),再跑 `runtime-config-application.test.ts` + @cindy/mcps browser 测试 + desktop `browserAvailability` 测试。diff --git a/packages/browser-control-runtime/upstream/browser-runtime.lock.json b/packages/browser-control-runtime/upstream/browser-runtime.lock.jsonindex c4bc636f96..a93dd46826 100644--- a/packages/browser-control-runtime/upstream/browser-runtime.lock.json+++ b/packages/browser-control-runtime/upstream/browser-runtime.lock.json@@ -29,6 +29,14 @@{"file": "extension/src/browser/config.ts","desc": "skip upstream auto-injected \"openclaw\"/\"user\" profiles when the host provides its own (avoids CDP port 18800 collision with the managed profile + never drives the user's Chrome)"+ },+ {+ "file": "extension/src/browser/chrome.ts",+ "desc": "decorate Chrome chip with host displayName so Cindy-real stays disk-only"+ },+ {+ "file": "extension/src/browser/chrome.ts",+ "desc": "pass chipName into decorateOpenClawProfile instead of the disk key"}],"fileCount": 335,diff --git a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.mdindex e838d77fb3..fa35cd2f9a 100644--- a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md+++ b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md@@ -8,9 +8,12 @@- **公开静态页 / JSON API / RSS / 文档**:优先用宿主的网页抓取工具(WebFetch / web_search 类)或 Bash `curl`——无 tab、无登录态依赖、最省 token。**不要**为"读一篇公开文章"开浏览器 tab。- **需要 JS 渲染、页面交互、或站点登录态(已在本浏览器里登录过)**:用本工具。-- **内容依赖用户本人在系统浏览器(Chrome / Safari)里的登录态**(公司内网 SSO、用户私人账号页):本工具的浏览器是**独立环境,拿不到那些登录态**。两条路二选一,如实告诉用户:- 1. 请用户把该 URL 复制到**自己的系统浏览器**打开、自行查看/操作(你无法代看);- 2. 或请用户在本工具的浏览器里**重新登录一次**该站点(登录态此后持久保留),你再继续自动化。+- **内容依赖用户本人在系统浏览器(Chrome / Safari)里的登录态**(公司内网 SSO、用户私人账号页):先 `action: "status"` 看 `data.realProfile`。+ - **`data.realProfile.applied === true`**(外置浏览器已套用用户同意的系统 Chrome / Edge / Brave 登录拷贝):先导航再 snapshot 判断是否已登录。已登录就继续,不要再让用户「在 Cindy 里再登一次」。仍撞登录墙时按下面「登录与登录墙」处理。+ - **未套用**(没有该字段、`applied` 不为 true、或侧边栏模式):本工具拿不到系统浏览器登录态。两条路二选一,如实告诉用户:+ 1. 请用户把该 URL 复制到**自己的系统浏览器**打开、自行查看/操作(你无法代看);+ 2. 或请用户在本工具的浏览器里**重新登录一次**该站点(登录态此后持久保留),你再继续自动化。+ 也可提示用户到**设置 → 自动操作**打开「使用我的浏览器登录态」(仅独立外置浏览器)。**不要**自己去拷 cookie、传 `profile`、或接管用户日常 Chrome。#### 核心操作环@@ -56,11 +59,11 @@宿主用两种后端之一承接本工具,**顶层 action 集合一致**(两边都支持 snapshot / act 各 kind / requests / upload / dialog 等),差别在两处:少数参数级能力只有侧边栏模式有,以及"页面呈现在哪里"。判别依据是 `action: "status"` 返回结果里的 **`data.backend`**(工具结果的外层是 `{ ok, action, status, data }`,`status` 是数字状态码——**别去读 `status.backend`**,那是 undefined):-- **`data.backend === "rsb-webview"` = Cindy 侧边栏内置浏览器(默认)**:页面活在 Cindy 的会话侧边栏里,不是一个常规浏览器窗口。侧边栏本身可能内嵌在主窗口、也可能被用户开成独立子窗口,`status` **不区分**这两种承载方式——所以请用户看页面时说"Cindy 的侧边栏(若你把侧边栏开成了独立窗口,就是那个窗口)",不要断言窗口存在或不存在。+- **`data.backend === "rsb-webview"` = Cindy 侧边栏内置浏览器**:页面活在 Cindy 的会话侧边栏里,不是一个常规浏览器窗口。侧边栏本身可能内嵌在主窗口、也可能被用户开成独立子窗口,`status` **不区分**这两种承载方式——所以请用户看页面时说"Cindy 的侧边栏(若你把侧边栏开成了独立窗口,就是那个窗口)",不要断言窗口存在或不存在。系统默认的自动化后端是独立外置浏览器,不是侧边栏。- 仅此模式支持:`act:saveResource`(托管下载)、以及 `query` 语义元素查询(role / name / text / label / placeholder / testId / css)。在外置模式下用这两个会被 schema 或运行时门控直接拒掉,别当通用能力使。- **`data.backend` 不是 `"rsb-webview"`(通常没有该字段)= 独立外置浏览器**:一个专属持久自动化浏览器窗口(profile 显示为 "Cindy")。`act:saveResource` 与语义 `query` 在此模式不可用,元素定位改用 snapshot 的 `ref` 或 `selector`。-**两种模式的登录态都与用户日常使用的系统浏览器(Chrome / Safari)彻底隔离,彼此之间也隔离**:初始是全空的干净环境,用户在其中登录过的站点会持久保留。**不要传 `profile`**,直接走默认即可;也不要试图接管用户日常使用的 Chrome。+**两种模式彼此隔离**。侧边栏始终是独立身份。外置浏览器默认也是独立的 `Cindy` profile;仅当用户在设置里打开「使用我的浏览器登录态」且 `status.data.realProfile.applied === true` 时,外置窗口才带着系统 Chrome / Edge / Brave 的登录拷贝(可撤销,Agent 以用户身份访问)。**不要传 `profile`**,不要试图 attach 用户日常使用的 Chrome。#### 登录与登录墙- 操作需要登录态的站点前,导航后先 `action: "snapshot"`(必要时配 `screenshot` 视觉确认)判断是否已登录。**不要**用 `profiles` 判断登录态——它不携带按站点的登录信号。diff --git a/scripts/browser-runtime/sync.mjs b/scripts/browser-runtime/sync.mjsindex 610dfce86d..cc5dffe2fb 100644--- a/scripts/browser-runtime/sync.mjs+++ b/scripts/browser-runtime/sync.mjs@@ -435,6 +435,47 @@ const LOCAL_PATCHES = {' );',},],+ 'extension/src/browser/chrome.ts': [+ {+ desc: 'decorate Chrome chip with host displayName so Cindy-real stays disk-only',+ find: ` fs.mkdirSync(userDataDir, { recursive: true });+ await ensureOutputDirectory(DEFAULT_DOWNLOAD_DIR);++ const needsDecorate = !isProfileDecorated(+ userDataDir,+ profile.name,+ (profile.color ?? DEFAULT_OPENCLAW_BROWSER_COLOR).toUpperCase(),+ DEFAULT_DOWNLOAD_DIR,+ );`,+ replace: ` fs.mkdirSync(userDataDir, { recursive: true });+ await ensureOutputDirectory(DEFAULT_DOWNLOAD_DIR);++ // LOCAL PATCH (Cindy, via sync.mjs): Chrome chip follows host displayName+ // when set so the disk key (Cindy-real) never leaks into the profile button.+ const chipName =+ normalizeOptionalString(resolved.profiles[profile.name]?.displayName) ?? profile.name;++ const needsDecorate = !isProfileDecorated(+ userDataDir,+ chipName,+ (profile.color ?? DEFAULT_OPENCLAW_BROWSER_COLOR).toUpperCase(),+ DEFAULT_DOWNLOAD_DIR,+ );`,+ },+ {+ desc: 'pass chipName into decorateOpenClawProfile instead of the disk key',+ find: ` decorateOpenClawProfile(userDataDir, {+ name: profile.name,+ color: profile.color,+ downloadDir: DEFAULT_DOWNLOAD_DIR,+ });`,+ replace: ` decorateOpenClawProfile(userDataDir, {+ name: chipName,+ color: profile.color,+ downloadDir: DEFAULT_DOWNLOAD_DIR,+ });`,+ },+ ],};/**