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-extension): address the pre-PR review

Dash7eacb3b33b74
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-browser-extension.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-browser-extension.md
index a616b11ba6..e9341ebffe 100644
--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-browser-extension.md
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-browser-extension.md
@@ -25,12 +25,19 @@
```js
// 插件 → 宿主:向扩展投递作业、推送站点策略与配对身份、回传转交结果
-const status = await cindy.send({ type: 'browser-extension-request', kind: 'status' });
-if (!status.ok && status.errorCode) {
- // 旧宿主不认识这个槽:回落到你自己的接线进程,不要把拒绝当作已连接
+let status;
+try {
+ status = await cindy.send({ type: 'browser-extension-request', kind: 'status' });
+} catch (err) {
+ // 只有旧宿主会拒绝这个管子类型([INVALID_PARAMS] 未知的管子消息类型):回落到你自己的
+ // 接线进程,并记住。不要把拒绝当作已连接。
}
+// 新宿主也会返回 errorCode(HOST_NOT_READY、PERMISSION_DENIED 等):这表示宿主有这个槽,
+// 只是暂时不可用。不要据此回落,也不要缓存结果,下次再探测。
await cindy.send({ type: 'browser-extension-request', kind: 'setPolicy', policy });
await cindy.send({ type: 'browser-extension-request', kind: 'setTrustedClients', clients: paired });
+// 宿主还没有你的站点策略时,会拒绝页面作业并发来事件
+// { type: 'event', name: 'browser-extension-policy-request' }:收到后立即推送策略与配对身份。
const result = await cindy.send({
type: 'browser-extension-request',
kind: 'act',
@@ -61,9 +68,14 @@ cindy.onHostMessage(async (msg) => {
规则与红线:
-- **站点策略归你**:读取默认开放公网、交互按站点授权、本机与私网一律拒绝。你保存并在启动
- 与每次变更时 `setPolicy` 推给宿主;宿主缓存到用户私有目录并在每个作业上强制,新授权必须经
- `cindy.confirm` 真实确认。
+- **站点策略归你**:读取与交互默认开放,本机、私网与单段内网主机名和公网网站一样可访问,也可以
+ 写进名单单独屏蔽。你保存并在启动与每次变更时 `setPolicy` 推给宿主;宿主缓存到用户私有目录
+ 并在每个作业上强制,没有缓存时在收到你的策略前拒绝页面作业,新授权必须经 `cindy.confirm`
+ 真实确认。
+- **`nativeHost` 只给官方 Cindy Chrome**:Native Messaging 程序在插件沙箱外运行,且同一账号的
+ 所有 Cindy 共用一份注册,宿主只为官方 Cindy Chrome(`my-browser`,名称
+ `com.makecindy.browser`,并声明了 Node 程序)安装它。其它插件声明了也只开桥接,扩展需要手动
+ 配对。
- **作业一次送达**:已送达的作业不会重投;结果 `execution` 为 `unknown` 时要让 Agent 核对
页面,不能当成功或未执行报告。
- **宿主代码不认识你**:桥接只按声明工作,不会为某个插件写特例;需要线协议之外的能力,先提
diff --git a/apps/desktop/src/main/browser-extension/__tests__/bridge.test.ts b/apps/desktop/src/main/browser-extension/__tests__/bridge.test.ts
index 431757d342..16149a2097 100644
--- a/apps/desktop/src/main/browser-extension/__tests__/bridge.test.ts
+++ b/apps/desktop/src/main/browser-extension/__tests__/bridge.test.ts
@@ -204,21 +204,35 @@ describe('policy · 站点策略与 URL 脱敏(与扩展侧同判据)', () => {
expect(normalizeBrowserExtensionHost('*.example.test')).toBe('example.test');
expect(normalizeBrowserExtensionHost('=example.test')).toBe('=example.test');
for (const bad of [
- 'com',
+
'https://example.test',
'example.test/path',
'example.test:443',
'*',
- '127.0.0.1',
]) {
expect(() => normalizeBrowserExtensionHost(bad)).toThrow();
}
+ // Local, private and single-label intranet hosts can be listed, so they can be blocked alone.
+ for (const host of ['127.0.0.1', '192.168.1.2', '[::1]', 'localhost', 'jira', 'nas.local'])
+ expect(() => normalizeBrowserExtensionHost(host)).not.toThrow();
expect(() =>
normalizeBrowserExtensionPolicy({ read: { block: 'example.test' }, interact: { allow: [] } }),
).toThrow();
});
+ // Review 2026-10-29: the protocol session took any DevTools method, so a recipe job could read
+ // every cookie in the profile. Mirrors the extension's list; it also keeps cookies on-site.
+ it('配方的协议命令只接受配方会发的方法;读 Cookie 必须指明站点地址', () => {
+ const cdp = (method: string, params?: unknown) =>
+ validateBrowserExtensionJob('cdp', { url: 'https://example.test', tabId: 1, op: 'command', method, params });
+ expect(() => cdp('Network.getAllCookies')).toThrow(/not available/);
+ expect(() => cdp('Runtime.evaluate', { expression: '1' })).toThrow(/not available/);
+ expect(() => cdp('Network.getCookies')).toThrow(/params.urls/);
+ expect(() => cdp('Network.getCookies', { urls: ['https://example.test/'] })).not.toThrow();
+ expect(() => cdp('Storage.getCookies', {})).not.toThrow();
+ });
+
it('提取属性是封闭集合;载荷校验保留空文本与空选项', () => {
for (const attr of ['href', 'src', 'datetime', 'title', 'alt', 'aria-label', 'role']) {
expect(() =>
@@ -297,6 +311,36 @@ describe('bridge · 连接与身份', () => {
expect(result).toMatchObject({ error: 'EXTENSION_DISCONNECTED', execution: 'not_executed' });
});
+ // Review 2026-10-29: a caller still holding a closed bridge reopened an ownerless listener the
+ // extension could connect to after the plugin was disabled or replaced.
+ it('关闭后的桥接不会被 status/act 重新拉起', async () => {
+ const { bridge } = await fixture();
+ await bridge.close();
+ expect(await bridge.status()).toMatchObject({ ok: false, error: 'BRIDGE_STOPPED' });
+ expect(await bridge.act('text', { url: 'https://example.test' })).toMatchObject({
+ ok: false,
+ error: 'BRIDGE_STOPPED',
+ execution: 'not_executed',
+ });
+ expect(bridge.listeningPort).toBe(0);
+ });
+
+ // Review 2026-10-29: without the user's saved permissions the permissive default must not stand
+ // in for a blocklist the plugin still holds.
+ it('等待策略的桥接在收到策略前拒绝页面作业', async () => {
+ const { bridge, client } = await fixture({ awaitPolicy: true });
+ await client({ native: true });
+ expect(await bridge.act('text', { url: 'https://example.test' })).toMatchObject({
+ ok: false,
+ error: 'POLICY_NOT_READY',
+ execution: 'not_executed',
+ });
+ await bridge.setPolicy(defaultBrowserExtensionPolicy());
+ expect(await bridge.act('text', { url: 'https://example.test' })).not.toMatchObject({
+ error: 'POLICY_NOT_READY',
+ });
+ });
+
it('回环 HTTP 拒绝网页、预检、改绑 Host、旧会话与任意端点', async () => {
const { url, ready } = await fixture();
const c = await ready();
@@ -641,7 +685,8 @@ describe('bridge · 转交请求(翻译/字幕)', () => {
const c = await ready();
const job = {
id: crypto.randomUUID(),
- request: { op: 'translate', text: 'hello', source: { url: 'https://example.test/' } },
+ // view: the tab the request came from; per-tab subtitle state depends on it reaching the plugin.
+ request: { op: 'translate', text: 'hello', view: 'tab:12', source: { url: 'https://example.test/' } },
};
expect(
(await c.request('/learning/start', job, { Origin: 'https://example.test' })).status,
@@ -653,7 +698,7 @@ describe('bridge · 转交请求(翻译/字幕)', () => {
expect(relays[0]).toMatchObject({
id: job.id,
clientId: c.id,
- request: { op: 'translate', text: 'hello' },
+ request: { op: 'translate', text: 'hello', view: 'tab:12' },
});
// 改动请求体后旧证明失效。
const challenge = await c.request('/learning/challenge');
diff --git a/apps/desktop/src/main/browser-extension/__tests__/native-binding.test.ts b/apps/desktop/src/main/browser-extension/__tests__/native-binding.test.ts
index 24b3d8142c..177fe2f7a4 100644
--- a/apps/desktop/src/main/browser-extension/__tests__/native-binding.test.ts
+++ b/apps/desktop/src/main/browser-extension/__tests__/native-binding.test.ts
@@ -95,6 +95,29 @@ describe('native-binding', () => {
await b.close();
});
+ // Review 2026-10-29: registrations were never withdrawn. Every Cindy on the account shares one,
+ // so it may only go once no running Cindy still serves a connection.
+ it('withdraws the browser registration only after the last running Cindy closes', async () => {
+ const { binaryDir, profile, root } = await fixture();
+ const opts = {
+ hostName: 'com.example.browser',
+ binaryDir,
+ root,
+ profiles: [profile],
+ platform: 'darwin' as const,
+ arch: 'arm64',
+ };
+ const registration = path.join(profile, 'NativeMessagingHosts', 'com.example.browser.json');
+ const release = createNativeBinding(opts);
+ const dev = createNativeBinding(opts);
+ await release.install(18810, [EXT]);
+ await dev.install(18811, [EXT]);
+ await dev.close();
+ await expect(fs.access(registration)).resolves.toBeUndefined();
+ await release.close();
+ await expect(fs.access(registration)).rejects.toThrow();
+ });
+
it('Windows registration uses only current-user fixed registry keys and argv', async () => {
const { dir, binaryDir } = await fixture();
await fs.mkdir(path.join(binaryDir, 'win32-x64'), { recursive: true });
diff --git a/apps/desktop/src/main/browser-extension/bridge.ts b/apps/desktop/src/main/browser-extension/bridge.ts
index 3ceab7d2c1..0c49fb70d7 100644
--- a/apps/desktop/src/main/browser-extension/bridge.ts
+++ b/apps/desktop/src/main/browser-extension/bridge.ts
@@ -100,6 +100,8 @@ export interface BrowserExtensionClientInfo {
origin: string;
extensionId: string;
publicKey?: string;
+ /** Changes when the browser restarts (tab ids start over); absent from older extensions. */
+ boot?: string;
}
export interface BrowserExtensionBridgeStatus {
@@ -131,6 +133,12 @@ export interface BrowserExtensionBridgeOptions {
nativeToken?: string;
/** 扩展发起的转交请求到达时回调(宿主转交给插件)。 */
onRelay?: (notice: BrowserExtensionRelayNotice) => void;
+ /**
+ * Refuse every page job until the first setPolicy: the host has no saved copy of the user's
+ * site permissions yet (first run after the bridge moved into the host, or an unreadable cache),
+ * so the permissive default must not stand in for a blocklist the plugin still holds.
+ */
+ awaitPolicy?: boolean;
ports?: readonly number[];
pollTimeout?: number;
connectWait?: number;
@@ -155,6 +163,7 @@ interface Client {
challenge: { value: string; expires: number; publicKey: string } | null;
session: string | null;
trusted: boolean;
+ boot?: string;
}
type JobState = 'queued' | 'delivered' | 'acknowledged';
@@ -221,9 +230,24 @@ export class BrowserExtensionBridge {
private readonly knownIds: Set<string>;
private readonly now: () => number;
+ private policyKnown: boolean;
+ private closed = false;
+
constructor(private readonly options: BrowserExtensionBridgeOptions) {
this.knownIds = new Set(options.extensionIds);
this.now = options.now ?? Date.now;
+ this.policyKnown = options.awaitPolicy !== true;
+ }
+
+ private gate(action: unknown, url: unknown): ReturnType<typeof checkBrowserExtensionPolicy> {
+ if (!this.policyKnown)
+ return {
+ ok: false,
+ error: 'POLICY_NOT_READY',
+ message: 'Cindy is still loading your site permissions from the plugin. Try again shortly.',
+ execution: 'not_executed',
+ };
+ return checkBrowserExtensionPolicy(this.policy, action, url);
}
get listeningPort(): number {
@@ -302,6 +326,7 @@ export class BrowserExtensionBridge {
origin: c.origin,
extensionId: c.extensionId,
...(c.publicKey ? { publicKey: c.publicKey } : {}),
+ ...(c.boot ? { boot: c.boot } : {}),
};
}
@@ -472,7 +497,7 @@ export class BrowserExtensionBridge {
): { id: string; action: string; payload: BrowserExtensionJobPayload } | null {
for (const job of this.jobs.values()) {
if (job.state !== 'queued' || job.clientId !== clientId) continue;
- const gate = checkBrowserExtensionPolicy(this.policy, job.action, job.payload.url);
+ const gate = this.gate(job.action, job.payload.url);
if (!gate.ok) {
this.finish(job, gate as unknown as Record<string, unknown>);
continue;
@@ -631,6 +656,8 @@ export class BrowserExtensionBridge {
}
client.browser = family ?? client.browser;
client.version = String(this.header(req, 'x-my-browser-version') || '').slice(0, 30);
+ const boot = this.header(req, 'x-my-browser-boot');
+ if (typeof boot === 'string' && /^[0-9a-f-]{36}$/i.test(boot)) client.boot = boot;
client.installedVersion = installedVersion;
client.seen = this.now();
if (keyHeader !== undefined && publicKey !== client.publicKey) {
@@ -783,7 +810,7 @@ export class BrowserExtensionBridge {
return this.send(res, failure('INVALID_INPUT', 'Check the selected text or file.'), 400);
}
if (payload.source.url) {
- const gate = checkBrowserExtensionPolicy(this.policy, 'text', payload.source.url);
+ const gate = this.gate('text', payload.source.url);
if (!gate.ok) return this.send(res, gate, 403);
payload.source.url = redactBrowserUrl(payload.source.url);
}
@@ -838,7 +865,7 @@ export class BrowserExtensionBridge {
return this.send(res, { ok: true });
}
const gate = item.payload.source.url
- ? checkBrowserExtensionPolicy(this.policy, 'text', item.payload.source.url)
+ ? this.gate('text', item.payload.source.url)
: { ok: true as const };
if (!gate.ok) {
this.relays.delete(item.id);
@@ -898,8 +925,7 @@ export class BrowserExtensionBridge {
if (job.revoked && req.url !== '/result')
return this.send(res, this.jobFailure(job, job.revoked.error, job.revoked.message), 403);
if (req.url === '/ack' || req.url === '/authorize') {
- const gate = checkBrowserExtensionPolicy(
- this.policy,
+ const gate = this.gate(
job.action,
req.url === '/authorize' ? b.url : job.payload.url,
);
@@ -938,7 +964,7 @@ export class BrowserExtensionBridge {
...result,
ok: true,
tabs: tabs.map((t) => {
- if (checkBrowserExtensionPolicy(this.policy, 'text', t.url).ok) return t;
+ if (this.gate('text', t.url).ok) return t;
const row: Record<string, unknown> = { id: t.id, redacted: true };
if (['loading', 'complete', 'unloaded'].includes(t.status as string))
row.status = t.status;
@@ -964,7 +990,7 @@ export class BrowserExtensionBridge {
} else if (
!result.error &&
result.url &&
- !checkBrowserExtensionPolicy(this.policy, job.action, result.url).ok
+ !this.gate(job.action, result.url).ok
) {
result = this.jobFailure(
job,
@@ -990,6 +1016,9 @@ export class BrowserExtensionBridge {
// ── 生命周期 ────────────────────────────────────────────────────────────
async start(): Promise<void> {
+ // A closed bridge stays closed: a caller still holding it must not reopen an ownerless
+ // listener that the extension could connect to after the plugin was disabled or replaced.
+ if (this.closed) throw new Error('BRIDGE_STOPPED');
if (this.server) return;
if (this.starting) return this.starting;
this.starting = (async () => {
@@ -1033,6 +1062,7 @@ export class BrowserExtensionBridge {
private startFailure(e: unknown): BrowserExtensionFailure {
const code = (e as NodeJS.ErrnoException)?.code;
+ if (this.closed) return failure('BRIDGE_STOPPED', 'This browser connection was closed. Check Cindy Chrome is enabled.');
return failure(
code === 'BRIDGE_PORTS_BUSY'
? 'BRIDGE_PORTS_BUSY'
@@ -1050,13 +1080,14 @@ export class BrowserExtensionBridge {
{ ok: true; policy: BrowserExtensionPolicy } | (BrowserExtensionFailure & { applied?: true })
> {
this.policy = normalizeBrowserExtensionPolicy(input);
+ this.policyKnown = true;
const dispatches: Array<Promise<boolean>> = [];
for (const job of [...this.jobs.values()]) {
// 撤销同时作用于原请求与其重定向目标:只按后者判会让被阻止的请求悄悄活着。
- const original = checkBrowserExtensionPolicy(this.policy, job.action, job.payload.url);
+ const original = this.gate(job.action, job.payload.url);
const gate =
original.ok && job.authorizedUrl
- ? checkBrowserExtensionPolicy(this.policy, job.action, job.authorizedUrl)
+ ? this.gate(job.action, job.authorizedUrl)
: original;
if (!gate.ok) {
if (job.dispatchSettled) {
@@ -1070,9 +1101,9 @@ export class BrowserExtensionBridge {
const completed = await Promise.all(dispatches);
const uncertain = [...this.unconfirmedDispatches.values()].some(
(job) =>
- !checkBrowserExtensionPolicy(this.policy, job.action, job.url).ok ||
+ !this.gate(job.action, job.url).ok ||
(job.authorizedUrl &&
- !checkBrowserExtensionPolicy(this.policy, job.action, job.authorizedUrl).ok),
+ !this.gate(job.action, job.authorizedUrl).ok),
);
if (completed.some((finished) => !finished) || uncertain || this.unconfirmedOverflow) {
return {
@@ -1113,7 +1144,7 @@ export class BrowserExtensionBridge {
!!client?.trusted &&
this.now() <= item.expiresAt &&
(!item.payload.source.url ||
- checkBrowserExtensionPolicy(this.policy, 'text', item.payload.source.url).ok);
+ this.gate('text', item.payload.source.url).ok);
return { item, valid };
}
@@ -1207,7 +1238,7 @@ export class BrowserExtensionBridge {
return failure('INVALID_ARGS', e instanceof Error ? e.message : 'Invalid browser action.');
}
const kind = action as BrowserExtensionAction;
- const gate = checkBrowserExtensionPolicy(this.policy, kind, payload.url);
+ const gate = this.gate(kind, payload.url);
if (!gate.ok) return { ...gate };
const until = this.now() + (this.options.connectWait ?? 6000);
while (!this.connected().length && this.now() < until)
@@ -1264,6 +1295,7 @@ export class BrowserExtensionBridge {
}
async close(): Promise<void> {
+ this.closed = true;
this.relays.clear();
for (const job of [...this.jobs.values()])
this.finish(
diff --git a/apps/desktop/src/main/browser-extension/native-binding.ts b/apps/desktop/src/main/browser-extension/native-binding.ts
index d87355423e..75b392a03e 100644
--- a/apps/desktop/src/main/browser-extension/native-binding.ts
+++ b/apps/desktop/src/main/browser-extension/native-binding.ts
@@ -89,6 +89,64 @@ export function createNativeBinding(options: NativeBindingOptions): NativeBindin
}
}
+ function browserProfiles(): string[] {
+ return (
+ options.profiles ??
+ (platform === 'darwin'
+ ? [
+ 'Google/Chrome',
+ 'Google/Chrome for Testing',
+ 'Chromium',
+ 'Microsoft Edge',
+ 'BraveSoftware/Brave-Browser',
+ ].map((p) => path.join(home, 'Library/Application Support', p))
+ : [
+ 'google-chrome',
+ 'google-chrome-for-testing',
+ 'chromium',
+ 'microsoft-edge',
+ 'BraveSoftware/Brave-Browser',
+ ].map((p) => path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), p)))
+ );
+ }
+
+ /**
+ * Withdraw the browser registrations once no Cindy still serves a connection. The registration
+ * is shared by every Cindy on this account (release and dev builds, both editions), and each
+ * running one keeps its own `connections/<port>.json`; removing it while another is live would
+ * cut that one off until it restarts.
+ */
+ async function unregisterIfUnused(): Promise<void> {
+ const live = await fs.readdir(path.join(root, 'connections')).catch(() => null);
+ if (live === null || live.some((name) => name.endsWith('.json'))) return;
+ const binaryName = 'cindy-browser-native' + (platform === 'win32' ? '.exe' : '');
+ const ours = path.join(root, binaryName);
+ if (platform === 'win32') {
+ const reg = path.join(env.SystemRoot || env.WINDIR || 'C:\\Windows', 'System32', 'reg.exe');
+ for (const vendor of ['Google\\Chrome', 'Microsoft\\Edge', 'BraveSoftware\\Brave-Browser']) {
+ await run!(
+ reg,
+ ['DELETE', 'HKCU\\Software\\' + vendor + '\\NativeMessagingHosts\\' + options.hostName, '/f'],
+ { windowsHide: true, timeout: 10000 },
+ ).catch(() => undefined);
+ }
+ await fs.rm(path.join(root, options.hostName + '.json'), { force: true });
+ return;
+ }
+ for (const profile of browserProfiles()) {
+ const file = path.join(profile, 'NativeMessagingHosts', options.hostName + '.json');
+ const registered = await fs.readFile(file, 'utf8').catch(() => null);
+ // Leave a registration that now points somewhere else (another installer took the name).
+ let target: unknown = null;
+ try {
+ target = registered === null ? null : (JSON.parse(registered) as { path?: unknown }).path;
+ } catch {
+ target = null;
+ }
+ if (target === ours) await fs.rm(file, { force: true });
+ }
+ }
+
async function install(port: number, extensionIds: readonly string[]) {
try {
await privateDirectory(root);
@@ -132,24 +190,7 @@ export function createNativeBinding(options: NativeBindingOptions): NativeBindin
);
}
} else {
- const profiles =
- options.profiles ??
- (platform === 'darwin'
- ? [
- 'Google/Chrome',
- 'Google/Chrome for Testing',
- 'Chromium',
- 'Microsoft Edge',
- 'BraveSoftware/Brave-Browser',
- ].map((p) => path.join(home, 'Library/Application Support', p))
- : [
- 'google-chrome',
- 'google-chrome-for-testing',
- 'chromium',
- 'microsoft-edge',
- 'BraveSoftware/Brave-Browser',
- ].map((p) => path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), p)));
- for (const profile of profiles) {
+ for (const profile of browserProfiles()) {
const dir = path.join(profile, 'NativeMessagingHosts');
await privateDirectory(dir);
await atomic(path.join(dir, options.hostName + '.json'), JSON.stringify(manifest));
@@ -178,6 +219,7 @@ export function createNativeBinding(options: NativeBindingOptions): NativeBindin
// 只删自己写的授权;同端口被另一实例接管时保留它的令牌。
if (data === JSON.stringify({ token })) await fs.rm(config, { force: true });
config = null;
+ await unregisterIfUnused().catch(() => undefined);
}
return { token, install, close, status: () => state };
diff --git a/apps/desktop/src/main/browser-extension/policy.ts b/apps/desktop/src/main/browser-extension/policy.ts
index 7a5cac5db6..cfe81240dd 100644
--- a/apps/desktop/src/main/browser-extension/policy.ts
+++ b/apps/desktop/src/main/browser-extension/policy.ts
@@ -93,14 +93,43 @@ export function defaultBrowserExtensionPolicy(): BrowserExtensionPolicy {
return { read: { block: [] }, interact: { allow: ['*'], block: [] } };
}
+/** DevTools methods the extension accepts for site recipes; mirrors CDP_METHODS in policy.js. */
+export const BROWSER_EXTENSION_CDP_METHODS: ReadonlySet<string> = new Set([
+ 'Accessibility.enable',
+ 'Accessibility.getFullAXTree',
+ 'DOM.enable',
+ 'DOM.focus',
+ 'DOM.getDocument',
+ 'DOM.querySelector',
+ 'DOM.querySelectorAll',
+ 'DOM.describeNode',
+ 'DOM.resolveNode',
+ 'DOM.getContentQuads',
+ 'DOM.getBoxModel',
+ 'DOM.scrollIntoViewIfNeeded',
+ 'Input.dispatchKeyEvent',
+ 'Input.dispatchMouseEvent',
+ 'Input.insertText',
+ 'Network.enable',
+ 'Network.getResponseBody',
+ 'Network.getCookies',
+ 'Storage.getCookies',
+ 'Page.captureScreenshot',
+ 'Page.getLayoutMetrics',
+ 'Page.getFrameTree',
+ 'Page.handleJavaScriptDialog',
+ 'Runtime.callFunctionOn',
+ 'Runtime.releaseObject',
+]);
+
export function normalizeBrowserExtensionHost(value: unknown): string {
if (typeof value !== 'string') throw new Error('Enter a domain, for example example.test.');
const text = value.trim().toLowerCase();
const exact = text.startsWith('=');
const raw = exact ? text.slice(1) : text.replace(/^\*\./, '');
if (/^\[[0-9a-f:.]+\]$/.test(raw)) {
+ // Local and private addresses are allowed like any site (2026-10-28), so they can be listed too.
const host = new URL('https://' + raw).hostname;
- if (isLocalBrowserHost(host)) throw new Error('Local and private addresses are not supported.');
return (exact ? '=' : '') + host;
}
if (!raw || /[\s/@:?#\\]/.test(raw))
@@ -109,14 +138,13 @@ export function normalizeBrowserExtensionHost(value: unknown): string {
// eslint-disable-next-line no-control-regex
if (host !== raw && !/[^\x00-\x7f]/.test(raw)) throw new Error('Invalid domain.');
if (
+ // Single-label intranet names (jira, localhost) are valid entries.
host.length > 253 ||
- !host.includes('.') ||
host.endsWith('.') ||
host.split('.').some((part) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(part))
) {
throw new Error('Invalid domain.');
}
- if (isLocalBrowserHost(host)) throw new Error('Local and private addresses are not supported.');
return (exact ? '=' : '') + host;
}
@@ -333,6 +361,20 @@ function validateParityPayload(action: string, payload: BrowserExtensionJobPaylo
throw new Error('cdp op must be begin, end, events or command.');
if (payload.op === 'command' && (typeof payload.method !== 'string' || !/^[A-Za-z]+\.[A-Za-z]+$/.test(payload.method)))
throw new Error('cdp command needs a protocol method such as Network.getCookies.');
+ // Mirrors the extension: only what site recipes send, and cookie reads name the site's URLs
+ // (the extension additionally keeps them to the attached tab's site).
+ if (payload.op === 'command' && !BROWSER_EXTENSION_CDP_METHODS.has(payload.method as string))
+ throw new Error('cdp command ' + String(payload.method) + ' is not available to site recipes.');
+ if (payload.op === 'command' && payload.method === 'Network.getCookies') {
+ const urls = (payload.params as { urls?: unknown } | undefined)?.urls;
+ if (
+ !Array.isArray(urls) ||
+ !urls.length ||
+ urls.length > 50 ||
+ urls.some((u) => typeof u !== 'string' || u.length > 8192 || !/^https?:\/\//i.test(u))
+ )
+ throw new Error('Network.getCookies needs params.urls: 1–50 HTTP(S) URLs of the site being operated on.');
+ }
if (
payload.params != null &&
(typeof payload.params !== 'object' || Array.isArray(payload.params) || JSON.stringify(payload.params).length > 1_000_000)
diff --git a/apps/desktop/src/main/browser-extension/relay-protocol.ts b/apps/desktop/src/main/browser-extension/relay-protocol.ts
index bb711bfa78..ef14fb345f 100644
--- a/apps/desktop/src/main/browser-extension/relay-protocol.ts
+++ b/apps/desktop/src/main/browser-extension/relay-protocol.ts
@@ -125,6 +125,13 @@ export function validateRelayRequest(input: unknown): RelayRequest {
if (!raw || typeof raw.op !== 'string' || !OPERATIONS.has(raw.op))
throw new Error('INVALID_OPERATION');
const out: RelayRequest = { op: raw.op, source: source(raw.source) };
+ // The tab or document the request came from, so per-view state (the current video's subtitle
+ // task) is not shared across tabs. Opaque to the host; mirrors the plugin's learning-core rule.
+ if (raw.view !== undefined) {
+ if (typeof raw.view !== 'string' || !/^[A-Za-z0-9:_-]{1,64}$/.test(raw.view))
+ throw new Error('INVALID_INPUT');
+ out.view = raw.view;
+ }
if (raw.target !== undefined) {
if (!validTarget(raw.target)) throw new Error('INVALID_LANGUAGE');
out.target = raw.target;
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts
index fc288459f2..39c5b67ac8 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts
@@ -37,7 +37,7 @@ function extGhost(
version?: string;
} = {},
): InstalledGhost {
- const id = options.id ?? 'ext-ghost';
+ const id = options.id ?? 'my-browser';
return {
manifest: {
schemaVersion: 3,
@@ -45,13 +45,14 @@ function extGhost(
name: 'Ext Ghost',
version: options.version ?? '1.0.0',
entry: 'main.js',
+ node: { entry: 'node/worker.cjs' },
...(options.declare !== false
? {
browserExtension: {
protocol: 'cindy-browser-extension/3',
extensionIds: [CHROME_ID],
...(options.nativeHost !== false
- ? { nativeHost: { name: 'com.example.browser', binary: 'native-host/bin' } }
+ ? { nativeHost: { name: 'com.makecindy.browser', binary: 'native-host/bin' } }
: {}),
...(options.pageControl !== false ? { pageControl: true as const } : {}),
},
@@ -187,14 +188,14 @@ describe('browserExtensionSlot · 桥接随花名册启停', () => {
await settle();
expect(bridges).toHaveLength(1);
expect(bridges[0].options).toMatchObject({
- ghostId: 'ext-ghost',
+ ghostId: 'my-browser',
installedVersion: '1.0.0',
extensionIds: [CHROME_ID],
nativeToken: 'f'.repeat(64),
});
expect(bridges[0].started).toBe(true);
expect(natives[0].install).toHaveBeenCalledWith(18810, [CHROME_ID]);
- expect(slot.getPageControl()).toMatchObject({ ghostId: 'ext-ghost', pluginName: 'Ext Ghost' });
+ expect(slot.getPageControl()).toMatchObject({ ghostId: 'my-browser', pluginName: 'Ext Ghost' });
// 幂等:同一份花名册不重建。
slot.reconcile(ghosts);
await settle();
@@ -214,6 +215,19 @@ describe('browserExtensionSlot · 桥接随花名册启停', () => {
expect(slot.getPageControl()).toBeNull();
});
+ // Native hosts run outside the sandbox and share one registration per account, so a plugin that
+ // is not the official Cindy Chrome must not get one, even under the official name.
+ it('只有官方 Cindy Chrome 能装 native host;其它插件声明了也只开桥接', async () => {
+ const ghosts = [extGhost({ id: 'impostor' })];
+ const { slot, bridges, natives, settle } = await makeSlot({}, ghosts);
+ slot.reconcile(ghosts);
+ await settle();
+ expect(bridges).toHaveLength(1);
+ expect(bridges[0].started).toBe(true);
+ expect(bridges[0].options.nativeToken).toBeUndefined();
+ expect(natives).toHaveLength(0);
+ });
+
it('没有 pageControl 的声明只做通道,不成为 Browser Use 执行端', async () => {
const ghosts = [extGhost({ pageControl: false, nativeHost: false })];
const { slot, bridges, natives, settle } = await makeSlot({}, ghosts);
@@ -242,7 +256,7 @@ describe('browserExtensionSlot · 管子上行', () => {
ok: false,
errorCode: 'PERMISSION_DENIED',
});
- expect(await slot.handleRequest('_root__ext-ghost', { kind: 'status' })).toMatchObject({
+ expect(await slot.handleRequest('_root__my-browser', { kind: 'status' })).toMatchObject({
ok: false,
errorCode: 'HOST_NOT_READY',
});
@@ -252,7 +266,7 @@ describe('browserExtensionSlot · 管子上行', () => {
const { slot, bridges, dir, ghosts, settle } = await makeSlot();
slot.reconcile(ghosts);
await settle();
- const id = '_root__ext-ghost';
+ const id = '_root__my-browser';
expect(await slot.handleRequest(id, 'nope')).toMatchObject({
ok: false,
errorCode: 'INVALID_REQUEST',
@@ -284,7 +298,7 @@ describe('browserExtensionSlot · 管子上行', () => {
});
expect(
JSON.parse(await fs.readFile(path.join(dir, encodeURIComponent(id) + '.json'), 'utf8')),
- ).toEqual({ version: 1, policy });
+ ).toEqual({ version: 1, policy, trustedClients: [] });
expect(await slot.handleRequest(id, { kind: 'setTrustedClients', clients: [] })).toEqual({
ok: true,
});
@@ -310,12 +324,30 @@ describe('browserExtensionSlot · 管子上行', () => {
ok: false,
errorCode: 'INVALID_REQUEST',
});
- // 重启(新槽、同目录):先恢复上次策略再 start。
+ // 重启(新槽、同目录):先恢复配对与上次策略再 start,不再向插件索要策略。
const again = await makeSlot({ policyDir: () => dir });
again.slot.reconcile(again.ghosts);
- await again.settle();
- expect(again.bridges[0].calls[0]).toEqual(['setPolicy', [policy]]);
- expect(again.bridges[0].started).toBe(true);
+ await vi.waitFor(() => expect(again.bridges[0]?.started).toBe(true));
+ expect(again.bridges[0].calls.slice(0, 2)).toEqual([
+ ['setTrustedClients', [[]]],
+ ['setPolicy', [policy]],
+ ]);
+ expect(again.sent.some(([, payload]) => (payload as { name?: string }).name === 'browser-extension-policy-request')).toBe(false);
+ });
+
+ // Review 2026-10-29: with no cached policy the host bridge must not fall back to "allow every
+ // site" while the plugin still holds the user's blocklist; it waits and asks the plugin.
+ it('没有缓存策略时让桥接等待策略并向插件索要;配对随策略一起落盘', async () => {
+ const { slot, bridges, sent, dir } = await makeSlot();
+ slot.reconcile([extGhost()]);
+ await vi.waitFor(() => expect(bridges[0]?.started).toBe(true));
+ expect(bridges[0].options.awaitPolicy).toBe(true);
+ expect(sent).toContainEqual(['_root__my-browser', { type: 'event', name: 'browser-extension-policy-request' }]);
+ const clients = [{ id: 'c1', origin: 'chrome-extension://' + CHROME_ID, extensionId: CHROME_ID, publicKey: 'k' }];
+ expect(await slot.handleRequest('_root__my-browser', { kind: 'setTrustedClients', clients })).toEqual({ ok: true });
+ expect(
+ JSON.parse(await fs.readFile(path.join(dir, encodeURIComponent('_root__my-browser') + '.json'), 'utf8')),
+ ).toEqual({ version: 1, trustedClients: clients });
});
});
@@ -334,6 +366,7 @@ describe('browserExtensionSlot · 转交扩展请求', () => {
}),
wake,
});
+ const relays = () => sent.filter(([, payload]) => (payload as { name?: string }).name === 'browser-extension-relay');
slot.reconcile(ghosts);
await settle();
const notice = {
@@ -343,9 +376,9 @@ describe('browserExtensionSlot · 转交扩展请求', () => {
};
bridges[0].emitRelay(notice);
await settle();
- expect(sent).toHaveLength(1);
- expect(sent[0][0]).toBe('_root__ext-ghost');
- expect(sent[0][1]).toMatchObject({
+ expect(relays()).toHaveLength(1);
+ expect(relays()[0][0]).toBe('_root__my-browser');
+ expect(relays()[0][1]).toMatchObject({
type: 'event',
name: 'browser-extension-relay',
id: 'req-1',
@@ -356,12 +389,12 @@ describe('browserExtensionSlot · 转交扩展请求', () => {
bridges[0].emitRelay({ ...notice, id: 'req-2' });
await settle();
expect(wake).toHaveBeenCalledOnce();
- expect(sent).toHaveLength(2);
+ expect(relays()).toHaveLength(2);
online = false;
wake.mockResolvedValueOnce(false);
bridges[0].emitRelay({ ...notice, id: 'req-3' });
await settle();
- expect(sent).toHaveLength(2);
+ expect(relays()).toHaveLength(2);
expect(bridges[0].calls.at(-1)).toEqual([
'relayResult',
['req-3', { ok: false, error: 'PLUGIN_UNAVAILABLE' }],
diff --git a/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts b/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts
index 7ff58dd316..572a976a09 100644
--- a/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts
@@ -13,14 +13,17 @@
* - 身份:允许连接的扩展 id 来自身份卡(装入时展示并钉死),宿主代码里不出现任何
* 具体插件名;native host 的授权令牌只写本机私有连接文件;
* - 策略归插件:站点策略由插件保存并推送(setPolicy),宿主只缓存、持久化到
- * owner 私有目录并在每个作业上强制;宿主重启后先恢复上次策略再接受连接,
- * 没有策略时按线协议默认值(读开放公网、交互开放,本机/私网拒绝);
+ * owner 私有目录并在每个作业上强制;宿主重启后先恢复上次策略与配对再接受连接,
+ * 没有可用缓存时桥接在收到插件策略前拒绝页面作业,并向插件索要策略;
+ * - native host 在插件沙箱外运行且全账号共用一份注册,只为官方 Cindy Chrome 安装
+ * (见 OFFICIAL_NATIVE_HOSTS,宿主唯一点名具体插件的地方);
* - 转交请求只投递给声明该扩展的插件(沙箱内处理),宿主不解释其业务内容。
*
* 纯逻辑 + 依赖注入(规则 14):ghost 查询、管子投递、目录与桥接工厂在
* cindy-brain/index.ts 组装时注入。
*/
+import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
@@ -47,6 +50,27 @@ import {
import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
import type { UserBrowserPageControl } from '../mcp-integrations/browser-backend/user-browser-backend.js';
+/**
+ * Native Messaging hosts run outside the plugin sandbox and every Cindy on the account shares
+ * their registration, so only the official Cindy Chrome plugin may install one, under its own
+ * name. It must also declare its bundled Node program, which the install confirmation already
+ * presents as running unsandboxed. Any other declaration is ignored: the bridge still runs and
+ * the extension falls back to pairing.
+ */
+const OFFICIAL_NATIVE_HOSTS: ReadonlyMap<string, string> = new Map([
+ ['my-browser', 'com.makecindy.browser'],
+]);
+
+export function mayInstallNativeHost(ghost: InstalledGhost): boolean {
+ const name = ghost.manifest.browserExtension?.nativeHost?.name;
+ return (
+ name !== undefined &&
+ ghost.namespace == null &&
+ OFFICIAL_NATIVE_HOSTS.get(ghost.manifest.id) === name &&
+ ghost.manifest.node !== undefined
+ );
+}
+
export interface BrowserExtensionSlotDeps {
getGhost(id: string): InstalledGhost | null;
/** 把转交事件投到插件逻辑页;false = 逻辑页不在线。 */
@@ -74,6 +98,17 @@ interface Entry {
native: NativeBinding | null;
ready: Promise<void>;
closing: boolean;
+ /** Bumped per setPolicy; only the newest request may persist, however long older ones waited. */
+ policyRevision: number;
+ /** Last applied policy and paired clients, persisted together. */
+ saved: SavedBrowserExtensionState;
+ /** Serialises cache writes so an older write cannot land after a newer one. */
+ writes: Promise<void>;
+}
+
+interface SavedBrowserExtensionState {
+ policy: BrowserExtensionPolicy | null;
+ trustedClients: unknown[];
}
function fail(
@@ -121,7 +156,12 @@ export class GhostBrowserExtensionSlot {
private start(instanceId: string, ghost: InstalledGhost, ownerScopeKey: string): void {
const needs = ghost.manifest.browserExtension!;
- const native = needs.nativeHost
+ if (needs.nativeHost && !mayInstallNativeHost(ghost))
+ this.deps.log?.warn('browser extension native host ignored: only the official plugin may install one', {
+ instanceId,
+ hostName: needs.nativeHost.name,
+ });
+ const native = needs.nativeHost && mayInstallNativeHost(ghost)
? (this.deps.createNativeBinding ?? createNativeBinding)({
hostName: needs.nativeHost.name,
binaryDir: path.join(ghost.dir, needs.nativeHost.binary),
@@ -129,6 +169,7 @@ export class GhostBrowserExtensionSlot {
: null;
const bridge = (this.deps.createBridge ?? ((options) => new BrowserExtensionBridge(options)))({
ghostId: ghost.manifest.id,
+ awaitPolicy: true,
installedVersion: ghost.manifest.version,
extensionIds: needs.extensionIds,
...(native ? { nativeToken: native.token } : {}),
@@ -144,20 +185,41 @@ export class GhostBrowserExtensionSlot {
native,
ready: Promise.resolve(),
closing: false,
+ policyRevision: 0,
+ saved: { policy: null, trustedClients: [] },
+ writes: Promise.resolve(),
};
entry.ready = (async () => {
- const saved = await this.readPolicy(instanceId);
+ const saved = await this.readSaved(instanceId);
+ let restored = false;
if (saved) {
+ entry.saved = saved;
try {
- await bridge.setPolicy(saved);
+ // Paired clients first, so an extension paired before the restart is not sent back to
+ // pairing while the plugin is still starting.
+ bridge.setTrustedClients(saved.trustedClients);
} catch (err) {
- this.deps.log?.warn('browser extension saved policy rejected; using defaults', {
+ this.deps.log?.warn('browser extension saved pairings rejected', {
instanceId,
error: errorText(err),
});
}
+ if (saved.policy) {
+ try {
+ await bridge.setPolicy(saved.policy);
+ restored = true;
+ } catch (err) {
+ this.deps.log?.warn('browser extension saved policy rejected; waiting for the plugin', {
+ instanceId,
+ error: errorText(err),
+ });
+ }
+ }
}
await bridge.start();
+ // Without a usable cached policy the bridge refuses page jobs; ask the plugin to push its
+ // stored permissions now instead of at its next tool call.
+ if (!restored) void this.requestPolicy(instanceId);
if (native) {
const installed = await native.install(bridge.listeningPort, needs.extensionIds);
if (!installed.ok)
@@ -287,17 +349,22 @@ export class GhostBrowserExtensionSlot {
} catch (err) {
return fail('INVALID_REQUEST', errorText(err));
}
+ const revision = ++entry.policyRevision;
const applied = await entry.bridge.setPolicy(policy);
- if (applied.ok || applied.applied === true)
- await this.writePolicy(entry.instanceId, policy);
+ if ((applied.ok || applied.applied === true) && revision === entry.policyRevision)
+ await this.persist(entry, { policy });
return applied as GhostPipeBrowserExtensionResult;
}
- case 'setTrustedClients':
+ case 'setTrustedClients': {
+ let applied: { ok: true };
try {
- return entry.bridge.setTrustedClients(req.clients);
+ applied = entry.bridge.setTrustedClients(req.clients);
} catch (err) {
return fail('INVALID_REQUEST', errorText(err));
}
+ await this.persist(entry, { trustedClients: Array.isArray(req.clients) ? req.clients : [] });
+ return applied;
+ }
case 'relayActive':
if (typeof req.id !== 'string') return fail('INVALID_REQUEST', 'relayActive 需要 id');
return entry.bridge.relayActive(req.id);
@@ -347,33 +414,76 @@ export class GhostBrowserExtensionSlot {
return path.join(this.deps.policyDir(), encodeURIComponent(instanceId) + '.json');
}
- private async readPolicy(instanceId: string): Promise<BrowserExtensionPolicy | null> {
+ /** Saved permissions and pairings; null when missing or unreadable (treated as unknown). */
+ private async readSaved(instanceId: string): Promise<SavedBrowserExtensionState | null> {
try {
const raw = JSON.parse(await fs.readFile(this.policyFile(instanceId), 'utf8')) as {
version?: unknown;
policy?: unknown;
+ trustedClients?: unknown;
};
if (raw?.version !== 1) return null;
- return normalizeBrowserExtensionPolicy(raw.policy);
+ let policy: BrowserExtensionPolicy | null = null;
+ if (raw.policy !== undefined) {
+ try {
+ policy = normalizeBrowserExtensionPolicy(raw.policy);
+ } catch {
+ policy = null;
+ }
+ }
+ return {
+ policy,
+ trustedClients: Array.isArray(raw.trustedClients) ? raw.trustedClients : [],
+ };
} catch {
return null;
}
}
- private async writePolicy(instanceId: string, policy: BrowserExtensionPolicy): Promise<void> {
+ private persist(entry: Entry, change: Partial<SavedBrowserExtensionState>): Promise<void> {
+ entry.saved = { ...entry.saved, ...change };
+ const snapshot = entry.saved;
+ entry.writes = entry.writes.then(() => this.writeSaved(entry.instanceId, snapshot));
+ return entry.writes;
+ }
+
+ private async writeSaved(instanceId: string, saved: SavedBrowserExtensionState): Promise<void> {
+ const file = this.policyFile(instanceId);
+ const tmp = `${file}.${crypto.randomUUID()}.tmp`;
try {
- const file = this.policyFile(instanceId);
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
- const tmp = file + '.tmp';
- await fs.writeFile(tmp, JSON.stringify({ version: 1, policy }), { mode: 0o600 });
+ await fs.writeFile(
+ tmp,
+ JSON.stringify({
+ version: 1,
+ ...(saved.policy ? { policy: saved.policy } : {}),
+ trustedClients: saved.trustedClients,
+ }),
+ { mode: 0o600 },
+ );
await fs.rename(tmp, file);
} catch (err) {
+ await fs.rm(tmp, { force: true }).catch(() => undefined);
this.deps.log?.warn('browser extension policy not persisted', {
instanceId,
error: errorText(err),
});
}
}
+
+ /** Ask the plugin to push its stored permissions: wake it when offline, else send a request. */
+ private async requestPolicy(instanceId: string): Promise<void> {
+ const payload = { type: 'event', name: 'browser-extension-policy-request' };
+ try {
+ if (this.deps.sendToGhost(instanceId, payload)) return;
+ if (this.deps.wake && (await this.deps.wake(instanceId))) this.deps.sendToGhost(instanceId, payload);
+ } catch (err) {
+ this.deps.log?.warn('browser extension policy request failed', {
+ instanceId,
+ error: errorText(err),
+ });
+ }
+ }
}
function errorText(err: unknown): string {
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/user-browser-backend.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/user-browser-backend.test.ts
index 8209fca511..a9dc0c68a7 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/user-browser-backend.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/user-browser-backend.test.ts
@@ -482,7 +482,12 @@ describe('UserBrowserBackend · 读取与动作', () => {
expect(userBrowserCapabilities(fakeControl({ version: '0.4.43' }).control)).toBe(
USER_BROWSER_PARITY_CAPABILITIES,
);
- expect(userBrowserCapabilities(null)).toBe(USER_BROWSER_CAPABILITIES);
+ // Not connected (reloading, reconnecting) means unknown, not "old": the backend reports the
+ // disconnect per job instead of the tool layer refusing screenshots with a misleading hint.
+ expect(userBrowserCapabilities(null)).toBe(USER_BROWSER_PARITY_CAPABILITIES);
+ expect(userBrowserCapabilities(fakeControl({ clients: [] }).control)).toBe(
+ USER_BROWSER_PARITY_CAPABILITIES,
+ );
});
it('新版扩展:open 开到后台窗口并按 tabId 寻址,不再逐次列标签页', async () => {
@@ -741,11 +746,68 @@ describe('UserBrowserBackend · 读取与动作', () => {
const realStatus = (fake.control.bridge as unknown as { status: () => Promise<{ ok: boolean; clients: Array<{ connected: boolean }> }> }).status;
(fake.control.bridge as unknown as { status: () => Promise<unknown> }).status = async () => {
const s = await realStatus();
- return ++calls < 3 ? { ...s, clients: s.clients.map((c) => ({ ...c, connected: false })) } : s;
+ // Connected first, then dropped for two reads (an extension reload), then back.
+ ++calls;
+ return calls === 2 || calls === 3 ? { ...s, clients: s.clients.map((c) => ({ ...c, connected: false })) } : s;
};
const b = new UserBrowserBackend({ getPageControl: () => fake.control, reconnectWaitMs: 5000, logger: { info: vi.fn(), warn: vi.fn() } });
expect(await call(b, { action: 'status' })).toMatchObject({ ok: true, data: { connected: true } });
- expect(calls).toBe(3);
+ expect(await call(b, { action: 'status' })).toMatchObject({ ok: true, data: { connected: true } });
+ expect(calls).toBe(4);
+ });
+
+ // Review 2026-10-29: an installed but unpaired extension waited 8 s and was then told to install
+ // the extension; it must be reported at once with its real reason.
+ // Review 2026-10-29: with many tabs the list is cut at its limit, and the handle of a tab the
+ // agent had just opened vanished because it was not in the truncated list.
+ it('标签页列表被截断时不丢掉没列出来的已记住标签', async () => {
+ const fake = fakeControl({ version: '0.4.46' });
+ fake.responses.set('open', (payload) => ({ ok: true, tabId: 42, window: 500, url: payload.url, title: 'New' }));
+ const b = backend(fake.control);
+ await call(b, { action: 'open', url: 'https://example.test/new', label: 'n' });
+ fake.responses.set('tabs', () => ({
+ ok: true,
+ tabs: [{ id: 7, url: 'https://example.test/a', title: 'A', active: true }],
+ truncated: true,
+ }));
+ await call(b, { action: 'tabs' });
+ await call(b, { action: 'act', targetId: 'n', request: { kind: 'click', ref: 'r1' } });
+ expect(fake.jobs.at(-1)).toMatchObject(['click', { tabId: 42 }]);
+ });
+
+ // Review 2026-10-29: tab ids start over after a browser restart while the client id stays, so a
+ // remembered handle could act on a tab the user restored.
+ it('浏览器重启(启动 id 变化)后忘掉之前记住的标签页', async () => {
+ const fake = fakeControl({ version: '0.4.46' });
+ let boot = '11111111-1111-1111-1111-111111111111';
+ const connected = fake.control.bridge.connectedClients.bind(fake.control.bridge);
+ (fake.control.bridge as unknown as { connectedClients: () => unknown[] }).connectedClients = () =>
+ connected().map((c) => ({ ...c, boot }));
+ fake.responses.set('open', (payload) => ({ ok: true, tabId: 42, window: 500, url: payload.url, title: 'New' }));
+ const b = backend(fake.control);
+ await call(b, { action: 'open', url: 'https://example.test/new', label: 'n' });
+ boot = '22222222-2222-2222-2222-222222222222';
+ const before = fake.jobs.length;
+ const result = await call(b, { action: 'act', targetId: 'n', request: { kind: 'click', ref: 'r1' } });
+ expect(result.ok).toBe(false);
+ expect(fake.jobs.slice(before).some(([action]) => action === 'click')).toBe(false);
+ });
+
+ it('扩展已连上但没配对时 status 立即说明需要配对,不空等', async () => {
+ const fake = fakeControl({ version: '0.4.46' });
+ const realStatus = (fake.control.bridge as unknown as { status: () => Promise<{ ok: boolean; clients: Array<Record<string, unknown>> }> }).status;
+ (fake.control.bridge as unknown as { status: () => Promise<unknown> }).status = async () => {
+ const s = await realStatus();
+ return { ...s, clients: s.clients.map((c) => ({ ...c, connected: false, trusted: false })) };
+ };
+ (fake.control.bridge as unknown as { connectedClients: () => unknown[] }).connectedClients = () => [];
+ const b = new UserBrowserBackend({ getPageControl: () => fake.control, reconnectWaitMs: 60_000, logger: { info: vi.fn(), warn: vi.fn() } });
+ const started = Date.now();
+ expect(await call(b, { action: 'status' })).toMatchObject({
+ ok: true,
+ data: { connected: false, reason: 'pairing-required' },
+ });
+ expect(Date.now() - started).toBeLessThan(1000);
});
it('从没连过扩展时 status 立即报告未连接,不空等', async () => {
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/user-browser-backend.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/user-browser-backend.ts
index c5b3d4a774..eca57279f8 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/user-browser-backend.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/user-browser-backend.ts
@@ -57,6 +57,8 @@ interface TargetRecord {
tabId: number;
url: string;
title?: string;
+ /** Browser launch the tab id belongs to; see forgetRestartedBrowsers. */
+ boot?: string;
}
export const USER_BROWSER_UNSUPPORTED_HINT =
@@ -106,11 +108,17 @@ export function extensionSupportsParity(version: string | null | undefined): boo
return true;
}
-/** 任一已连接的扩展是新版就给完整能力;具体作业落到旧版连接时再逐个拒绝。 */
+/**
+ * 任一已连接的扩展是新版就给完整能力;具体作业落到旧版连接时再逐个拒绝。
+ * 没有连接(断开、重连中、扩展刚刷新)时也按完整能力报:能力未知不等于不支持,
+ * 否则截图、evaluate 等会在工具层被直接拒绝,还错误地建议换专用浏览器;
+ * 真正的断开由后端按作业报告(并享有重连等待)。只有全部连接都是旧版时才收窄。
+ */
export function userBrowserCapabilities(
control: UserBrowserPageControl | null,
): Readonly<Record<keyof typeof USER_BROWSER_CAPABILITIES, boolean>> {
- return control?.bridge.connectedClients().some((c) => extensionSupportsParity(c.version))
+ const clients = control?.bridge.connectedClients() ?? [];
+ return clients.length === 0 || clients.some((c) => extensionSupportsParity(c.version))
? USER_BROWSER_PARITY_CAPABILITIES
: USER_BROWSER_CAPABILITIES;
}
@@ -181,6 +189,9 @@ const NOT_CONFIGURED_MESSAGE =
const DISCONNECTED_MESSAGE =
'浏览器扩展未连接:请在用户的 Chrome / Edge 中安装并启用 Cindy 扩展,保持 Cindy 运行;连接后重新查询 status。';
+const UNPAIRED_MESSAGE =
+ '浏览器扩展已连到 Cindy,但还没完成配对或授权:请让用户在 Cindy Chrome 插件页确认这个浏览器,或重新启用插件后再查询 status。';
+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export class UserBrowserBackend implements BrowserBackend {
@@ -189,6 +200,9 @@ export class UserBrowserBackend implements BrowserBackend {
private readonly recipeSessions = new RecipeBrowserSessions();
/** 任务(会话)→ 它操作过的标签页;任务停下时清掉这些页面上的「Cindy 正在操作」标记。 */
private readonly sessionTabs = new Map<string, Map<string, { clientId: string; tabId: number }>>();
+ private readonly clientBoots = new Map<string, string>();
+ /** Clients that have been fully connected before: only these are worth a reconnect wait. */
+ private readonly everReady = new Set<string>();
/** 配方会话 id → 取回扩展缓存的网络事件(事件随每条命令回传,读取抓包前再取一次)。 */
private readonly recipePumps = new Map<string, () => Promise<void>>();
private nextAlias = 1;
@@ -309,7 +323,28 @@ export class UserBrowserBackend implements BrowserBackend {
}
private connectedClients(control: UserBrowserPageControl): BrowserExtensionClientInfo[] {
- return control.bridge.connectedClients();
+ const clients = control.bridge.connectedClients();
+ this.forgetRestartedBrowsers(clients);
+ for (const client of clients) if (client.connected) this.everReady.add(client.id);
+ return clients;
+ }
+
+ /**
+ * Tab ids start over when the browser restarts while the client id stays the same, so a
+ * remembered handle could reach a tab the user restored. Forget a browser's handles once its
+ * launch id changes. Older extensions send no launch id and keep the previous behaviour.
+ */
+ private forgetRestartedBrowsers(clients: readonly BrowserExtensionClientInfo[]): void {
+ for (const client of clients) {
+ if (!client.boot) continue;
+ const known = this.clientBoots.get(client.id);
+ this.clientBoots.set(client.id, client.boot);
+ if (known === undefined || known === client.boot) continue;
+ for (const [targetId, record] of this.targets)
+ if (record.clientId === client.id) this.targets.delete(targetId);
+ for (const tabs of this.sessionTabs.values())
+ for (const [targetId, tab] of tabs) if (tab.clientId === client.id) tabs.delete(targetId);
+ }
}
/** 这条连接的扩展是否已与专用浏览器对齐(按 tabId 寻址、提供完整动作)。 */
@@ -445,6 +480,8 @@ export class UserBrowserBackend implements BrowserBackend {
private resolveTarget(id: string | undefined): TargetRecord | null {
if (!id) return null;
+ const control = this.opts.getPageControl();
+ if (control) this.forgetRestartedBrowsers(control.bridge.connectedClients());
const direct = this.targets.get(id);
if (direct) return direct;
for (const record of this.targets.values()) {
@@ -551,10 +588,12 @@ export class UserBrowserBackend implements BrowserBackend {
// Right after an extension reload or update it reconnects within seconds: wait briefly before
// reporting "not connected", so the agent does not give up on a browser that is coming back.
const deadline = (this.opts.now ?? Date.now)() + (this.opts.reconnectWaitMs ?? 8000);
- // Only an extension seen recently (now dropped) is worth waiting for; none at all is reported at once.
+ // Only an extension that was connected before (now dropped) is worth waiting for. One that never
+ // finished connecting, such as an unpaired install, is reported at once with its own reason.
+ if (status.ok) for (const c of status.clients) if (c.connected) this.everReady.add(c.id);
while (
status.ok &&
- status.clients.length > 0 &&
+ status.clients.some((c) => this.everReady.has(c.id)) &&
!status.clients.some((c) => c.connected) &&
(this.opts.now ?? Date.now)() < deadline
) {
@@ -583,6 +622,8 @@ export class UserBrowserBackend implements BrowserBackend {
fullFeatures: extensionSupportsParity(c.version),
}));
const outdatedClients = clients.filter((c) => !c.fullFeatures);
+ // Installed and reaching Cindy, but not allowed in yet: say so instead of "install the extension".
+ const unpaired = clients.length === 0 && status.clients.some((c) => !c.trusted);
return actionOk(req.action, {
ready: clients.length > 0,
running: clients.length > 0,
@@ -592,7 +633,8 @@ export class UserBrowserBackend implements BrowserBackend {
pluginName: control.pluginName,
connected: clients.length > 0,
clients,
- ...(clients.length === 0 ? { message: DISCONNECTED_MESSAGE } : {}),
+ ...(clients.length === 0 ? { message: unpaired ? UNPAIRED_MESSAGE : DISCONNECTED_MESSAGE } : {}),
+ ...(unpaired ? { reason: 'pairing-required' } : {}),
...(outdatedClients.length
? {
updateNote: `有 ${outdatedClients.length} 个连接的 Cindy 扩展低于 ${USER_BROWSER_PARITY_VERSION},只支持基础读取与交互;更新扩展后可用截图、上传、页面脚本等完整能力。`,
@@ -654,17 +696,23 @@ export class UserBrowserBackend implements BrowserBackend {
return actionFailed(req.action, DISCONNECTED_MESSAGE, 'BROWSER_RUNTIME_UNAVAILABLE');
const tabs: Array<Record<string, unknown>> = [];
const seen = new Set<string>();
+ // Only a complete listing proves a remembered tab is gone; a truncated one (many tabs, size
+ // budget) would otherwise turn a tab the agent just opened into an unknown targetId.
+ const complete = new Set<string>();
for (const client of clients) {
const listed = await gate.control.bridge.act('tabs', {
browser: client.id,
limit: Math.min(100, Math.max(1, req.limit ?? 50)),
});
if (!listed.ok) return this.failureResult(req.action, listed);
+ if (listed.truncated !== true) complete.add(client.id);
for (const tab of (Array.isArray(listed.tabs) ? listed.tabs : []) as Array<
Record<string, unknown>
>) {
if (typeof tab.id !== 'number') continue;
if (tab.redacted || typeof tab.url !== 'string') {
+ // Still open, only its details are withheld: keep any remembered handle.
+ seen.add(this.targetKey(client.id, tab.id));
tabs.push({
targetId: this.targetKey(client.id, tab.id),
redacted: true,
@@ -689,8 +737,7 @@ export class UserBrowserBackend implements BrowserBackend {
}
// 已关闭的标签页从映射里清掉,别名不复用。
for (const [targetId, record] of this.targets) {
- if (clients.some((c) => c.id === record.clientId) && !seen.has(targetId))
- this.targets.delete(targetId);
+ if (complete.has(record.clientId) && !seen.has(targetId)) this.targets.delete(targetId);
}
return actionOk(req.action, {
backend: this.kind,
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index c8d264927e..ed9dbd1130 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -1,4 +1,6 @@
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { readInstalledGhostsSnapshot } from '@/cindy-brain/useInstalledGhosts';
+import { installedGhostStoragePart, resolvePluginInstanceQuery } from '../../../shared/pluginIdentity';
import { drainPendingDeepLinks } from '@/lib/pendingDeepLinks';
import { ChatInviteHost, reportMalformedChatInvite, requestChatInvite } from '@/features/bots/ChatInviteHost';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
@@ -768,7 +770,16 @@ export function MainLayout() {
return;
}
if (payload.type === 'installed-plugin') {
- navigate(payload.ghostId ? `/plugins?ghost=${encodeURIComponent(payload.ghostId)}` : '/plugins');
+ // The link carries the plugin's own id; the plugin page selects by instance key
+ // (`_root__my-browser`), so resolve it against what is installed.
+ const resolved = payload.ghostId
+ ? resolvePluginInstanceQuery(readInstalledGhostsSnapshot(), payload.ghostId)
+ : null;
+ navigate(
+ resolved?.status === 'unique'
+ ? `/plugins?ghost=${encodeURIComponent(installedGhostStoragePart(resolved.ghost))}`
+ : '/plugins',
+ );
return;
}
if (payload.type === 'session') {
diff --git a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
index d1c006278f..ffb50a589e 100644
--- a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
@@ -462,9 +462,19 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
useInstalledGhosts().find((ghost) => ghost.manifest.id === RECOMMENDED_PAGE_CONTROL_PLUGIN_ID) ??
null;
const [userBrowserSetupBusy, setUserBrowserSetupBusy] = useState(false);
+ const browserBackendHealthSeqRef = useRef(0);
+ const browserBackendKindRef = useRef(browserBackendKind);
+ browserBackendKindRef.current = browserBackendKind;
const refreshUserBrowserHealth = useCallback(async () => {
+ const seq = browserBackendHealthSeqRef.current;
const next = await window.electronAPI.browserBackend?.getHealth?.().catch(() => null);
- if (next?.active === 'user-browser') setBrowserBackendHealth(next);
+ // A switch, recovery or newer read may have landed meanwhile (one read can take seconds);
+ // a late "My browser" answer must not replace the sidebar browser's state.
+ if (seq !== browserBackendHealthSeqRef.current || browserBackendKindRef.current !== 'user-browser') return;
+ if (next?.active === 'user-browser') {
+ browserBackendHealthSeqRef.current += 1;
+ setBrowserBackendHealth(next);
+ }
}, []);
// Step 1 happens right here: install the plugin from the market (Main still shows its usual
// permission confirmation) or turn it on, then re-check so the guidance moves on to step 2.
@@ -533,15 +543,24 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
// guidance turns into "connected" as soon as the user finishes a step elsewhere.
useEffect(() => {
if (browserBackendKind !== 'user-browser' || browserBackendHealth?.status !== 'error') return;
- const timer = setInterval(() => void refreshUserBrowserHealth(), 3000);
- return () => clearInterval(timer);
+ // Schedule the next check only after the previous one finished, so slow reads never pile up.
+ let stopped = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const tick = async () => {
+ await refreshUserBrowserHealth();
+ if (!stopped) timer = setTimeout(() => void tick(), 3000);
+ };
+ timer = setTimeout(() => void tick(), 3000);
+ return () => {
+ stopped = true;
+ clearTimeout(timer);
+ };
}, [browserBackendKind, browserBackendHealth?.status, refreshUserBrowserHealth]);
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.
- const browserBackendHealthSeqRef = useRef(0);
useEffect(() => {
let cancelled = false;
@@ -676,6 +695,8 @@ export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
if (browserBackendPending) return;
if (browserBackendKind === kind) return;
const prev = browserBackendKind;
+ // Results of reads started for the previous browser no longer apply.
+ browserBackendHealthSeqRef.current += 1;
setBrowserBackendKind(kind);
setBrowserBackendPending(true);
try {
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 743f4206c0..c8d95f391b 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -131,12 +131,16 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
- `browserExtension` 是宿主承接随包浏览器扩展连接的直接字段(2026-10-27 由 Cindy Chrome
插件自带接线进程迁入宿主):`protocol` 必须是当前宿主实现的 `cindy-browser-extension/3`,
`extensionIds` 是允许连接的扩展 id(装入时逐条展示并钉死),可选 `nativeHost{name,binary}`
- 由宿主复制包内平台二进制并注册 Native Messaging,可选 `pageControl: true` 表示扩展实现
+ 由宿主复制包内平台二进制并注册 Native Messaging:该程序在插件沙箱外运行且同一账号的所有
+ Cindy 共用一份注册,宿主只为官方 Cindy Chrome(`my-browser`、`com.makecindy.browser`、
+ 声明了 Node 程序)安装,其它插件的声明被忽略(2026-10-29 决定,宿主代码点名具体插件的唯一
+ 例外);注册在没有任何运行中的 Cindy 仍在使用时撤销。可选 `pageControl: true` 表示扩展实现
页面控制契约、可作为 Browser Use 的「我的浏览器」执行端。宿主代码里不得出现具体插件名
或专有协议:桥接按声明启停(`cindy-brain/browserExtensionSlot.ts`),扩展发起的请求经
`browser-extension-relay` 事件转交给声明插件,插件经 `browser-extension-request` 投递作业、
推送站点策略与配对身份。站点策略归插件所有,宿主只缓存到 owner 私有目录并在每个作业上
- 强制;新增 id 或新增 `pageControl` 视为权限变多,删减视为收权。
+ 强制,没有缓存时在收到插件策略前拒绝页面作业;本机与私网地址和公网网站一样可访问,也可以
+ 写进名单单独屏蔽(2026-10-28 决定)。新增 id 或新增 `pageControl` 视为权限变多,删减视为收权。
- 无配置的布尔能力只接受字面量 `true`:`notify`、`badge`、`confirm`、`fs`、`library`、
`sessionContext`、`pick`、`workspace`。不用就省略,写 `false` 是无效清单。
- `card: {}` 与 `agent: {}` 分别表示基础卡片能力和由真实用户点击触发 Agent 回合;