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(browser): 把被 Agent 浏览器抢走的外部链接转回用户自己的浏览器

Dashad282cd0e48f
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts
index 4e6459284c..cde90879b1 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts
@@ -1361,3 +1361,41 @@ describe('ExternalChromeBackend proxy lifecycle', () => {
);
});
});
+
+describe('ExternalChromeBackend external link handoff', () => {
+ it('reports an agent open as tab creation only while it may still create the tab', async () => {
+ // An agent tab looks exactly like a clicked link (URL at creation, no
+ // opener); if `open` were not reported, the handoff would take the agent's
+ // tab away and send it to the user's browser.
+ const seen: Record<string, boolean> = {};
+ let isAgentOpeningTab: () => boolean = () => false;
+ const handoff = { ensure: vi.fn(), dispose: vi.fn() };
+ const backend = new ExternalChromeBackend({
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ seen[req.action] = isAgentOpeningTab();
+ return { ok: true, action: req.action, status: 200, data: {} };
+ }),
+ }, fakeLogger(), {
+ isBrowserGone: vi.fn(async () => true),
+ createLinkHandoff: (predicate) => {
+ isAgentOpeningTab = predicate;
+ return handoff;
+ },
+ });
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ await backend.call({ action: 'snapshot' });
+ await backend.call({ action: 'open', url: 'https://example.com/' });
+
+ expect(seen).toMatchObject({ snapshot: false, open: true });
+ // Chrome's creation event may trail the call's reply.
+ expect(isAgentOpeningTab()).toBe(true);
+ vi.setSystemTime(Date.now() + 1_000);
+ expect(isAgentOpeningTab()).toBe(false);
+ // Each call re-attaches the handoff after a browser restart.
+ expect(handoff.ensure).toHaveBeenCalledTimes(3);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-link-handoff.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-link-handoff.test.ts
new file mode 100644
index 0000000000..f65399c8fa
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-link-handoff.test.ts
@@ -0,0 +1,156 @@
+// Links the user clicks elsewhere can be delivered by macOS to the managed
+// browser (same app, other profile). The handoff must reopen exactly those in
+// the user's browser before any request leaves, and never take a tab the agent
+// or the user opened inside the managed browser.
+
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { WebSocketServer, type WebSocket } from 'ws';
+
+import { ExternalLinkHandoff } from '../external-link-handoff.js';
+
+interface CdpCommand {
+ id: number;
+ method: string;
+ params?: Record<string, unknown>;
+}
+
+const APP = '/Applications/Google Chrome.app';
+const servers: Server[] = [];
+const sockets: WebSocket[] = [];
+const handoffs: ExternalLinkHandoff[] = [];
+
+afterEach(async () => {
+ for (const handoff of handoffs.splice(0)) handoff.dispose();
+ for (const socket of sockets.splice(0)) socket.terminate();
+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
+});
+
+/** Reports `existingTargets` the way Chrome does: before the discover reply. */
+async function createFakeBrowser(existingTargets: Array<Record<string, unknown>> = []) {
+ const commands: CdpCommand[] = [];
+ let browserSocket: WebSocket | undefined;
+ const wsServer = new WebSocketServer({ noServer: true });
+ wsServer.on('connection', (socket) => {
+ sockets.push(socket);
+ browserSocket = socket;
+ socket.on('message', (raw) => {
+ const command = JSON.parse(raw.toString()) as CdpCommand;
+ commands.push(command);
+ if (command.method === 'SystemInfo.getInfo') {
+ socket.send(JSON.stringify({
+ id: command.id,
+ result: { commandLine: `${APP}/Contents/MacOS/Google Chrome --remote-debugging-port=18800` },
+ }));
+ return;
+ }
+ if (command.method === 'Target.setDiscoverTargets') {
+ for (const targetInfo of existingTargets) {
+ socket.send(JSON.stringify({ method: 'Target.targetCreated', params: { targetInfo } }));
+ }
+ }
+ socket.send(JSON.stringify({ id: command.id, result: {} }));
+ });
+ });
+ const server = createServer((req, res) => {
+ const address = server.address() as AddressInfo;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ webSocketDebuggerUrl: `ws://127.0.0.1:${address.port}/devtools/browser/test` }));
+ });
+ server.on('upgrade', (request, socket, head) => {
+ wsServer.handleUpgrade(request, socket, head, (ws) => wsServer.emit('connection', ws, request));
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
+ servers.push(server);
+ return {
+ cdpHttpUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
+ commands,
+ send(event: Record<string, unknown>) {
+ browserSocket?.send(JSON.stringify(event));
+ },
+ };
+}
+
+async function connectedHandoff(options: {
+ agentOpening?: boolean;
+ openFails?: boolean;
+ existingTargets?: Array<Record<string, unknown>>;
+} = {}) {
+ const browser = await createFakeBrowser(options.existingTargets);
+ const openInUserBrowser = vi.fn(async () => {
+ if (options.openFails) throw new Error('open failed');
+ });
+ const handoff = new ExternalLinkHandoff({
+ cdpHttpUrl: () => browser.cdpHttpUrl,
+ isAgentOpeningTab: () => options.agentOpening === true,
+ logger: { warn: vi.fn() },
+ openInUserBrowser,
+ appExists: () => true,
+ });
+ handoffs.push(handoff);
+ handoff.ensure();
+ await vi.waitFor(() => expect(browser.commands.map((c) => c.method)).toContain('Fetch.enable'));
+ return { browser, openInUserBrowser };
+}
+
+/** Sends a new tab and its first document request; returns how it was resolved. */
+async function openTab(
+ browser: Awaited<ReturnType<typeof createFakeBrowser>>,
+ targetInfo: Record<string, unknown> | undefined,
+ headers: Record<string, string> = {},
+) {
+ if (targetInfo) browser.send({ method: 'Target.targetCreated', params: { targetInfo } });
+ browser.send({
+ method: 'Fetch.requestPaused',
+ params: {
+ requestId: 'request-1',
+ frameId: 'tab-1',
+ resourceType: 'Document',
+ request: { url: 'https://login.example/magic?token=1', headers },
+ },
+ });
+ await vi.waitFor(() => expect(
+ browser.commands.some((c) => c.method === 'Fetch.continueRequest' || c.method === 'Fetch.failRequest'),
+ ).toBe(true));
+ // Let a handoff's closing command land too.
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ return browser.commands
+ .filter((c) => c.method === 'Fetch.continueRequest' || c.method === 'Fetch.failRequest' || c.method === 'Target.closeTarget')
+ .map((c) => c.method);
+}
+
+const externalTab = { targetId: 'tab-1', type: 'page', url: 'https://login.example/magic?token=1' };
+
+describe('ExternalLinkHandoff', () => {
+ it('reopens an externally delivered link in the user browser before its request leaves', async () => {
+ const { browser, openInUserBrowser } = await connectedHandoff();
+
+ const resolved = await openTab(browser, externalTab);
+
+ expect(openInUserBrowser).toHaveBeenCalledWith(APP, 'https://login.example/magic?token=1');
+ // The request is failed, not continued: a one-time link must stay unused.
+ expect(resolved).toEqual(['Fetch.failRequest', 'Target.closeTarget']);
+ });
+
+ it.each([
+ ['an agent open is creating a tab', { agentOpening: true }, externalTab, {}],
+ ['the tab came from a ⌘-click in the managed window', {}, externalTab, { Referer: 'https://app.example/' }],
+ ['a page opened it as a popup', {}, { ...externalTab, openerId: 'tab-0' }, {}],
+ ['the tab existed before the handoff attached', { existingTargets: [externalTab] }, undefined, {}],
+ ])('lets the request through when %s', async (_case, options, targetInfo, headers) => {
+ const { browser, openInUserBrowser } = await connectedHandoff(options);
+
+ const resolved = await openTab(browser, targetInfo, headers);
+
+ expect(openInUserBrowser).not.toHaveBeenCalled();
+ expect(resolved).toEqual(['Fetch.continueRequest']);
+ });
+
+ it('keeps the link in the managed browser when the user browser cannot be opened', async () => {
+ const { browser } = await connectedHandoff({ openFails: true });
+
+ expect(await openTab(browser, externalTab)).toEqual(['Fetch.continueRequest']);
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts
index 9f1dbc51da..620caa4b25 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts
@@ -22,6 +22,7 @@ import {
closeAdoptedManagedBrowser,
isManagedBrowserGone,
} from './proxy-auth.js';
+import type { ExternalLinkHandoff } from './external-link-handoff.js';
interface BackendLogger {
warn(message: string, ...args: unknown[]): void;
@@ -51,8 +52,17 @@ export interface ExternalChromeBackendOptions {
closeAdoptedBrowser?: (cdpHttpUrl: string, expectedUserDataDir: string) => Promise<boolean>;
/** Non-destructive liveness probe; must not close the browser. */
isBrowserGone?: (cdpHttpUrl: string, managedUserDataDir?: string) => Promise<boolean>;
+ /**
+ * macOS only: hands links that LaunchServices delivered to the managed
+ * browser back to the user's own browser. Given whether an agent `open` may
+ * be creating a tab right now, so agent tabs are never taken away.
+ */
+ createLinkHandoff?: (isAgentOpeningTab: () => boolean) => Pick<ExternalLinkHandoff, 'ensure' | 'dispose'>;
}
+/** An agent tab's creation event can trail the end of its `open` call slightly. */
+const AGENT_TAB_OPEN_GRACE_MS = 1_000;
+
function invalidRequest(action: BrowserControlRequest['action'], message: string): BrowserControlResult {
return {
ok: false,
@@ -151,6 +161,9 @@ export class ExternalChromeBackend implements BrowserBackend {
*/
private routeBlockedByUnprovenLiveness = false;
private quiescing = false;
+ private readonly linkHandoff: Pick<ExternalLinkHandoff, 'ensure' | 'dispose'> | undefined;
+ private tabOpensInFlight = 0;
+ private lastTabOpenEndedAt = Number.NEGATIVE_INFINITY;
constructor(
runtime: BackendRuntimeShape,
@@ -158,6 +171,11 @@ export class ExternalChromeBackend implements BrowserBackend {
private readonly options: ExternalChromeBackendOptions = {},
) {
this.runtime = runtime;
+ this.linkHandoff = options.createLinkHandoff?.(() => (
+ this.tabOpensInFlight > 0 || Date.now() - this.lastTabOpenEndedAt < AGENT_TAB_OPEN_GRACE_MS
+ ));
+ // A browser left running by the previous app session takes links too.
+ this.linkHandoff?.ensure();
}
private resolveCdpHttpUrl(): string {
@@ -181,7 +199,20 @@ export class ExternalChromeBackend implements BrowserBackend {
message: 'managed browser is shutting down; new calls are not accepted',
});
}
- return this.withBackendIdentity(request, await this.enqueue(() => this.handleCall(request)));
+ const result = await this.enqueue(() => this.trackTabOpen(request, () => this.handleCall(request)));
+ this.linkHandoff?.ensure();
+ return this.withBackendIdentity(request, result);
+ }
+
+ private async trackTabOpen(request: BackendRequest, operation: () => Promise<BackendResult>): Promise<BackendResult> {
+ if (request.action !== 'open') return operation();
+ this.tabOpensInFlight += 1;
+ try {
+ return await operation();
+ } finally {
+ this.tabOpensInFlight -= 1;
+ this.lastTabOpenEndedAt = Date.now();
+ }
}
/**
@@ -202,6 +233,7 @@ export class ExternalChromeBackend implements BrowserBackend {
}
async dispose(): Promise<void> {
+ this.linkHandoff?.dispose();
return this.enqueue(async () => {
if (!this.used) return;
try {
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/external-link-handoff.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/external-link-handoff.ts
new file mode 100644
index 0000000000..cf07a8ee15
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/external-link-handoff.ts
@@ -0,0 +1,267 @@
+// External link handoff (macOS) — keeps the user's link clicks out of the
+// managed browser.
+//
+// The managed browser runs the same app as the user's everyday browser (the
+// runtime prefers the system default Chromium browser), only with another
+// user-data-dir. LaunchServices routes a clicked link's open-URL event by
+// bundle id, so it may land in the managed instance instead of the user's own.
+// Such a tab has no opener and its first document request carries no Referer.
+//
+// This watcher pauses top-level document requests browser-wide, recognizes
+// those tabs before the request leaves the machine (one-time login links stay
+// unused), and reopens the URL with `open -n -a <app> --args <url>`: the fresh
+// process forwards the URL to the user's running instance through Chrome's
+// process singleton, or launches it. The managed tab is then closed.
+
+import { execFile } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { promisify } from 'node:util';
+
+import WebSocket from 'ws';
+
+import { fetchBrowserWebSocketUrl } from './proxy-auth.js';
+
+const execFileAsync = promisify(execFile);
+
+const COMMAND_TIMEOUT_MS = 10_000;
+/** A clicked link's request follows its tab creation within milliseconds. */
+const CANDIDATE_TTL_MS = 10_000;
+
+type CdpMessage = {
+ id?: number;
+ result?: unknown;
+ error?: { message?: string };
+ method?: string;
+ params?: Record<string, unknown>;
+};
+
+type Pending = {
+ resolve: (value: unknown) => void;
+ reject: (error: Error) => void;
+ timer: ReturnType<typeof setTimeout>;
+};
+
+type TargetInfo = { targetId?: unknown; type?: unknown; url?: unknown; openerId?: unknown };
+
+export interface ExternalLinkHandoffOptions {
+ cdpHttpUrl: () => string;
+ /** True while an agent `open` may be creating a tab with a URL. */
+ isAgentOpeningTab: () => boolean;
+ logger: { warn(message: string, ...args: unknown[]): void };
+ /** Test seam; production runs `open -n -a <app> --args <url>`. */
+ openInUserBrowser?: (appPath: string, url: string) => Promise<void>;
+ /** Test seam for the app bundle check. */
+ appExists?: (appPath: string) => boolean;
+}
+
+async function openWithDefaultProfile(appPath: string, url: string): Promise<void> {
+ await execFileAsync('/usr/bin/open', ['-n', '-a', appPath, '--args', url], {
+ timeout: COMMAND_TIMEOUT_MS,
+ });
+}
+
+/** `SystemInfo.getInfo` reports the unquoted executable path first. */
+function appPathFromCommandLine(commandLine: unknown): string | undefined {
+ if (typeof commandLine !== 'string') return undefined;
+ return /^(\/.+?\.app)\/Contents\/MacOS\//.exec(commandLine)?.[1];
+}
+
+function isWebUrl(value: string): boolean {
+ try {
+ const { protocol } = new URL(value);
+ return protocol === 'http:' || protocol === 'https:';
+ } catch {
+ return false;
+ }
+}
+
+function hasReferer(headers: unknown): boolean {
+ if (!headers || typeof headers !== 'object') return false;
+ return Object.entries(headers).some(
+ ([name, value]) => name.toLowerCase() === 'referer' && typeof value === 'string' && value !== '',
+ );
+}
+
+export class ExternalLinkHandoff {
+ private socket: WebSocket | undefined;
+ private connecting = false;
+ private nextId = 1;
+ private readonly pending = new Map<number, Pending>();
+ /** Tabs that look externally opened, keyed by target id, until their first request. */
+ private readonly candidates = new Map<string, { url: string; expiresAt: number }>();
+ /** Targets reported before this id's reply already existed when we attached. */
+ private discoverCommandId: number | undefined;
+ private live = false;
+ private appPath: string | undefined;
+ private disposed = false;
+
+ constructor(private readonly options: ExternalLinkHandoffOptions) {}
+
+ /**
+ * Attach to the managed browser if not attached. A miss costs one refused
+ * loopback request, so every browser call may retry: the browser often comes
+ * up only a moment after the call that found it stopped.
+ */
+ ensure(): void {
+ if (this.disposed || this.socket || this.connecting) return;
+ this.connecting = true;
+ void this.connect()
+ .catch(() => this.reset())
+ .finally(() => {
+ this.connecting = false;
+ });
+ }
+
+ dispose(): void {
+ this.disposed = true;
+ this.reset();
+ }
+
+ private async connect(): Promise<void> {
+ const wsUrl = await fetchBrowserWebSocketUrl(this.options.cdpHttpUrl());
+ const socket = new WebSocket(wsUrl, { handshakeTimeout: COMMAND_TIMEOUT_MS });
+ socket.on('message', (data) => {
+ if (this.socket === socket) this.handleMessage(data);
+ });
+ socket.on('close', () => {
+ if (this.socket === socket) this.reset();
+ });
+ socket.on('error', () => {
+ if (this.socket === socket) this.reset();
+ });
+ await new Promise<void>((resolve, reject) => {
+ socket.once('open', () => resolve());
+ socket.once('error', () => reject(new Error('link handoff channel could not open')));
+ socket.once('close', () => reject(new Error('link handoff channel closed before setup')));
+ });
+ if (this.disposed) {
+ socket.terminate();
+ return;
+ }
+ this.socket = socket;
+
+ const info = (await this.command('SystemInfo.getInfo')) as { commandLine?: unknown };
+ const appPath = appPathFromCommandLine(info.commandLine);
+ if (!appPath || !(this.options.appExists ?? existsSync)(appPath)) {
+ throw new Error('managed browser app bundle is unknown');
+ }
+ this.appPath = appPath;
+ this.discoverCommandId = this.nextId;
+ await this.command('Target.setDiscoverTargets', { discover: true });
+ await this.command('Fetch.enable', {
+ patterns: [{ urlPattern: '*', resourceType: 'Document', requestStage: 'Request' }],
+ });
+ }
+
+ private reset(): void {
+ const socket = this.socket;
+ this.socket = undefined;
+ this.live = false;
+ this.discoverCommandId = undefined;
+ this.appPath = undefined;
+ this.candidates.clear();
+ for (const [id, pending] of this.pending) {
+ clearTimeout(pending.timer);
+ pending.reject(new Error('link handoff channel closed'));
+ this.pending.delete(id);
+ }
+ // Closing the client ends its interception; Chrome resumes paused requests.
+ if (socket && socket.readyState !== WebSocket.CLOSED) socket.terminate();
+ }
+
+ private handleMessage(data: WebSocket.RawData): void {
+ let message: CdpMessage;
+ try {
+ message = JSON.parse(Buffer.isBuffer(data) ? data.toString('utf8') : String(data)) as CdpMessage;
+ } catch {
+ return;
+ }
+ if (typeof message.id === 'number') {
+ // Set synchronously: frames parsed from one chunk dispatch back to back,
+ // before any continuation of the awaited command could run.
+ if (message.id === this.discoverCommandId) this.live = true;
+ const pending = this.pending.get(message.id);
+ if (!pending) return;
+ this.pending.delete(message.id);
+ clearTimeout(pending.timer);
+ if (message.error) pending.reject(new Error('link handoff command failed'));
+ else pending.resolve(message.result);
+ return;
+ }
+ const params = message.params ?? {};
+ if (message.method === 'Target.targetCreated') {
+ this.noteCreatedTarget(params.targetInfo as TargetInfo | undefined);
+ } else if (message.method === 'Target.targetDestroyed') {
+ if (typeof params.targetId === 'string') this.candidates.delete(params.targetId);
+ } else if (message.method === 'Fetch.requestPaused') {
+ this.handlePausedRequest(params);
+ }
+ }
+
+ private noteCreatedTarget(info: TargetInfo | undefined): void {
+ if (!this.live || !info || info.type !== 'page' || info.openerId) return;
+ if (typeof info.targetId !== 'string' || typeof info.url !== 'string') return;
+ // Agent tabs are created with their URL too; they are told apart only by
+ // the agent's own open call being in flight.
+ if (!isWebUrl(info.url) || this.options.isAgentOpeningTab()) return;
+ this.candidates.set(info.targetId, { url: info.url, expiresAt: Date.now() + CANDIDATE_TTL_MS });
+ }
+
+ private handlePausedRequest(params: Record<string, unknown>): void {
+ const requestId = typeof params.requestId === 'string' ? params.requestId : undefined;
+ if (!requestId) return;
+ // A main-frame request reports the tab's target id as its frame id.
+ const targetId = typeof params.frameId === 'string' ? params.frameId : undefined;
+ const candidate = targetId ? this.candidates.get(targetId) : undefined;
+ if (targetId) this.candidates.delete(targetId);
+ const request = params.request as { headers?: unknown } | undefined;
+ const appPath = this.appPath;
+ if (
+ !targetId
+ || !candidate
+ || candidate.expiresAt < Date.now()
+ // ⌘-click inside the managed window also makes an opener-less tab, but
+ // its request carries the source page as Referer.
+ || hasReferer(request?.headers)
+ || !appPath
+ ) {
+ void this.command('Fetch.continueRequest', { requestId }).catch(() => {});
+ return;
+ }
+ void this.handOff(requestId, targetId, candidate.url, appPath);
+ }
+
+ private async handOff(requestId: string, targetId: string, url: string, appPath: string): Promise<void> {
+ try {
+ await (this.options.openInUserBrowser ?? openWithDefaultProfile)(appPath, url);
+ } catch {
+ this.options.logger.warn('could not hand an external link to the user browser; keeping it in the managed browser');
+ await this.command('Fetch.continueRequest', { requestId }).catch(() => {});
+ return;
+ }
+ await this.command('Fetch.failRequest', { requestId, errorReason: 'Aborted' }).catch(() => {});
+ await this.command('Target.closeTarget', { targetId }).catch(() => {});
+ }
+
+ private command(method: string, params?: Record<string, unknown>): Promise<unknown> {
+ const socket = this.socket;
+ if (!socket || socket.readyState !== WebSocket.OPEN) {
+ return Promise.reject(new Error('link handoff channel is not open'));
+ }
+ const id = this.nextId++;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error('link handoff command timed out'));
+ }, COMMAND_TIMEOUT_MS);
+ this.pending.set(id, { resolve, reject, timer });
+ try {
+ socket.send(JSON.stringify({ id, method, ...(params ? { params } : {}) }));
+ } catch {
+ clearTimeout(timer);
+ this.pending.delete(id);
+ reject(new Error('link handoff command failed'));
+ }
+ });
+ }
+}
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..c63c29c462 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
@@ -53,7 +53,7 @@ function isNetworkCapableTargetType(type: unknown): boolean {
return typeof type === 'string' && NETWORK_CAPABLE_TARGET_TYPES.has(type);
}
-async function fetchBrowserWebSocketUrl(cdpHttpUrl: string): Promise<string> {
+export async function fetchBrowserWebSocketUrl(cdpHttpUrl: string): Promise<string> {
const base = new URL(cdpHttpUrl);
if (
base.protocol !== 'http:'
diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.ts
index 9091ea1ddb..5d564237f0 100644
--- a/apps/desktop/src/main/mcp-integrations/browser.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser.ts
@@ -71,6 +71,7 @@ import {
} from './browser-real-profile/index.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { createBrowserBackendIpcHandlers } from './browser-backend/settings-ipc.js';
+import { ExternalLinkHandoff } from './browser-backend/external-link-handoff.js';
import { resolveBrowserScreenshot } from './browserScreenshotResolver.js';
import { compressInlineImage } from './inlineImageCompressor.js';
import { raiseAgentBrowserWindow } from './raise-agent-browser-window.js';
@@ -240,6 +241,15 @@ const externalChromeBackend = new ExternalChromeBackend(
createRuntime: createManagedRuntime,
cdpHttpUrl: () => currentGuardIdentity().cdpHttpUrl,
managedUserDataDir: () => currentGuardIdentity().managedUserDataDir,
+ ...(process.platform === 'darwin'
+ ? {
+ createLinkHandoff: (isAgentOpeningTab: () => boolean) => new ExternalLinkHandoff({
+ cdpHttpUrl: () => currentGuardIdentity().cdpHttpUrl,
+ isAgentOpeningTab,
+ logger,
+ }),
+ }
+ : {}),
},
);
diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.md
index 51200a63ff..c0e526c340 100644
--- a/packages/browser-control-runtime/upstream/MAINTAINING.md
+++ b/packages/browser-control-runtime/upstream/MAINTAINING.md
@@ -78,6 +78,7 @@ host 在 `browser-managed-config.ts` 用 `buildManagedConfig({proxyServer?})`
| 11 | 开了「使用我的浏览器登录态」但窗口仍是登出 | 快照把 `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` |
| 12 | 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` |
| 13 | 已有完全磁盘访问仍弹「需要完全磁盘访问权限」 | 第一次 enable 在 macOS 无条件跑 `guideFullDiskAccessAfterReadDenied` | 同意拷贝之后先 `probeSourceRead`(只 open 源 Local State / Cookies,不拷贝、不回路径);`readable: true` 就跳过。真正快照 `REAL_PROFILE_READ_DENIED` 仍弹。不自动打开系统设置 |
+| 14 | macOS 上用户在别的 App 点链接,打开的是 Agent 浏览器而不是自己的浏览器 | Agent 浏览器优先选用系统默认浏览器的同一个 App,只换 `--user-data-dir`;LaunchServices 按 bundle id 投递打开链接事件,会落到任意一个同 App 实例 | host 的 `ExternalLinkHandoff`(`browser-backend/external-link-handoff.ts`,仅 macOS)在浏览器级 `Fetch.enable` 只暂停 Document 请求:新标签无 opener、创建时即带 http(s) URL、首个请求无 Referer,且当时没有 Agent `open` 在途(含 1 秒余量),即判为外部链接——先 `open -n -a <App> --args <url>`(新进程经 Chrome 单例转交给用户的默认 profile 实例,未运行则启动它),成功后 `failRequest` + `closeTarget`,请求从未发出,一次性登录链接不会被用掉;转交失败则放行。⌘ 点击靠 Referer、网页弹窗靠 opener 排除。新增建标签的 action 必须同样计入 `trackTabOpen`,否则 Agent 标签会被当成外部链接转走 |
### 4.1 per-start 代理不变量