Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(settings): say why the browser login copy switch failed

Dashf603d26e82dd
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.ts
index 03103c8836..19a52fb0cc 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
@@ -1,5 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
+import { extractIpcError } from '../../../../shared/ipcError.js';
+import { RealProfileError } from '../../browser-real-profile/types.js';
import { createBrowserBackendIpcHandlers } from '../settings-ipc.js';
function buildHandlers() {
@@ -95,4 +97,15 @@ describe('browser backend Settings IPC handlers', () => {
await expect(handlers.setKind(trustedEvent, { kind: 'unknown' })).rejects.toThrow();
});
+
+ // The login-copy switch failed with only a generic toast; a known cause such as another Cindy
+ // holding the agent browser must reach Settings as its code so the toast can name it.
+ it('keeps the code of a known login-copy failure for Settings', async () => {
+ const { trustedEvent, deps, handlers } = buildHandlers();
+ deps.setUseRealProfile.mockRejectedValueOnce(
+ new RealProfileError('FOREIGN_AGENT_BROWSER', 'Another Cindy is using the agent browser port.'),
+ );
+ const err = await handlers.setUseRealProfile(trustedEvent, { enabled: true }).catch((e) => e);
+ expect(extractIpcError(err)?.code).toBe('FOREIGN_AGENT_BROWSER');
+ });
});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/proxy-auth.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/proxy-auth.ts
index 1ff24c09ed..d5c1e09719 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/proxy-auth.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/proxy-auth.ts
@@ -302,6 +302,46 @@ export async function isManagedBrowserGone(cdpHttpUrl: string): Promise<boolean>
return await confirmCdpGone(cdpHttpUrl);
}
+/**
+ * Read the command line of the Chrome answering on a loopback CDP endpoint, without touching it.
+ * Null when the endpoint does not answer in time.
+ */
+export async function readCdpBrowserCommandLine(cdpHttpUrl: string): Promise<string | null> {
+ let wsUrl: string;
+ try {
+ wsUrl = await fetchBrowserWebSocketUrl(cdpHttpUrl);
+ } catch {
+ return null;
+ }
+ const socket = new WebSocket(wsUrl, { handshakeTimeout: COMMAND_TIMEOUT_MS });
+ const commandLine = await new Promise<string | null>((resolve) => {
+ const timer = setTimeout(() => resolve(null), COMMAND_TIMEOUT_MS);
+ const finish = (value: string | null) => {
+ clearTimeout(timer);
+ resolve(value);
+ };
+ socket.once('open', () => {
+ socket.send(JSON.stringify({ id: 1, method: 'SystemInfo.getInfo' }), (error) => {
+ if (error) finish(null);
+ });
+ });
+ socket.on('message', (data) => {
+ try {
+ const message = JSON.parse(Buffer.isBuffer(data) ? data.toString('utf8') : String(data)) as CdpResponse;
+ if (message.id !== 1) return;
+ const value = (message.result as { commandLine?: unknown } | undefined)?.commandLine;
+ finish(typeof value === 'string' ? value : null);
+ } catch {
+ // Ignore unrelated events.
+ }
+ });
+ socket.once('close', () => finish(null));
+ socket.once('error', () => finish(null));
+ });
+ try { socket.close(); } catch { /* best effort */ }
+ return commandLine;
+}
+
export async function closeAdoptedManagedBrowser(
cdpHttpUrl: string,
expectedUserDataDir: string,
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.ts
index 2a66a4138e..7bd9e93b1a 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
@@ -3,7 +3,14 @@ import type {
BrowserBackendRecoveryResult,
BrowserBackendSourceReadAccess,
} from '../../../shared/browserBackend.js';
-import { requireBoolean, requireEnum, requireObject } from '../../utils/ipcValidate.js';
+import { isBrowserOpenForLoginErrorCode } from '../../../shared/browserBackend.js';
+import {
+ requireBoolean,
+ requireEnum,
+ requireObject,
+ throwIpcError,
+} from '../../utils/ipcValidate.js';
+import { isRealProfileError } from '../browser-real-profile/types.js';
import type { BackendKind } from './types.js';
export interface BrowserBackendSettingsState {
@@ -46,7 +53,15 @@ export function createBrowserBackendIpcHandlers<Event>(deps: BrowserBackendIpcDe
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) };
+ try {
+ return { ok: true as const, enabled: await deps.setUseRealProfile(enabled) };
+ } catch (err) {
+ // Known login-copy failures keep their code so Settings can say what went wrong.
+ if (isRealProfileError(err) && isBrowserOpenForLoginErrorCode(err.code)) {
+ throwIpcError(err.code, err.message);
+ }
+ throw err;
+ }
},
async reset(event: Event) {
deps.assertTrusted(event);
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.ts
index ccc0774705..9ff40350d0 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-real-profile/types.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-real-profile/types.ts
@@ -17,6 +17,7 @@ export type RealProfileErrorCode =
| 'HEADLESS_FORBIDDEN'
| 'COPY_FAILED'
| 'STOP_FAILED'
+ | 'FOREIGN_AGENT_BROWSER'
| 'REAL_PROFILE_READ_DENIED'
| 'APP_BOUND_ENCRYPTION_UNSUPPORTED';
diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.ts
index 0bac4b8a56..cba7ae0a1c 100644
--- a/apps/desktop/src/main/mcp-integrations/browser.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser.ts
@@ -69,6 +69,7 @@ import {
createBrowserProfileLifecycleQueue,
managedConfigPatchBeforeStop,
FOREIGN_AGENT_BROWSER_ERROR,
+ isRealProfileError,
probeOsSourceProfileReadAccess,
readCopiedLoginsCdpPort,
wrapRuntimeWithRealProfile,
@@ -77,6 +78,7 @@ import {
} from './browser-real-profile/index.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { createBrowserBackendIpcHandlers } from './browser-backend/settings-ipc.js';
+import { readCdpBrowserCommandLine } from './browser-backend/proxy-auth.js';
import { resolveBrowserScreenshot } from './browserScreenshotResolver.js';
import { compressInlineImage } from './inlineImageCompressor.js';
import { raiseAgentBrowserWindow } from './raise-agent-browser-window.js';
@@ -434,6 +436,20 @@ export async function setActiveBrowserBackendKind(kind: BackendKind): Promise<vo
await backendController.setKind(kind);
}
+/**
+ * Whether the Chrome on the managed CDP port was started with a profile outside this Cindy's
+ * browser runtime, i.e. another Cindy (another edition or a dev build) shares the port. Only
+ * used to explain a failed stop; it never decides whether a browser may be closed.
+ */
+async function managedPortHeldByAnotherCindy(): Promise<boolean> {
+ const runtimeDir = realProfileRuntimeDir();
+ if (!runtimeDir) return false;
+ const commandLine = await readCdpBrowserCommandLine(currentGuardIdentity().cdpHttpUrl).catch(
+ () => null,
+ );
+ return commandLine !== null && !commandLine.includes(`--user-data-dir=${runtimeDir}${nodePath.sep}`);
+}
+
async function stopExternalRuntimeIfUsed(): Promise<void> {
const useRealProfile = readBrowserBackendSettings().useRealProfile;
const patch = managedConfigPatchBeforeStop({
@@ -454,7 +470,17 @@ async function stopExternalRuntimeIfUsed(): Promise<void> {
// into the now-unlinked files. The backend's stop is idempotent and proves
// absence itself, so always issue it and require it to succeed.
const stop = await externalChromeBackend.call({ action: 'stop' });
- assertManagedBrowserStopped({ status, stop });
+ try {
+ assertManagedBrowserStopped({ status, stop });
+ } catch (err) {
+ if (isRealProfileError(err) && err.code === 'STOP_FAILED' && (await managedPortHeldByAnotherCindy())) {
+ throw new RealProfileError(
+ 'FOREIGN_AGENT_BROWSER',
+ 'Another Cindy is using the agent browser port, so copied logins cannot be changed now.',
+ );
+ }
+ throw err;
+ }
if (!stop.ok) {
throw new RealProfileError(
'STOP_FAILED',
diff --git a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
index 70b7c700c4..a5bf890719 100644
--- a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
@@ -717,7 +717,14 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
);
} catch (err) {
log.error('browserBackend.setUseRealProfile failed', err);
- toast.error(t('settings.computerUse.realProfile.toast.failed'));
+ const errorCode = browserOpenForLoginErrorCode(err);
+ toast.error(
+ t(
+ errorCode
+ ? browserOpenForLoginToastKey(errorCode, 'settings.computerUse.realProfile.toast.failed')
+ : 'settings.computerUse.realProfile.toast.failed',
+ ),
+ );
} finally {
setUseRealProfilePending(false);
}
diff --git a/apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts b/apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts
index 0cbb1270c5..16554237e2 100644
--- a/apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts
+++ b/apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts
@@ -23,6 +23,9 @@ export function browserOpenForLoginErrorCode(
return isBrowserOpenForLoginErrorCode(code) ? code : null;
}
-export function browserOpenForLoginToastKey(code: BrowserOpenForLoginErrorCode): string {
- return TOAST_KEYS[code] ?? 'settings.computerUse.browser.toast.openForLoginFailed';
+export function browserOpenForLoginToastKey(
+ code: BrowserOpenForLoginErrorCode,
+ fallback = 'settings.computerUse.browser.toast.openForLoginFailed',
+): string {
+ return TOAST_KEYS[code] ?? fallback;
}