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。

refactor(browser-extension): drop site lists from My browser

Dash24800941a421
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 bbae262953..a0f7c36180 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
@@ -1,7 +1,7 @@
## 4.23 随包浏览器扩展(browserExtension 能力)
插件随包携带一个 Chrome / Edge 扩展(翻译、字幕、页面读取之类"住在用户浏览器里"的功能)时,
-由 **Cindy 承接扩展的连接**:配对、身份绑定、作业分发、站点策略守门、结果脱敏都在宿主,插件
+由 **Cindy 承接扩展的连接**:配对、身份绑定、作业分发、结果脱敏都在宿主,插件
不再自带接线进程。在身份卡声明:
```json
@@ -25,7 +25,7 @@
运行期两条管子:
```js
-// 插件 → 宿主:向扩展投递作业、推送站点策略与配对身份、回传转交结果
+// 插件 → 宿主:向扩展投递作业、推送配对身份、回传转交结果
let status;
try {
status = await cindy.send({ type: 'browser-extension-request', kind: 'status' });
@@ -36,10 +36,9 @@ try {
}
// 新宿主也会返回 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' }:收到后立即推送策略与配对身份。
+// 宿主没有保存过你的配对身份时,启动后会发来事件
+// { type: 'event', name: 'browser-extension-policy-request' }:收到后立即推送配对身份。
const result = await cindy.send({
type: 'browser-extension-request',
kind: 'act',
@@ -70,10 +69,9 @@ cindy.onHostMessage(async (msg) => {
规则与红线:
-- **站点策略归你**:读取与交互默认开放,本机、私网与单段内网主机名和公网网站一样可访问,也可以
- 写进名单单独屏蔽。你保存并在启动与每次变更时 `setPolicy` 推给宿主;宿主缓存到用户私有目录
- 并在每个作业上强制,没有缓存时在收到你的策略前拒绝页面作业,新授权必须经 `cindy.confirm`
- 真实确认。
+- **不设站点名单**:「我的浏览器」与 Cindy 专用浏览器一样,读取与交互不按网站限制,本机、私网与
+ 单段内网主机名和公网网站一样可访问;安全交给任务的权限档位与自动审核(2026-10-30 决定)。
+ 旧插件推送的 `setPolicy` 照常应答但不生效。
- **`nativeHost` 只给官方 Cindy Chrome**:Native Messaging 程序在插件沙箱外运行,且同一账号的
所有 Cindy 共用一份注册,宿主只为官方 Cindy Chrome(`my-browser`,名称
`com.makecindy.browser`,并声明了 Node 程序)安装它。其它插件声明了也只开桥接,扩展需要手动
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 be2ab7f64f..dd9185f203 100644
--- a/apps/desktop/src/main/browser-extension/__tests__/bridge.test.ts
+++ b/apps/desktop/src/main/browser-extension/__tests__/bridge.test.ts
@@ -2,12 +2,12 @@
* bridge.test — 浏览器扩展桥接的线协议回归(从插件时期的协议测试迁入宿主)。
*
* 测试价值
- * - 生产入口与可观察结果:BrowserExtensionBridge 的真实 HTTP 监听 + act/setPolicy/relay*
+ * - 生产入口与可观察结果:BrowserExtensionBridge 的真实 HTTP 监听 + act/setTrustedClients/relay*
* 方法;扩展看到的 /health、/poll、/ack、/authorize、/result、/learning/* 状态码与载荷。
- * - Bug/规则依据:插件 my-browser 0.4.x 的桥接合同(一次送达、unknown 不重投、撤销等待
- * 派发、结果脱敏、官方身份须 native 绑定);桥接迁入宿主后这些合同必须逐条保持。
+ * - Bug/规则依据:插件 my-browser 0.4.x 的桥接合同(一次送达、unknown 不重投、结果脱敏、
+ * 官方身份须 native 绑定);桥接迁入宿主后这些合同必须逐条保持。站点名单 2026-10-30 取消。
* - 现有覆盖缺口:宿主此前没有这条链路。
- * - 最小失败输入:见各用例(重复 ack、撤销后的 /authorize、带凭证的 tabs URL 等)。
+ * - 最小失败输入:见各用例(重复 ack、旧插件推送的名单、带凭证的 tabs URL 等)。
* - tier:unit(真实回环 socket,端口 0,无外部进程);实测耗时约 1 秒。
*/
@@ -18,10 +18,8 @@ import { afterEach, describe, expect, it } from 'vitest';
import { BrowserExtensionBridge, type BrowserExtensionRelayNotice } from '../bridge';
import {
- checkBrowserExtensionPolicy,
- defaultBrowserExtensionPolicy,
+ checkBrowserExtensionTarget,
normalizeBrowserExtensionHost,
- normalizeBrowserExtensionPolicy,
redactBrowserUrl,
validateBrowserExtensionJob,
} from '../policy';
@@ -172,65 +170,22 @@ async function fixture(
return { bridge, url, client, ready, relays, nativeToken };
}
-describe('policy · 站点策略与 URL 脱敏(与扩展侧同判据)', () => {
- it('默认策略开放读写(含本机与私网);带凭证地址与非网页协议拒绝;主机名规范化', () => {
- const p = defaultBrowserExtensionPolicy();
- expect(checkBrowserExtensionPolicy(p, 'text', 'https://example.test').ok).toBe(true);
- expect(checkBrowserExtensionPolicy(p, 'click', 'https://example.test').ok).toBe(true);
- expect(normalizeBrowserExtensionPolicy(p)).toEqual(p);
- p.read.block = ['blocked.test'];
- for (const url of [
- 'https://blocked.test',
- 'https://child.blocked.test',
- 'file:///etc/passwd',
- 'https://a:[email protected]',
- ]) {
- expect(checkBrowserExtensionPolicy(p, 'text', url).ok, url).toBe(false);
- }
- // Local and private pages are the user's own: reachable like in the dedicated browser.
- for (const url of ['http://127.0.0.2', 'http://[::1]', 'http://10.2.3.4', 'http://localhost.']) {
- expect(checkBrowserExtensionPolicy(p, 'text', url).ok, url).toBe(true);
- }
- expect(checkBrowserExtensionPolicy(p, 'text', 'https://[2606:4700:4700::1111]/').ok).toBe(true);
- p.interact.allow = ['example.test', 'blocked.test'];
- expect(checkBrowserExtensionPolicy(p, 'click', 'https://sub.example.test').ok).toBe(true);
- expect(checkBrowserExtensionPolicy(p, 'click', 'https://example.test.evil.test').ok).toBe(
- false,
- );
- expect(checkBrowserExtensionPolicy(p, 'click', 'https://blocked.test')).toMatchObject({
- error: 'READ_BLOCKED',
- });
+describe('policy · 地址校验与 URL 脱敏', () => {
+ it('任何网页地址都放行(含本机与私网);带凭证地址与非网页协议拒绝;主机名规范化', () => {
+ for (const url of ['https://example.test', 'http://127.0.0.2', 'http://[::1]', 'http://10.2.3.4', 'http://jira'])
+ for (const action of ['text', 'click'])
+ expect(checkBrowserExtensionTarget(action, url).ok, `${action} ${url}`).toBe(true);
+ for (const url of ['file:///etc/passwd', 'https://a:[email protected]', 'chrome://settings'])
+ expect(checkBrowserExtensionTarget('text', url).ok, url).toBe(false);
+ expect(checkBrowserExtensionTarget('nope', 'https://example.test')).toMatchObject({ error: 'INVALID_ACTION' });
+ // The tabs host filter still takes a plain domain.
expect(normalizeBrowserExtensionHost(' WWW.Example.test ')).toBe('www.example.test');
- expect(normalizeBrowserExtensionHost('*.example.test')).toBe('example.test');
- expect(normalizeBrowserExtensionHost('=example.test')).toBe('=example.test');
- for (const bad of [
-
- 'https://example.test',
- 'example.test/path',
- 'example.test:443',
- '*',
- ]) {
+ for (const bad of ['https://example.test', 'example.test/path', 'example.test:443', '*'])
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();
+ // Site recipes may send any DevTools method; there is no per-recipe allowlist (2026-10-30).
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();
+ validateBrowserExtensionJob('cdp', { url: 'https://example.test', tabId: 1, op: 'command', method: 'Storage.getCookies' }),
+ ).not.toThrow();
});
it('提取属性是封闭集合;载荷校验保留空文本与空选项', () => {
@@ -325,25 +280,6 @@ describe('bridge · 连接与身份', () => {
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 () => {
- let asked = 0;
- const { bridge, client } = await fixture({ awaitPolicy: true, onPolicyMissing: () => asked++ });
- await client({ native: true });
- expect(await bridge.act('text', { url: 'https://example.test' })).toMatchObject({
- ok: false,
- error: 'POLICY_NOT_READY',
- execution: 'not_executed',
- });
- // Each refusal tells the host, which asks the plugin again (throttled there).
- expect(asked).toBeGreaterThan(0);
- 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();
@@ -509,134 +445,38 @@ describe('bridge · 作业生命周期', () => {
expect((await c.request('/ack', { id: delivered.id })).status).toBe(409);
});
- it('送达后撤销权限:ack 被拒、不留排队作业;重新授权也不能复活', async () => {
+ // 2026-10-30: site lists are gone. A plugin of the site-list era still pushes one; it is acknowledged
+ // and blocks nothing, while tab URLs keep their credential redaction.
+ it('旧插件推送的站点名单不再生效;标签页地址仍做凭证脱敏', async () => {
const { bridge, ready } = await fixture();
const c = await ready();
- const p = defaultBrowserExtensionPolicy();
- p.interact.allow = ['example.test'];
- await bridge.setPolicy(p);
- const promise = bridge.act('click', { url: 'https://example.test', selector: 'button' });
- await sleep(5);
- const { job } = await c.request('/poll');
- await bridge.setPolicy({ read: { block: [] }, interact: { allow: [], block: [] } });
- expect((await promise).execution).toBe('not_executed');
- expect((await c.request('/ack', { id: job.id })).status).toBe(409);
- for (const blocked of ['example.test', 'redirect.test']) {
- await bridge.setPolicy(defaultBrowserExtensionPolicy());
- const pending = bridge.act('click', { url: 'https://example.test', selector: 'button' });
- await sleep(5);
- const delivered = (await c.request('/poll')).job;
- await c.request('/ack', { id: delivered.id });
- expect(
- (await c.request('/authorize', { id: delivered.id, url: 'https://redirect.test' })).ok,
- ).toBe(true);
- await bridge.setPolicy({ ...defaultBrowserExtensionPolicy(), read: { block: [blocked] } });
- const result = await pending;
- expect(result).toMatchObject({ error: 'READ_BLOCKED', execution: 'unknown' });
- await bridge.setPolicy(defaultBrowserExtensionPolicy());
- expect(
- (await c.request('/authorize', { id: delivered.id, url: 'https://redirect.test' })).status,
- ).toBe(409);
- expect((await c.request('/result', { id: delivered.id, result: { ok: true } })).status).toBe(
- 409,
- );
- }
- });
-
- it('撤销等待最终文档派发结束并丢弃其结果;丢失的派发不能报告为撤销成功', async () => {
- const { bridge, ready } = await fixture({ jobTimeout: 2000 });
- const c = await ready();
- const pending = bridge.act('click', { url: 'https://example.test', selector: 'button' });
+ expect(
+ bridge.setPolicy({ read: { block: ['example.test'] }, interact: { allow: [], block: [] } }),
+ ).toMatchObject({ ok: true, policy: { read: { block: [] }, interact: { allow: ['*'] } } });
+ const p = bridge.act('tabs', {});
await sleep(5);
const { job } = await c.request('/poll');
- await c.request('/ack', { id: job.id });
- expect(
- (await c.request('/authorize', { id: job.id, url: 'https://example.test', dispatch: true }))
- .ok,
- ).toBe(true);
- let saved = false;
- const save = bridge
- .setPolicy({ ...defaultBrowserExtensionPolicy(), read: { block: ['example.test'] } })
- .then((r) => {
- saved = true;
- return r;
- });
- await sleep(25);
- expect(saved).toBe(false);
- expect(
- (await c.request('/authorize', { id: job.id, url: 'https://example.test', dispatch: true }))
- .status,
- ).toBe(403);
- expect(await bridge.act('text', { url: 'https://example.test' })).toMatchObject({
- error: 'READ_BLOCKED',
+ expect((await c.request('/ack', { id: job.id })).policy).toMatchObject({ read: { block: [] } });
+ await c.request('/result', {
+ id: job.id,
+ result: {
+ tabs: [
+ { id: 1, url: 'https://example.test?code=11111111-1111-4111-8111-111111111111', title: 'mail' },
+ { id: 2, url: 'chrome://settings', title: 'settings' },
+ ],
+ },
});
- await c.request('/result', { id: job.id, result: { ok: true, text: 'must not escape' } });
- expect((await save).ok).toBe(true);
- const result = await pending;
- expect(result).toMatchObject({ error: 'READ_BLOCKED', execution: 'unknown' });
- expect(result.text).toBeUndefined();
-
- const { bridge: lost, ready: readyLost } = await fixture({ jobTimeout: 100 });
- const l = await readyLost();
- const lostPending = lost.act('click', { url: 'https://example.test', selector: 'button' });
+ const tabs = (await p).tabs as Array<Record<string, unknown>>;
+ expect(tabs[0].title).toBe('mail');
+ expect(tabs[0].url).not.toContain('11111111');
+ expect(tabs[1]).toEqual({ id: 2, redacted: true });
+ const clicked = bridge.act('click', { url: 'https://example.test', selector: 'button' });
await sleep(5);
- const lostJob = (await l.request('/poll')).job;
- await l.request('/ack', { id: lostJob.id });
- await l.request('/authorize', { id: lostJob.id, url: 'https://example.test', dispatch: true });
- const policy = { ...defaultBrowserExtensionPolicy(), read: { block: ['example.test'] } };
- expect(await lost.setPolicy(policy)).toMatchObject({
- ok: false,
- error: 'REVOCATION_UNCONFIRMED',
- execution: 'unknown',
- applied: true,
- });
- expect(await lost.setPolicy(policy)).toMatchObject({ error: 'REVOCATION_UNCONFIRMED' });
- expect(
- (await l.request('/result', { id: lostJob.id, result: { ok: false, execution: 'unknown' } }))
- .status,
- ).toBe(409);
- expect(await lost.setPolicy(policy)).toMatchObject({ error: 'REVOCATION_UNCONFIRMED' });
- expect((await l.request('/result', { id: lostJob.id, result: { ok: true } })).status).toBe(409);
- expect((await lost.setPolicy(policy)).ok).toBe(true);
- expect((await lostPending).execution).toBe('unknown');
- });
-
- it('被阻止站点的标签与跳转到被阻止站点的内容由宿主脱敏,不依赖扩展过滤', async () => {
- const { bridge, ready } = await fixture();
- const c = await ready();
- await bridge.setPolicy({
- ...defaultBrowserExtensionPolicy(),
- read: { block: ['blocked.test'] },
- });
- async function roundtrip(action: string, result: unknown) {
- const p = bridge.act(action, action === 'tabs' ? {} : { url: 'https://example.test' });
- await sleep(5);
- const { job } = await c.request('/poll');
- await c.request('/ack', { id: job.id });
- await c.request('/result', { id: job.id, result });
- return p;
- }
- const r = await roundtrip('tabs', {
- tabs: [
- { id: 1, url: 'https://blocked.test', title: 'private' },
- {
- id: 2,
- url: 'https://example.test?code=11111111-1111-4111-8111-111111111111',
- title: 'public',
- },
- ],
- });
- const tabs = r.tabs as Array<Record<string, unknown>>;
- expect(tabs[0]).toEqual({ id: 1, redacted: true });
- expect(tabs[1].title).toBe('public');
- expect(tabs[1].url).not.toContain('11111111');
- const redirected = await roundtrip('text', {
- ok: true,
- url: 'https://blocked.test',
- text: 'private',
- });
- expect(redirected).toMatchObject({ error: 'REDIRECT_BLOCKED' });
- expect(redirected.text).toBeUndefined();
+ const delivered = (await c.request('/poll')).job;
+ expect((await c.request('/ack', { id: delivered.id })).ok).toBe(true);
+ expect((await c.request('/authorize', { id: delivered.id, url: 'https://example.test' })).ok).toBe(true);
+ await c.request('/result', { id: delivered.id, result: { ok: true, execution: 'executed' } });
+ expect((await clicked).ok).toBe(true);
});
// Review 2026-10-29 (Codex P1): network-result entries were forwarded to the model with their URLs
@@ -772,9 +612,6 @@ describe('bridge · 转交请求(翻译/字幕)', () => {
done: true,
result: { translations: ['你好'] },
});
- await bridge.setPolicy({ read: { block: ['example.test'] }, interact: { allow: [] } });
- expect(bridge.relayActive(job.id).active).toBe(false);
- expect((await c.signed('/learning/result', { id: job.id })).status).toBe(403);
const config = { id: crypto.randomUUID(), request: { op: 'config' } };
await c.signed('/learning/start', config);
await c.signed('/learning/cancel', { id: config.id });
diff --git a/apps/desktop/src/main/browser-extension/bridge.ts b/apps/desktop/src/main/browser-extension/bridge.ts
index 84f00fc6bb..f2d67ece34 100644
--- a/apps/desktop/src/main/browser-extension/bridge.ts
+++ b/apps/desktop/src/main/browser-extension/bridge.ts
@@ -1,6 +1,6 @@
/**
* 浏览器扩展桥接(宿主侧):在 127.0.0.1 的一段固定端口上承接随包浏览器扩展的
- * 长轮询连接,负责配对、身份绑定、作业分发、站点策略守门、结果脱敏,以及把
+ * 长轮询连接,负责配对、身份绑定、作业分发、结果脱敏,以及把
* 扩展发起的转交请求(翻译、字幕等)交给声明 browserExtension 的插件处理。
*
* 线协议 `cindy-browser-extension/3`(协议号 3,签名线合同 0.4.13)原样沿用插件
@@ -17,7 +17,8 @@
* - 只有扩展 origin 能连:自定义头 + 无 CORS,网页、预检、改绑 Host 一律 403;
* - 官方扩展 id 首次出现必须经 native host 绑定公钥,HTTP 调用方不能自称官方;
* - 作业一次送达绝不重投;已确认未完成的作业只能是 unknown,不能按成功或未执行报告;
- * - 策略撤销对在途作业生效:未授权直接作废,已进入 DOM 派发的等待派发结束再丢弃结果;
+ * - 不设站点名单(2026-10-30 决定):安全交给任务的权限档位与自动审核;旧扩展与旧插件仍收发
+ * 的 policy 字段只作兼容,恒为「全部允许」;
* - 每个 URL 交给模型前都经 redactBrowserUrl;读取结果标 untrusted_content。
*/
@@ -25,11 +26,10 @@ import http from 'node:http';
import crypto from 'node:crypto';
import {
- checkBrowserExtensionPolicy,
+ checkBrowserExtensionTarget,
defaultBrowserExtensionPolicy,
isBrowserExtensionInteractAction,
isBrowserExtensionReadAction,
- normalizeBrowserExtensionPolicy,
redactBrowserUrl,
validateBrowserExtensionJob,
type BrowserExtensionAction,
@@ -133,14 +133,6 @@ 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;
- /** Called whenever a job is refused for lack of a policy, so the host can ask the plugin again. */
- onPolicyMissing?: () => void;
ports?: readonly number[];
pollTimeout?: number;
connectWait?: number;
@@ -179,10 +171,6 @@ interface Job {
resolve: (result: BrowserExtensionJobResult) => void;
created: number;
timer?: ReturnType<typeof setTimeout>;
- authorizedUrl?: string;
- dispatchSettled?: Promise<boolean>;
- settleDispatch?: (finished: boolean) => void;
- revoked?: { error: string; message: string };
}
interface RelayItem {
@@ -213,17 +201,13 @@ const isHttp = (value: unknown): value is string =>
const FIELD_VALUE_MAX = 4000;
export class BrowserExtensionBridge {
- private policy: BrowserExtensionPolicy = defaultBrowserExtensionPolicy();
+ /** Wire compatibility only: extensions and plugins of the site-list era still read it. */
+ private readonly policy: BrowserExtensionPolicy = defaultBrowserExtensionPolicy();
private pins: BrowserExtensionTrustedClient[] = [];
private readonly nativeBindings = new Map<string, string>();
private server: http.Server | null = null;
private starting: Promise<void> | null = null;
private port = 0;
- private readonly unconfirmedDispatches = new Map<
- string,
- { clientId: string; action: BrowserExtensionAction; url?: string; authorizedUrl?: string }
- >();
- private unconfirmedOverflow = false;
private readonly jobs = new Map<string, Job>();
private readonly clients = new Map<string, Client>();
private readonly waiting = new Map<string, () => void>();
@@ -232,26 +216,15 @@ 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) {
- this.options.onPolicyMissing?.();
- 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);
+ private gate(action: unknown, url: unknown): ReturnType<typeof checkBrowserExtensionTarget> {
+ return checkBrowserExtensionTarget(action, url);
}
get listeningPort(): number {
@@ -462,24 +435,10 @@ export class BrowserExtensionBridge {
// ── 作业生命周期 ────────────────────────────────────────────────────────
- private finish(job: Job, result: Record<string, unknown>, browserFinished = false): void {
+ private finish(job: Job, result: Record<string, unknown>): void {
if (!this.jobs.has(job.id)) return;
clearTimeout(job.timer);
this.jobs.delete(job.id);
- if (job.dispatchSettled && !browserFinished) {
- // 历史不是可运行的工作:只保留有界的授权元数据,不保留载荷文本与结果承诺。
- if (this.unconfirmedDispatches.size >= 128) {
- this.unconfirmedDispatches.delete(this.unconfirmedDispatches.keys().next().value as string);
- this.unconfirmedOverflow = true; // 忘记身份不是完成的证据。
- }
- this.unconfirmedDispatches.set(job.id, {
- clientId: job.clientId,
- action: job.action,
- url: job.payload.url,
- authorizedUrl: job.authorizedUrl,
- });
- }
- job.settleDispatch?.(browserFinished);
const safe = this.redactResult(result, job.payload.maxChars || 6000);
const timing = (safe.timing && typeof safe.timing === 'object' ? safe.timing : {}) as Record<
string,
@@ -933,18 +892,6 @@ export class BrowserExtensionBridge {
const b = (await this.readBody(req, req.url === '/result' ? 32_000_000 : 512000)).value;
const jobId = String(b.id);
const job = this.jobs.get(jobId);
- // 迟到的完成只消除不确定性,绝不复活或返回过期结果。
- if (req.url === '/result' && this.unconfirmedDispatches.get(jobId)?.clientId === clientId) {
- const result = b.result as { execution?: unknown } | undefined;
- if (
- result &&
- typeof result === 'object' &&
- !Array.isArray(result) &&
- result.execution !== 'unknown'
- )
- this.unconfirmedDispatches.delete(jobId);
- return this.send(res, failure('JOB_EXPIRED', 'The operation result expired.'), 409);
- }
if (
!job ||
job.clientId !== clientId ||
@@ -952,8 +899,6 @@ export class BrowserExtensionBridge {
) {
return this.send(res, failure('JOB_EXPIRED', 'Do not execute this job.'), 409);
}
- 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 = this.gate(
job.action,
@@ -964,21 +909,12 @@ export class BrowserExtensionBridge {
this.finish(job, result);
return this.send(res, result, 403);
}
+ // /authorize only re-validates the address the extension is about to touch (older extensions
+ // call it before every page action); there is no site list to revoke against.
if (req.url === '/ack') job.state = 'acknowledged';
- else {
- job.authorizedUrl = typeof b.url === 'string' ? b.url : undefined;
- // 文档已准备执行:撤销必须等待这次派发结束;单独作废结果并不能阻止 DOM。
- if (b.dispatch === true && !job.dispatchSettled) {
- job.dispatchSettled = new Promise((resolve) => {
- job.settleDispatch = resolve;
- });
- }
- }
return this.send(res, { ok: true, policy: this.policy });
}
- let result: Record<string, unknown> = job.revoked
- ? this.jobFailure(job, job.revoked.error, job.revoked.message)
- : (b.result as Record<string, unknown>);
+ let result = b.result as Record<string, unknown>;
if (!result || typeof result !== 'object' || Array.isArray(result)) {
result = this.jobFailure(
job,
@@ -1034,12 +970,7 @@ export class BrowserExtensionBridge {
) {
result = { ...result, execution: this.jobFailure(job, '', '').execution };
}
- const browserFinished =
- !!b.result &&
- typeof b.result === 'object' &&
- !Array.isArray(b.result) &&
- (b.result as { execution?: unknown }).execution !== 'unknown';
- this.finish(job, result, browserFinished);
+ this.finish(job, result);
return this.send(res, { ok: true });
}
@@ -1109,48 +1040,11 @@ export class BrowserExtensionBridge {
);
}
- /** 插件推送(或宿主恢复)站点策略;在途作业按新策略撤销,DOM 派发中的等其结束。 */
- async setPolicy(
- input: unknown,
- ): Promise<
- { 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 = this.gate(job.action, job.payload.url);
- const gate =
- original.ok && job.authorizedUrl
- ? this.gate(job.action, job.authorizedUrl)
- : original;
- if (!gate.ok) {
- if (job.dispatchSettled) {
- job.revoked = gate;
- dispatches.push(job.dispatchSettled);
- } else {
- this.finish(job, this.jobFailure(job, gate.error, gate.message));
- }
- }
- }
- const completed = await Promise.all(dispatches);
- const uncertain = [...this.unconfirmedDispatches.values()].some(
- (job) =>
- !this.gate(job.action, job.url).ok ||
- (job.authorizedUrl &&
- !this.gate(job.action, job.authorizedUrl).ok),
- );
- if (completed.some((finished) => !finished) || uncertain || this.unconfirmedOverflow) {
- return {
- ...failure(
- 'REVOCATION_UNCONFIRMED',
- 'Permissions are applied, but an earlier browser action did not confirm completion. Check the page before continuing.',
- 'unknown',
- ),
- applied: true,
- };
- }
+ /**
+ * Plugins of the site-list era still push their lists; they are acknowledged and ignored (site lists
+ * were removed on 2026-10-30, safety is the task's permission mode and review).
+ */
+ setPolicy(_input?: unknown): { ok: true; policy: BrowserExtensionPolicy } {
return { ok: true, policy: this.policy };
}
diff --git a/apps/desktop/src/main/browser-extension/policy.ts b/apps/desktop/src/main/browser-extension/policy.ts
index cfe81240dd..f0f1662c69 100644
--- a/apps/desktop/src/main/browser-extension/policy.ts
+++ b/apps/desktop/src/main/browser-extension/policy.ts
@@ -1,12 +1,10 @@
/**
- * 浏览器扩展站点策略(宿主侧实现)。
+ * 浏览器扩展作业的地址与载荷校验(宿主侧实现)。
*
- * 与扩展内的 policy 实现是同一套语义:扩展在页面侧再查一遍,宿主在分发作业前
- * 查一遍,两侧都必须对同一 URL 给出同样的结论。改动任何判据时两侧一起改。
+ * 不设站点名单(2026-10-30 决定):AI 本身权限已经很高,安全交给任务的权限档位与自动审核,
+ * 与 Cindy 专用浏览器一致。线上的 policy 字段只为兼容旧扩展与旧插件保留,恒为「全部允许」。
*
- * - READ 动作默认开放公网,INTERACT 动作按 interact.allow / block 守门;
- * - 只接受无内嵌凭证的 http(s) URL;本机与私网地址同样允许(2026-10-28 决定:用户自己的
- * 浏览器本来就能访问这些地址,能力与专用浏览器对齐,不另设防线);
+ * - 只接受无内嵌凭证的 http(s) URL;本机与私网地址同样允许(2026-10-28 决定);
* - 交给模型之前的每个 URL 都过 redactUrl:OAuth code、重置令牌、implicit-flow
* fragment 与 Basic Auth userinfo 不离开本机。
*/
@@ -61,6 +59,7 @@ export type BrowserExtensionReadAction = (typeof BROWSER_EXTENSION_READ_ACTIONS)
export type BrowserExtensionInteractAction = (typeof BROWSER_EXTENSION_INTERACT_ACTIONS)[number];
export type BrowserExtensionAction = BrowserExtensionReadAction | BrowserExtensionInteractAction;
+/** Wire shape kept for extensions and plugins of the site-list era; always the permissive default now. */
export interface BrowserExtensionPolicy {
read: { block: string[] };
interact: { allow: string[]; block: string[] };
@@ -93,43 +92,13 @@ 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;
+ const host = new URL('https://' + raw).hostname;
return (exact ? '=' : '') + host;
}
if (!raw || /[\s/@:?#\\]/.test(raw))
@@ -148,97 +117,18 @@ export function normalizeBrowserExtensionHost(value: unknown): string {
return (exact ? '=' : '') + host;
}
-function publicLiteral(ip: string): boolean {
- if (/^\d+\.\d+\.\d+\.\d+$/.test(ip)) {
- const [a, b] = ip.split('.').map(Number);
- return (
- a !== 0 &&
- a !== 10 &&
- a !== 127 &&
- a < 224 &&
- !(a === 169 && b === 254) &&
- !(a === 172 && b >= 16 && b <= 31) &&
- !(a === 192 && b === 168) &&
- !(a === 100 && b >= 64 && b <= 127)
- );
- }
- try {
- const host = new URL('http://[' + ip + ']/').hostname.slice(1, -1);
- const [first, second] = host.split(':').map((x) => parseInt(x || '0', 16));
- return (
- first >= 0x2000 &&
- first <= 0x3fff &&
- first !== 0x2002 &&
- first !== 0x3fff &&
- !(first === 0x2001 && (second < 0x200 || second === 0xdb8))
- );
- } catch {
- return false;
- }
-}
-
-export function isLocalBrowserHost(host: string): boolean {
- if (
- host === 'localhost' ||
- host.endsWith('.localhost') ||
- host.endsWith('.local') ||
- host.endsWith('.internal')
- ) {
- return true;
- }
- const ip =
- host.startsWith('[') && host.endsWith(']')
- ? host.slice(1, -1)
- : host.includes(':')
- ? host
- : /^\d+\.\d+\.\d+\.\d+$/.test(host)
- ? host
- : null;
- if (ip) return !publicLiteral(ip);
- return !host.includes('.');
-}
-
-export function browserExtensionHostMatches(host: string, pattern: string): boolean {
- return (
- pattern === '*' ||
- (pattern.startsWith('=')
- ? host === pattern.slice(1)
- : host === pattern || host.endsWith('.' + pattern))
- );
-}
-
-export function normalizeBrowserExtensionPolicy(input: unknown): BrowserExtensionPolicy {
- const p = input as {
- read?: { block?: unknown };
- interact?: { allow?: unknown; block?: unknown };
- } | null;
- if (!p || !p.read || !p.interact)
- throw new Error('Invalid policy. Reload settings before saving.');
- const list = (items: unknown, wildcard = false): string[] => {
- if (!Array.isArray(items) || items.length > 200)
- throw new Error('Each policy list must contain at most 200 domains.');
- return [
- ...new Set(
- items.map((h) => (wildcard && h === '*' ? '*' : normalizeBrowserExtensionHost(h))),
- ),
- ];
- };
- return {
- read: { block: list(p.read.block) },
- interact: { allow: list(p.interact.allow, true), block: list(p.interact.block ?? []) },
- };
-}
-
-export function checkBrowserExtensionPolicy(
- policy: BrowserExtensionPolicy,
+/**
+ * The address checks every job still gets: a supported action and a plain HTTP(S) URL without embedded
+ * credentials. There are no site lists (removed 2026-10-30): safety is the task's permission mode and review.
+ */
+export function checkBrowserExtensionTarget(
action: unknown,
url: unknown,
): BrowserExtensionPolicyVerdict {
- const deny = (error: string, message: string, host?: string): BrowserExtensionPolicyDenial => ({
+ const deny = (error: string, message: string): BrowserExtensionPolicyDenial => ({
ok: false,
error,
message,
- ...(host !== undefined ? { host } : {}),
execution: 'not_executed',
});
if (!isBrowserExtensionReadAction(action) && !isBrowserExtensionInteractAction(action)) {
@@ -254,26 +144,7 @@ export function checkBrowserExtensionPolicy(
if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password) {
return deny('URL_NOT_ALLOWED', 'Only HTTP/HTTPS URLs without embedded credentials are supported.');
}
- const host = u.hostname.toLowerCase().replace(/\.$/, '');
- if (policy.read.block.some((p) => browserExtensionHostMatches(host, p))) {
- return deny(
- 'READ_BLOCKED',
- 'This site is on the read block list. Review the site policy in plugin settings.',
- host,
- );
- }
- if (
- isBrowserExtensionInteractAction(action) &&
- (!policy.interact.allow.some((p) => browserExtensionHostMatches(host, p)) ||
- policy.interact.block.some((p) => browserExtensionHostMatches(host, p)))
- ) {
- return deny(
- 'INTERACT_NOT_ALLOWED',
- 'Ask the user to allow this exact site before clicking, typing or searching.',
- host,
- );
- }
- return { ok: true, host };
+ return { ok: true, host: u.hostname.toLowerCase().replace(/\.$/, '') };
}
export interface BrowserExtensionJobPayload {
@@ -361,20 +232,6 @@ 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/cindy-brain/__tests__/browserExtensionSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts
index bc767bb89f..37c16f6ccb 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/browserExtensionSlot.test.ts
@@ -100,9 +100,8 @@ class FakeBridge {
this.calls.push(['act', [action, payload]]);
return { ok: true, text: 'hello' };
}
- async setPolicy(policy: unknown) {
- this.calls.push(['setPolicy', [policy]]);
- this.policy = policy as typeof this.policy;
+ setPolicy() {
+ this.calls.push(['setPolicy', []]);
return { ok: true as const, policy: this.policy };
}
setTrustedClients(clients: unknown) {
@@ -300,7 +299,7 @@ describe('browserExtensionSlot · 管子上行', () => {
});
});
- it('status / act / setPolicy / setTrustedClients / relay* 原样转给桥接;策略落盘并在重启后恢复', async () => {
+ it('status / act / setTrustedClients / relay* 原样转给桥接;旧插件的 setPolicy 应答不落盘;配对重启后恢复', async () => {
const { slot, bridges, dir, ghosts, settle } = await makeSlot();
slot.reconcile(ghosts);
await settle();
@@ -323,23 +322,18 @@ describe('browserExtensionSlot · 管子上行', () => {
}),
).toMatchObject({ ok: true, text: 'hello' });
expect(bridges[0].calls.at(-1)).toEqual(['act', ['text', { url: 'https://example.test' }]]);
- expect(
- await slot.handleRequest(id, { kind: 'setPolicy', policy: { read: { block: 'bad' } } }),
- ).toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });
- const policy = {
- read: { block: ['blocked.test'] },
- interact: { allow: ['example.test'], block: [] },
- };
+ // Site lists were removed (2026-10-30): a plugin that still pushes one gets an acknowledgement.
+ const policy = { read: { block: ['blocked.test'] }, interact: { allow: ['example.test'], block: [] } };
expect(await slot.handleRequest(id, { kind: 'setPolicy', policy })).toMatchObject({
ok: true,
- policy,
+ policy: { read: { block: [] } },
});
- expect(
- JSON.parse(await fs.readFile(path.join(dir, encodeURIComponent(id) + '.json'), 'utf8')),
- ).toEqual({ version: 1, policy, trustedClients: [] });
expect(await slot.handleRequest(id, { kind: 'setTrustedClients', clients: [] })).toEqual({
ok: true,
});
+ expect(
+ JSON.parse(await fs.readFile(path.join(dir, encodeURIComponent(id) + '.json'), 'utf8')),
+ ).toEqual({ version: 1, trustedClients: [] });
expect(await slot.handleRequest(id, { kind: 'relayActive', id: 'r1' })).toEqual({
ok: true,
active: true,
@@ -362,49 +356,22 @@ describe('browserExtensionSlot · 管子上行', () => {
ok: false,
errorCode: 'INVALID_REQUEST',
});
- // 重启(新槽、同目录):先恢复配对与上次策略再 start,不再向插件索要策略。
+ // 重启(新槽、同目录):先恢复配对再 start,不再向插件索要;旧版本存下的名单被忽略。
+ await fs.writeFile(
+ path.join(dir, encodeURIComponent(id) + '.json'),
+ JSON.stringify({ version: 1, policy, trustedClients: [] }),
+ );
const again = await makeSlot({ policyDir: () => dir });
again.slot.reconcile(again.ghosts);
await vi.waitFor(() => expect(again.bridges[0]?.started).toBe(true));
- expect(again.bridges[0].calls.slice(0, 2)).toEqual([
- ['setTrustedClients', [[]]],
- ['setPolicy', [policy]],
- ]);
+ expect(again.bridges[0].calls).toEqual([['setTrustedClients', [[]]]]);
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.
- // Review 2026-10-29 (Greptile P1): a setPolicy that was still waiting when the account switched
- // saved the old account's permissions and pairings into the new account's cache.
- it('切换账号时在途的策略写入仍落在原账号的缓存目录', async () => {
- const other = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-browser-extension-slot-b-'));
- dirs.push(other);
- const { slot, bridges, dir, deps } = await makeSlot();
- slot.reconcile([extGhost()]);
- await vi.waitFor(() => expect(bridges[0]?.started).toBe(true));
- let release: () => void = () => undefined;
- const gate = new Promise<void>((resolve) => (release = resolve));
- const realSetPolicy = bridges[0].setPolicy.bind(bridges[0]);
- bridges[0].setPolicy = async (policy: unknown) => {
- await gate;
- return realSetPolicy(policy);
- };
- const policy = { read: { block: ['blocked.test'] }, interact: { allow: ['example.test'], block: [] } };
- const pending = slot.handleRequest('_root__my-browser', { kind: 'setPolicy', policy });
- // The account switches while the job is still settling.
- (deps as { policyDir: () => string }).policyDir = () => other;
- release();
- expect(await pending).toMatchObject({ ok: true });
- await expect(fs.readFile(path.join(dir, encodeURIComponent('_root__my-browser') + '.json'), 'utf8')).resolves.toContain('blocked.test');
- expect(await fs.readdir(other)).toEqual([]);
- });
-
- it('没有缓存策略时让桥接等待策略并向插件索要;配对随策略一起落盘', async () => {
+ 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 });
diff --git a/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts b/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts
index e63577a4c5..28c136a42a 100644
--- a/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/browserExtensionSlot.ts
@@ -4,7 +4,7 @@
* 插件随包携带一个浏览器扩展时,由宿主承接扩展的连接:为每个**已装、启用、声明
* browserExtension** 的插件各开一份本机桥接(BrowserExtensionBridge),复制并注册
* 它的 Native Messaging host,把扩展发起的请求(翻译、字幕…)经管子转交给插件,
- * 并把插件的作业、策略与配对身份推送转给桥接。声明 pageControl 的扩展同时成为
+ * 并把插件的作业与配对身份推送转给桥接。声明 pageControl 的扩展同时成为
* Browser Use 的「我的浏览器」执行端(user-browser 后端经 getPageControl 取桥接)。
*
* 安全模型:
@@ -12,9 +12,10 @@
* 按 BRIDGE_STOPPED 作废,不留排队作业;
* - 身份:允许连接的扩展 id 来自身份卡(装入时展示并钉死),宿主代码里不出现任何
* 具体插件名;native host 的授权令牌只写本机私有连接文件;
- * - 策略归插件:站点策略由插件保存并推送(setPolicy),宿主只缓存、持久化到
- * owner 私有目录并在每个作业上强制;宿主重启后先恢复上次策略与配对再接受连接,
- * 没有可用缓存时桥接在收到插件策略前拒绝页面作业,并向插件索要策略;
+ * - 不设站点名单(2026-10-30 决定):安全交给任务的权限档位与自动审核;旧插件推送的
+ * setPolicy 照常应答但不生效;
+ * - 配对归插件:插件推送已配对的浏览器,宿主持久化到 owner 私有目录,重启后先恢复再
+ * 接受连接;没有缓存时向插件索要一次;
* - native host 在插件沙箱外运行且全账号共用一份注册,只为官方 Cindy Chrome 安装
* (见 OFFICIAL_NATIVE_HOSTS,宿主唯一点名具体插件的地方);
* - 转交请求只投递给声明该扩展的插件(沙箱内处理),宿主不解释其业务内容。
@@ -39,8 +40,6 @@ import {
} from '../browser-extension/native-binding.js';
import {
defaultBrowserExtensionPolicy,
- normalizeBrowserExtensionPolicy,
- type BrowserExtensionPolicy,
} from '../browser-extension/policy.js';
import {
ghostInstallApprovalToken,
@@ -86,9 +85,9 @@ export interface BrowserExtensionSlotDeps {
sendToGhost(ghostId: string, payload: unknown): boolean;
/** 逻辑页不在线时拉起它(订阅网关同款);缺省不拉起。 */
wake?(ghostId: string): Promise<boolean>;
- /** 策略缓存目录(owner 私有);切换账号后目录变化,桥接按新目录重启。 */
+ /** 配对缓存目录(owner 私有);切换账号后目录变化,桥接按新目录重启。 */
policyDir(): string;
- /** 当前数据所有者标识;变化时所有桥接重建(策略不跨账号)。 */
+ /** 当前数据所有者标识;变化时所有桥接重建(配对不跨账号)。 */
ownerScopeKey(): string;
createBridge?(options: BrowserExtensionBridgeOptions): BrowserExtensionBridge;
createNativeBinding?(options: NativeBindingOptions): NativeBinding;
@@ -107,22 +106,19 @@ 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. */
+ /** Paired clients as last persisted. */
saved: SavedBrowserExtensionState;
/** Serialises cache writes so an older write cannot land after a newer one. */
writes: Promise<void>;
/**
* Cache directory of the account this entry was created for. Fixed at creation: an account
- * switch changes policyDir() while a setPolicy may still be waiting, and its permissions and
- * pairings must never be written into the new account's cache.
+ * switch changes policyDir() while a write may still be waiting, and its pairings must never be
+ * written into the new account's cache.
*/
cacheDir: string;
}
interface SavedBrowserExtensionState {
- policy: BrowserExtensionPolicy | null;
trustedClients: unknown[];
}
@@ -173,7 +169,6 @@ export class GhostBrowserExtensionSlot {
private start(instanceId: string, ghost: InstalledGhost, ownerScopeKey: string): void {
const needs = ghost.manifest.browserExtension!;
- let lastPolicyRequest = Number.NEGATIVE_INFINITY;
const cacheDir = this.deps.policyDir();
if (needs.nativeHost && !mayInstallNativeHost(ghost))
this.deps.log?.warn('browser extension native host ignored: only the official plugin may install one', {
@@ -188,14 +183,6 @@ export class GhostBrowserExtensionSlot {
: null;
const bridge = (this.deps.createBridge ?? ((options) => new BrowserExtensionBridge(options)))({
ghostId: ghost.manifest.id,
- awaitPolicy: true,
- // The first request can be lost (plugin page still loading); ask again on refusal, throttled.
- onPolicyMissing: () => {
- const now = (this.deps.now ?? Date.now)();
- if (now - lastPolicyRequest < 5000) return;
- lastPolicyRequest = now;
- void this.requestPolicy(instanceId);
- },
installedVersion: ghost.manifest.version,
extensionIds: needs.extensionIds,
...(native ? { nativeToken: native.token } : {}),
@@ -211,8 +198,7 @@ export class GhostBrowserExtensionSlot {
native,
ready: Promise.resolve(),
closing: false,
- policyRevision: 0,
- saved: { policy: null, trustedClients: [] },
+ saved: { trustedClients: [] },
writes: Promise.resolve(),
cacheDir,
};
@@ -221,7 +207,6 @@ export class GhostBrowserExtensionSlot {
// The old bridge must release its port and native registration before this one claims them.
await previous?.catch(() => undefined);
const saved = await this.readSaved(cacheDir, instanceId);
- let restored = false;
if (saved) {
entry.saved = saved;
try {
@@ -234,22 +219,11 @@ export class GhostBrowserExtensionSlot {
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);
+ // No saved pairings (first run in the host, or an unreadable cache): ask the plugin to push them
+ // now, so a browser it already paired is not sent back to pairing.
+ if (!saved) void this.requestPairings(instanceId);
if (native) {
const installed = await native.install(bridge.listeningPort, needs.extensionIds);
if (!installed.ok)
@@ -378,19 +352,9 @@ export class GhostBrowserExtensionSlot {
req.action,
req.payload ?? {},
)) as GhostPipeBrowserExtensionResult;
- case 'setPolicy': {
- let policy: BrowserExtensionPolicy;
- try {
- policy = normalizeBrowserExtensionPolicy(req.policy);
- } 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) && revision === entry.policyRevision)
- await this.persist(entry, { policy });
- return applied as GhostPipeBrowserExtensionResult;
- }
+ // Site lists were removed (2026-10-30); plugins that still push them are acknowledged.
+ case 'setPolicy':
+ return entry.bridge.setPolicy() as GhostPipeBrowserExtensionResult;
case 'setTrustedClients': {
let applied: { ok: true };
try {
@@ -445,31 +409,21 @@ export class GhostBrowserExtensionSlot {
return null;
}
- // ── 策略持久化 ──────────────────────────────────────────────────────────
+ // ── 配对持久化 ──────────────────────────────────────────────────────────
private policyFile(cacheDir: string, instanceId: string): string {
return path.join(cacheDir, encodeURIComponent(instanceId) + '.json');
}
- /** Saved permissions and pairings; null when missing or unreadable (treated as unknown). */
+ /** Saved pairings; null when missing or unreadable. A site list saved by older versions is ignored. */
private async readSaved(cacheDir: string, instanceId: string): Promise<SavedBrowserExtensionState | null> {
try {
const raw = JSON.parse(await fs.readFile(this.policyFile(cacheDir, instanceId), 'utf8')) as {
version?: unknown;
- policy?: unknown;
trustedClients?: unknown;
};
if (raw?.version !== 1) return null;
- 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 {
@@ -495,31 +449,30 @@ export class GhostBrowserExtensionSlot {
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
await fs.writeFile(
tmp,
- JSON.stringify({
- version: 1,
- ...(saved.policy ? { policy: saved.policy } : {}),
- trustedClients: saved.trustedClients,
- }),
+ JSON.stringify({ version: 1, 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', {
+ this.deps.log?.warn('browser extension pairings 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> {
+ /**
+ * Ask the plugin to push its paired browsers: wake it when offline, else send the request. The event
+ * keeps its published name; plugins answer it with their pairings (and a site list that is ignored).
+ */
+ private async requestPairings(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', {
+ this.deps.log?.warn('browser extension pairing request failed', {
instanceId,
error: errorText(err),
});
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 50b670f9e2..e0238635b7 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -9071,7 +9071,7 @@ export function registerGhostIpc(): void {
return getGhostPreviewSlot().handleRequest(id, payload);
}
// browser-extension-request = 浏览器扩展槽(browserExtension):插件向自己的扩展
- // 投递作业、推送站点策略/配对身份、回传转交结果;资格审与桥接在 browserExtensionSlot。
+ // 投递作业、推送配对身份、回传转交结果;资格审与桥接在 browserExtensionSlot。
if (type === 'browser-extension-request') {
return getGhostBrowserExtensionSlot().handleRequest(id, payload);
}
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 d84cba452b..76c5c24430 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
@@ -11,7 +11,7 @@
* 按需使用:用户在扩展里授权一次后,扩展只在这些动作期间临时接上调试(Chrome 会显示
* 提示条),做完即断开;未授权时明确告诉模型请用户开启,绝不悄悄换目标。旧版扩展只有
* 基础读取与交互,同样明确拒绝并提示更新;
- * - 每个作业都经桥接按插件保存的站点策略守门,结果脱敏后才回到这里。
+ * - 每个作业都经桥接校验地址,结果脱敏后才回到这里;不设站点名单(2026-10-30 决定)。
*
* 寻址:这里维护 targetId ↔ {连接, tabId, url} 的映射。新版扩展按 tabId 寻址;
* 旧版扩展按精确 URL 寻址,页面在两次调用之间跳转时报 PAGE_CHANGED,不猜新页。
@@ -548,7 +548,7 @@ export class UserBrowserBackend implements BrowserBackend {
ok: false,
result: actionFailed(
action,
- `标签页 ${record.targetId} 当前页面不允许读取(站点策略或本机地址)`,
+ `标签页 ${record.targetId} 当前页面无法读取(不是网页或文档不可访问)`,
'BROWSER_RUNTIME_INVALID_REQUEST',
),
};
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 7cc51d5e70..3303386bdb 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7383,7 +7383,7 @@
"previewDetail": "Only the sites listed below can be opened; every page it opens is attributed to this plugin.",
"browserExtension": "Lets its bundled browser extension connect to Cindy",
"browserExtensionDetail": "Only the extensions listed below can connect, over the local loopback address; Cindy hands requests the extension makes to this plugin.",
- "browserExtensionPageControlDetail": "Only the extensions listed below can connect. The extension also implements page control: with “My browser” selected, the agent can read and operate pages in the browser you are using, within the plugin's site permissions.",
+ "browserExtensionPageControlDetail": "Only the extensions listed below can connect. The extension also implements page control: with “My browser” selected, the agent can read and operate pages in the browser you are using.",
"nodeChildSpawn": "Its Node program can ask the host to start declared sub-processes from its package",
"nodeChildSpawnDetail": "Only JS files declared inside its own package can be started (same local permissions as the main program); arbitrary commands cannot be executed. Sub-processes are closed together when the plugin is disabled or exits.",
"skill": "Adds the skill \"{{name}}\" to your AI assistants",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 49a9473d63..3418ef5717 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7351,7 +7351,7 @@
"previewDetail": "開けるのは下に列挙されたサイトだけです。ページを開くたびに、どのプラグインが開いたかが表示されます。",
"browserExtension": "同梱のブラウザ拡張を Cindy に接続できます",
"browserExtensionDetail": "接続できるのは下に列挙された拡張だけです。接続はローカルのループバックアドレス経由で、拡張からの要求は Cindy がこのプラグインに引き渡します。",
- "browserExtensionPageControlDetail": "接続できるのは下に列挙された拡張だけです。この拡張はページ操作も実装しており、「自分のブラウザ」を選ぶと、エージェントはプラグインのサイト権限の範囲内で使用中のブラウザのページを読み取り・操作できます。",
+ "browserExtensionPageControlDetail": "接続できるのは下に列挙された拡張だけです。この拡張はページ操作も実装しており、「自分のブラウザ」を選ぶと、エージェントは使用中のブラウザのページを読み取り・操作できます。",
"nodeChildSpawn": "Node プログラムは、パッケージ内で申告済みのサブプロセスの起動をホストに依頼できます",
"nodeChildSpawnDetail": "起動できるのは自身のパッケージ内で申告済みの JS ファイルだけです(メインプログラムと同じローカル権限)。任意のコマンドは実行できません。プラグインの無効化や終了時にはサブプロセスも一緒に閉じられます。",
"skill": "AI アシスタントにスキル「{{name}}」を追加します",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 2a5f9d273d..799689be26 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7351,7 +7351,7 @@
"previewDetail": "아래에 나열된 사이트만 열 수 있으며, 페이지를 열 때마다 어떤 플러그인이 열었는지 표시됩니다.",
"browserExtension": "함께 제공되는 브라우저 확장을 Cindy에 연결할 수 있습니다",
"browserExtensionDetail": "아래에 나열된 확장만 연결할 수 있으며, 연결은 로컬 루프백 주소를 통해 이루어집니다. 확장이 보낸 요청은 Cindy가 이 플러그인에 전달합니다.",
- "browserExtensionPageControlDetail": "아래에 나열된 확장만 연결할 수 있습니다. 이 확장은 페이지 제어도 구현하므로 「내 브라우저」를 선택하면 에이전트가 플러그인의 사이트 권한 범위 안에서 사용 중인 브라우저의 페이지를 읽고 조작할 수 있습니다.",
+ "browserExtensionPageControlDetail": "아래에 나열된 확장만 연결할 수 있습니다. 이 확장은 페이지 제어도 구현하므로 「내 브라우저」를 선택하면 에이전트가 사용 중인 브라우저의 페이지를 읽고 조작할 수 있습니다.",
"nodeChildSpawn": "Node 프로그램이 패키지에 신고된 하위 프로세스 시작을 호스트에 요청할 수 있습니다",
"nodeChildSpawnDetail": "자신의 패키지 안에 신고된 JS 파일만 시작할 수 있으며(메인 프로그램과 동일한 로컬 권한), 임의의 명령은 실행할 수 없습니다. 플러그인이 비활성화되거나 종료되면 하위 프로세스도 함께 종료됩니다.",
"skill": "AI 어시스턴트에 스킬 \"{{name}}\"을(를) 추가합니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index e6cdd02ac1..7bfe41dad4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7351,7 +7351,7 @@
"previewDetail": "只能打开下方列出的网站;每次打开都会提示是哪个插件打开的。",
"browserExtension": "可让它自带的浏览器扩展连接到 Cindy",
"browserExtensionDetail": "只有下方列出的扩展能连接;连接经本机回环地址,由 Cindy 把扩展发起的请求转交给这个插件。",
- "browserExtensionPageControlDetail": "只有下方列出的扩展能连接。该扩展还实现页面控制:选择「我的浏览器」后,Agent 可经它读取和操作你正在使用的浏览器页面,受插件的站点权限约束。",
+ "browserExtensionPageControlDetail": "只有下方列出的扩展能连接。该扩展还实现页面控制:选择「我的浏览器」后,Agent 可经它读取和操作你正在使用的浏览器页面。",
"nodeChildSpawn": "Node 程序可请宿主再启动包内申报过的子进程",
"nodeChildSpawnDetail": "只能启动它自己包里申报过的 JS 文件(与主程序同样的本机权限),不能执行任意命令;插件停用或退出时子进程一并关闭。",
"skill": "为 AI 助手添加技能「{{name}}」",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 28df3682fa..f30fb027cc 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -7351,7 +7351,7 @@
"previewDetail": "只能開啟下方列出的網站;每次開啟都會提示是哪個插件開啟的。",
"browserExtension": "可讓它自帶的瀏覽器擴充功能連線到 Cindy",
"browserExtensionDetail": "只有下方列出的擴充功能能連線;連線經本機回環位址,由 Cindy 把擴充功能發起的請求轉交給這個插件。",
- "browserExtensionPageControlDetail": "只有下方列出的擴充功能能連線。該擴充功能還實作頁面控制:選擇「我的瀏覽器」後,Agent 可經它讀取和操作你正在使用的瀏覽器頁面,受插件的站點權限約束。",
+ "browserExtensionPageControlDetail": "只有下方列出的擴充功能能連線。該擴充功能還實作頁面控制:選擇「我的瀏覽器」後,Agent 可經它讀取和操作你正在使用的瀏覽器頁面。",
"nodeChildSpawn": "Node 程式可請宿主再啟動包內申報過的子處理程序",
"nodeChildSpawnDetail": "只能啟動它自己包裡申報過的 JS 檔案(與主程式同樣的本機權限),不能執行任意命令;插件停用或退出時子處理程序一併關閉。",
"skill": "為 AI 助手新增技能「{{name}}」",
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 3b18f03c7b..6c18e0ab5f 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -7140,9 +7140,9 @@ export type GhostPipePreviewResult =
* 上行:browserExtension 槽——插件经宿主桥接与自己的浏览器扩展通讯。
* - status:连接与安装状态(不读页面);
* - act:向扩展投递一个页面作业(action + payload 的形状由线协议定义,
- * 宿主按站点策略守门后分发,结果脱敏后返回);
- * - setPolicy / setTrustedClients:插件把自己保存的站点策略与配对身份
- * 推给宿主(策略由插件拥有,宿主缓存并在每个作业上强制);
+ * 宿主校验地址后分发,结果脱敏后返回);
+ * - setTrustedClients:插件把自己保存的配对身份推给宿主(宿主缓存);
+ * setPolicy 仅为兼容旧插件保留,站点名单已于 2026-10-30 取消,应答但不生效;
* - relayActive / relayProgress / relayResult:插件处理完宿主转交的扩展
* 请求(翻译、字幕等)后回传进度与结果。
*/
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 5c4ec75ca2..dd7deb9c08 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -139,9 +139,9 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
插件声明了也不会接管「我的浏览器」(2026-10-30 决定)。宿主代码里不得出现具体插件名
或专有协议:桥接按声明启停(`cindy-brain/browserExtensionSlot.ts`),扩展发起的请求经
`browser-extension-relay` 事件转交给声明插件,插件经 `browser-extension-request` 投递作业、
- 推送站点策略与配对身份。站点策略归插件所有,宿主只缓存到 owner 私有目录并在每个作业上
- 强制,没有缓存时在收到插件策略前拒绝页面作业;本机与私网地址和公网网站一样可访问,也可以
- 写进名单单独屏蔽(2026-10-28 决定)。新增 id 或新增 `pageControl` 视为权限变多,删减视为收权。
+ 推送配对身份。不设站点名单(2026-10-30 决定:安全交给任务的权限档位与自动审核,与专用浏览器
+ 一致);旧插件仍推送的 `setPolicy` 照常应答但不生效。本机与私网地址和公网网站一样可访问
+ (2026-10-28 决定)。新增 id 或新增 `pageControl` 视为权限变多,删减视为收权。
- 无配置的布尔能力只接受字面量 `true`:`notify`、`badge`、`confirm`、`fs`、`library`、
`sessionContext`、`pick`、`workspace`。不用就省略,写 `false` 是无效清单。
- `card: {}` 与 `agent: {}` 分别表示基础卡片能力和由真实用户点击触发 Agent 回合;
diff --git a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
index b026ce5984..fb9597d5b0 100644
--- a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
+++ b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
@@ -94,7 +94,7 @@
- 点击、坐标与拖拽是合成事件(非可信输入),个别要求可信输入的站点会忽略;页面 CSP 禁止脚本时 `evaluate` 报 `EVAL_BLOCKED_BY_PAGE`,改用 snapshot / extract。
- 控制台从第一次 `console` 调用开始捕获;`requests` 来自页面资源计时(无方法与请求头);`responseBody` 以页面身份重新请求该地址;`dialog` 预先应答页面下一个 alert / confirm / prompt,已经弹出的原生弹窗需要用户自己处理。
- 不支持:`saveResource` 与语义 `query`。`status.data.updateNote` 出现时说明扩展是旧版,只有基础读取与交互,请用户更新 Cindy 扩展。遇到不支持的操作先告诉用户,由用户决定是否改用专用浏览器,**不要自行 setBackend 切换**。
- - 站点策略归 Cindy Chrome 插件:读取默认开放,交互按站点授权(作业报 `INTERACT_NOT_ALLOWED` 时用该插件的 `browser_policy` 工具请求授权,需用户确认)。`profile` 是浏览器连接 id(一个浏览器用户配置一条),多条连接时必须指定,不要猜账号。
+ - `profile` 是浏览器连接 id(一个浏览器用户配置一条),多条连接时必须指定,不要猜账号。
- 页面跳转后旧 ref 失效(报 `STALE_REF`),先 `snapshot` 再继续;旧版扩展按 URL 寻址,跳转会报 `PAGE_CHANGED`,`navigate` 也可能落在另一个标签页并返回新的 targetId。`status.data.connected === false` 时请用户在自己的浏览器里安装并启用 Cindy 扩展,不要反复重试。
`setBackend` 与设置页修改同一个**全局、持久**选择,会影响其他正在使用浏览器的任务,旧模式的操作可能中断。仅按用户明确的模式要求切换,无需重复确认;不要因页面报错自行换模式。切换后重新 `tabs` / `snapshot`,不沿用旧模式的 targetId、ref 或登录态。宿主不支持切换或返回失败时如实说明,不能声称切换成功。