Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugins): 支持 OAuth 账号注入并统一会话审批
liugaowei5b564ba2860e
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex e284fd82a1..facd33c9b0 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -1865,8 +1865,9 @@ describe('FORGE_GUIDE', () => {'CONFIRM_DENIED','uploadDir','dir_deposit',- // 目录/保存交接的权限档契约:本地 Full Access 自动,其余/远程确认。+ // 目录/保存交接沿用会话档位:Full 自动、Auto 审阅、Ask/远程确认。'本地 Full Access 会话则自动过户、不弹卡',+ 'Auto 交当前会话统一审阅','远程会话仍由用户确认',// fs 槽(2026-07-14):三档代写(私有目录/工作目录/save 票据)。'fs-request',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.tsindex 02ca7898d8..65702f9078 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts@@ -3,7 +3,7 @@* 确认记忆 / save 票据透传 / 远程工作区拒绝。全部走注入 deps + os.tmpdir* 临时目录(规则 23:凭证与生成物不落仓库工作区),零 Electron。*/-import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';@@ -54,6 +54,7 @@ function makeHarness(dataRoot: string, overrides: HarnessOverrides = {}) {? {ghostId: overrides.callGhostId ?? GHOST_ID,sessionId: overrides.callSessionId === undefined ? 'sess-1' : overrides.callSessionId,+ sessionInstanceId: 'instance-1',scriptWorkdir: overrides.callScriptWorkdir ?? null,scriptWritePath: overrides.callScriptWritePath ?? null,channel: overrides.callChannel ?? (overrides.callSessionId === null ? 'script' as const : 'session' as const),@@ -89,7 +90,7 @@ describe('workdirWriteVerdict(权限映射表)', () => {it('免批模式直写,逐条模式确认,plan 拒,未知模式保守确认', () => {expect(workdirWriteVerdict('acceptEdits', false)).toBe('allow');expect(workdirWriteVerdict('bypassPermissions', false)).toBe('allow');- expect(workdirWriteVerdict('auto', false)).toBe('allow');+ expect(workdirWriteVerdict('auto', false)).toBe('review');expect(workdirWriteVerdict('ask', false)).toBe('confirm');expect(workdirWriteVerdict('default', false)).toBe('confirm');expect(workdirWriteVerdict('plan', false)).toBe('deny');@@ -396,6 +397,52 @@ describe('GhostFsSlot', () => {})).toMatchObject({ ok: false });});+ it.each(['allow', 'block', 'ask', 'unavailable'] as const)('workdir Auto follows review %s for every write', async (verdict) => {+ const reviewAction = vi.fn(async () => {+ if (verdict === 'unavailable') throw new Error('review unavailable');+ return { verdict };+ });+ const { slot, confirmCalls } = makeHarness(dataRoot, {+ session: { workingDir: workdir, permissionMode: 'auto', planModeEnabled: false, remoteHostId: null, reviewAction },+ });+ for (let i = 0; i < 2; i++) {+ expect(await slot.handleFsRequest(GHOST_ID, {+ type: 'fs-request', op: 'write', root: 'workdir', path: `auto-${i}.txt`, content: 'hello', callId: 'call-1',+ })).toMatchObject({ ok: verdict !== 'block' });+ expect(fs.existsSync(path.join(workdir, `auto-${i}.txt`))).toBe(verdict !== 'block');+ }+ expect(reviewAction).toHaveBeenCalledTimes(2);+ expect(reviewAction).toHaveBeenCalledWith(expect.objectContaining({ kind: 'file-write', resolvedWritableRoots: [await fs.promises.realpath(workdir)] }));+ expect(confirmCalls).toHaveLength(verdict === 'ask' || verdict === 'unavailable' ? 2 : 0);+ });++ it.each([false, true])('workdir rejects expired live permission even with fs declared (%s)', async (fsCapability) => {+ let current = true;+ const { slot, confirmCalls } = makeHarness(dataRoot, {+ fs: fsCapability,+ session: { workingDir: workdir, permissionMode: 'auto', planModeEnabled: false, remoteHostId: null,+ isCurrent: () => current, reviewAction: async () => { current = false; return { verdict: 'allow' }; } },+ });+ expect(await slot.handleFsRequest(GHOST_ID, {+ type: 'fs-request', op: 'write', root: 'workdir', path: 'expired.txt', content: 'hello', callId: 'call-1',+ })).toMatchObject({ ok: false });+ expect(fs.existsSync(path.join(workdir, 'expired.txt'))).toBe(false);+ expect(confirmCalls).toHaveLength(0);+ });++ it('workdir uses the injected live instance resolver, not the database permission snapshot', async () => {+ const { slot, confirmCalls } = makeHarness(dataRoot, {+ session: { workingDir: workdir, permissionMode: 'bypassPermissions', planModeEnabled: false, remoteHostId: null },+ });+ const resolve = vi.fn(async () => ({ workingDir: workdir, permissionMode: 'ask', planModeEnabled: false, remoteHostId: null }));+ slot.setSessionSnapshotResolver(resolve);+ expect(await slot.handleFsRequest(GHOST_ID, {+ type: 'fs-request', op: 'write', root: 'workdir', path: 'live.txt', content: 'hello', callId: 'call-1',+ })).toMatchObject({ ok: true });+ expect(resolve).toHaveBeenCalledWith('sess-1', 'instance-1');+ expect(confirmCalls).toHaveLength(1);+ });+it('workdir:read/list/delete 一律拒(仅 write)', async () => {const { slot } = makeHarness(dataRoot, {session: { workingDir: workdir, permissionMode: 'bypassPermissions', planModeEnabled: false, remoteHostId: null },diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.tsindex 9ec70b0136..db69d14041 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts@@ -1684,6 +1684,42 @@ describe('多实例共库的 RT 轮换竞态(invalid_grant 防误删)', () => {});describe('账号清单操作', () => {+ it('昵称独立保存、可清空,清单重写不覆盖昵称或凭据', () => {+ const vault = seededVault();+ const deps = { vault, fetchImpl: vi.fn() as unknown as typeof fetch, openExternal: vi.fn() };+ const mgr = new GhostOauthAccountManager(deps);+ const originalManifest = vault.read(GHOST, `${KEY}-accounts`);+ expect(mgr.renameAccount(GHOST, KEY, 'acc-1', ' 公司邮箱 ')).toBe('saved');+ expect(vault.read(GHOST, `${KEY}-accounts`)).toBe(originalManifest);+ expect(vault.read(GHOST, `${KEY}-rt-acc-1`)).toBe('rt-seed');+ mgr.setDefaultAccount(GHOST, KEY, 'acc-1');+ const reloaded = new GhostOauthAccountManager(deps);+ expect(reloaded.listAccounts(GHOST, KEY)[0]).toMatchObject({+ id: 'acc-1', label: '[email protected]', nickname: '公司邮箱', status: 'connected',+ });+ expect(reloaded.renameAccount(GHOST, KEY, 'acc-1', '')).toBe('saved');+ expect(reloaded.listAccounts(GHOST, KEY)[0]).not.toHaveProperty('nickname');+ reloaded.renameAccount(GHOST, KEY, 'acc-1', '私人邮箱');+ reloaded.disconnectAccount(GHOST, KEY, 'acc-1');+ expect(vault.read(GHOST, `${KEY}-nickname-acc-1`)).toBeNull();+ });++ it('昵称更新限定在现有账号,拒绝非法输入并报告落库失败', () => {+ const vault = seededVault();+ const mgr = new GhostOauthAccountManager({+ vault, fetchImpl: vi.fn() as unknown as typeof fetch, openExternal: vi.fn(),+ });+ const before = [...vault.data];+ expect(mgr.renameAccount('other-ghost', KEY, 'acc-1', '公司')).toBe('not-found');+ expect(mgr.renameAccount(GHOST, 'other-key', 'acc-1', '公司')).toBe('not-found');+ expect(mgr.renameAccount(GHOST, KEY, 'missing', '公司')).toBe('not-found');+ expect(mgr.renameAccount(GHOST, KEY, 'acc-1', 'x'.repeat(81))).toBe('invalid');+ expect(mgr.renameAccount(GHOST, KEY, 'acc-1', '公司\n邮箱')).toBe('invalid');+ expect([...vault.data]).toEqual(before);+ vault.store = () => false;+ expect(mgr.renameAccount(GHOST, KEY, 'acc-1', '公司')).toBe('write-failed');+ });+it('disconnect:摘行 + 清 rt + 默认账号顺延;setDefault 未知账号 → false', async () => {const vault = memoryVault({[`${KEY}-client-id`]: 'cid',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.tsindex 085c4858bd..94aa54fa9d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts@@ -1783,6 +1783,86 @@ describe('nodeRuntimeBroker · 权限与协议', () => {expect(spawnProcess).not.toHaveBeenCalled();});+ it('OAuth 注入按插件与显式账号解析,且不读取静态 Secret', async () => {+ const ghost = fakeGhost();+ ghost.manifest.network = { hosts: ['example.test'], secrets: [{+ key: 'mail_account', label: 'Mail', source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: { authorizeUrl: 'https://example.test/auth', tokenUrl: 'https://example.test/token', scopes: ['mail'] },+ }] };+ ghost.manifest.node!.secretBindings = [{+ key: 'access_token', label: 'Mail', methods: ['mail/run'], oauthSecret: 'mail_account',+ }];+ let child!: ReturnType<typeof makeAutoReplyProcess>;+ const readSecret = vi.fn();+ const resolveOauthSecret = vi.fn(async (_id: string, _key: string, account?: string) => ({+ ok: true as const, accessToken: `fake-token-${account ?? 'default'}`,+ }));+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost, readSecret, resolveOauthSecret,+ // OAuth 解析先异步完成,再创建假进程,避免 spawn 在宿主监听前发出。+ spawnProcess: () => (child = makeAutoReplyProcess()),+ });+ try {+ await broker.handleRequest('node-ghost', { ...rpcRequest('mail/run'), authAccount: 'account-a' });+ await broker.handleRequest('node-ghost', { ...rpcRequest('mail/run'), authAccount: 'account-b' });+ await broker.handleRequest('node-ghost', rpcRequest('mail/run'));+ await broker.handleRequest('node-ghost', rpcRequest('mail/schema'));+ expect(resolveOauthSecret.mock.calls).toEqual([+ ['node-ghost', 'mail_account', 'account-a'],+ ['node-ghost', 'mail_account', 'account-b'],+ ['node-ghost', 'mail_account', undefined],+ ]);+ expect(readSecret).not.toHaveBeenCalled();+ expect(child.received[0]).toMatchObject({ cindy: { secrets: { access_token: 'fake-token-account-a' } } });+ expect(child.received[1]).toMatchObject({ cindy: { secrets: { access_token: 'fake-token-account-b' } } });+ expect(child.received[3]).not.toHaveProperty('cindy');+ } finally { broker.destroyAll(); }+ });++ it('OAuth 无可用账号时不启动 Worker、不回退到静态凭据', async () => {+ const ghost = fakeGhost();+ ghost.manifest.network = { hosts: ['example.test'], secrets: [{+ key: 'mail_account', label: 'Mail', source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: { authorizeUrl: 'https://example.test/auth', tokenUrl: 'https://example.test/token', scopes: ['mail'] },+ }] };+ ghost.manifest.node!.secretBindings = [{+ key: 'access_token', label: 'Mail', methods: ['mail/run'], oauthSecret: 'mail_account',+ }];+ const spawnProcess = vi.fn();+ const readSecret = vi.fn();+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost, readSecret, spawnProcess,+ resolveOauthSecret: async () => ({ ok: false, error: 'NO_ACCOUNT' }),+ });+ const result = await broker.handleRequest('node-ghost', rpcRequest('mail/run'));+ expect(result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(readSecret).not.toHaveBeenCalled();+ expect(spawnProcess).not.toHaveBeenCalled();+ broker.destroyAll();+ });++ it('OAuth 刷新跨越停用再启用时不把旧调用交给新 Worker', async () => {+ const ghost = fakeGhost();+ ghost.manifest.network = { hosts: ['example.test'], secrets: [{+ key: 'mail_account', label: 'Mail', source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: { authorizeUrl: 'https://example.test/auth', tokenUrl: 'https://example.test/token', scopes: ['mail'] },+ }] };+ ghost.manifest.node!.secretBindings = [{ key: 'access_token', label: 'Mail', methods: ['run'], oauthSecret: 'mail_account' }];+ let finish!: (value: { ok: true; accessToken: string }) => void;+ const token = new Promise<{ ok: true; accessToken: string }>((resolve) => { finish = resolve; });+ const spawnProcess = vi.fn();+ const broker = new GhostNodeRuntimeBroker({ getGhost: () => ghost, spawnProcess, resolveOauthSecret: () => token });+ const request = broker.handleRequest('node-ghost', rpcRequest('run'));+ broker.stop('node-ghost');+ finish({ ok: true, accessToken: 'fake-token' });+ expect(await request).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(spawnProcess).not.toHaveBeenCalled();+ broker.destroyAll();+ });+it('只在清单绑定的方法中把 safeStorage 凭证注入 Worker 保留字段', async () => {const ghost = fakeGhost();ghost.manifest.node!.secretBindings = [diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 7317bacd5a..1c2cf27700 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -3062,6 +3062,8 @@ settingsHtml 里自填**(用户用自己注册的 OAuth 应用,配额风控归\`\`\`js// 状态回查(哪些 oauth 凭证项、client 配没配、连了哪些账号;零令牌字节):const list = await (await fetch('/oauth')).json();+// accounts 中可选 nickname 为用户昵称;与 label/账号 id 分离。按昵称匹配用户意图,歧义时询问,执行仍传 id。+// PUT /oauth/acct/accounts/<accountId>/nickname,body { nickname }:最长 80 字符,不含控制字符;空字符串清除昵称,204 成功。// → [{ key:'acct', clientConfigured:true, clientCustom:false, accounts:[{ id, label, status:'connected'|'expired', isDefault, createdAt, avatarDataUrl, scopeStale }] }]// avatarDataUrl = 头像 data URL(声明了 identity.avatarPath 且主机下载成功才有,否则 null;<img src> 直接用)// scopeStale = true 表示该账号有真实权限错误证据,或其全量授权快照未包含插件后来新增的 scope;账号仍可用,设置页应显示非阻塞提示并复用现有重新连接动作@@ -3155,8 +3157,8 @@ const r = await cindy.fetch({**目录上传(uploadDir,目录过户票据)**:要把用户的一个本地目录整体传给你的服务(静态站点部署等),流程是"主 agent 过户 → 你凭票上传"——主 agent 调ghost_call 时把目录**绝对路径**放在顶层 \`dir\` 参数(会话工作目录内直接放行,-工作目录外若主 agent 是本地 Full Access 会话则自动过户、不弹卡;其它权限档及-远程会话仍由用户确认;自动排除 node_modules/.git/.env 等),主机收集文件后把一次性限时票据注入你的+工作目录外若主 agent 是本地 Full Access 会话则自动过户、不弹卡;Auto 交当前会话统一审阅,+Ask 及远程会话仍由用户确认;自动排除 node_modules/.git/.env 等),主机收集文件后把一次性限时票据注入你的\`args.dir_deposit\`(含 token / file_count / total_bytes / rel_paths 相对路径清单);你在工具描述里写清"目录经 ghost_call 顶层 dir 交付",然后:@@ -3184,7 +3186,7 @@ preset 判定等纯逻辑);伪造/过期/别人的票据统一"票据无效"。(邮件附件、云盘文档等任意类型)存到用户本地时,流程同样是"主 agent 过户 →你凭票下载"——主 agent 调 ghost_call 时把**目标目录绝对路径**放在顶层\`save_dir\` 参数(目录必须已存在;会话工作目录内直接放行,工作目录外主机会-在本地 Full Access 下自动过户、不弹卡;其它权限档及远程会话仍弹确认卡),主机把限时+在本地 Full Access 下自动过户、不弹卡;Auto 交当前会话统一审阅,Ask 及远程会话仍弹确认卡),主机把限时票据注入你的 \`args.save_deposit\`(含 token / dir_name 目录名);你在工具描述里写清"下载目录经 ghost_call 顶层 save_dir 交付",然后:@@ -3934,6 +3936,15 @@ cindy.onHostMessage((msg) => {### 4.12.2 stdio MCP+Node 可通过既有 \`secretBindings\` 引用本插件 OAuth 账号,不必复制或重新授权:+\`{ key: 'access_token', label: '账号', methods: ['service/run'], oauthSecret: '已有的 network.secrets OAuth key' }\`。+引用必须指向同一插件的 \`source:'oauth'\` 声明;它不是新的可填写 Secret,设置页继续使用+\`/oauth\` 管理多账号。\`cindy.node.request({ method:'service/run', authAccount: accountId, params })\`+可选择账号,省略时使用该 OAuth 槽的默认账号。Host 刷新后仅把 access token 放入 Worker 的+\`cindy.secrets.access_token\`,不交付 refresh token;未绑定的方法不注入。+Worker 与它启动的 CLI 是受信任的原生代码,会接触短期令牌;不得回传、落盘或记录令牌,+每次调用使用独立子进程环境,不修改全局 \`process.env\`。令牌失效后的写操作不能自动重放。+把 \`protocol\` 改成 \`"mcp-stdio"\`,worker 实现标准的逐行 JSON-RPC MCP server。Cindy 会统一完成 \`initialize\` + \`notifications/initialized\`,你的 main.js 不要重复初始化,直接调用标准方法:diff --git a/apps/desktop/src/main/cindy-brain/fsSlot.ts b/apps/desktop/src/main/cindy-brain/fsSlot.tsindex 416a89d5b0..01521732e3 100644--- a/apps/desktop/src/main/cindy-brain/fsSlot.ts+++ b/apps/desktop/src/main/cindy-brain/fsSlot.ts@@ -12,8 +12,8 @@* cardService 严格反查当前 Agent 调用与 session,不信意识* 自报);当前 Agent 调用无需插件自主 fs 声明;**跟随会话* permission 模式**(映射表见 workdirWriteVerdict:免批模式- * 直写、逐条模式弹 fs_write 确认卡、plan 拒)。未声明 fs- * 而复用 Agent 授权时,每个实际落盘动作前还要重新确认同一+ * 直写、Auto 统一审阅、逐条模式弹 fs_write 确认卡、plan 拒)。+ * 每个实际落盘动作前还要重新确认同一* callId 仍严格在途并绑定该插件和会话;远程工作区* (remoteHostId 非空)明确拒——路径在远端机器,本地代写* 写不到(规则 26,首期不支持不静默坏)。@@ -39,9 +39,8 @@** 权限对齐哲学:意识写 workdir 的"吵闹程度"必须和主 agent 自己 Edit 文件* 完全一致——agent 免批的模式意识也免批,agent 逐条批的模式意识也逐条批。- * claude / codex / pi 共用 sessions.permission_mode 这一列(codex 的 approval/- * sandbox 由它映射派生,pi bridge 每次 tool_call 现读自己的运行时权限文件),- * 所以一张映射表覆盖三种 agent(规则 9:映射写死在代码,不靠 prompt 判断)。+ * claude / codex / pi 共用活跃 Session 的权限真相,不得从可能滞后的+ * DB permission_mode 或调用开始时的快照恢复自动授权。** 依赖注入(规则 14):fs 之外的能力(意识清单/票据库/session 快照/确认桥)* 全部经 deps,单测拿 tmpdir 直测零 Electron。@@ -49,6 +48,7 @@import * as fs from 'node:fs';import * as path from 'node:path';+import type { AutoReviewDecision, ReviewableAction } from '@cindy/maker-core';import {GHOST_FS_DATA_MAX_FILES,@@ -75,6 +75,9 @@ export interface FsSessionSnapshot {planModeEnabled: boolean;/** 非空 = SSH 远程工作区会话(workdir 在远端机器,本地代写必拒)。 */remoteHostId: string | null;+ /** 活跃 Session 的裁决与代次复核,不从数据库权限快照推定自动授权。 */+ reviewAction?: (action: ReviewableAction) => Promise<AutoReviewDecision>;+ isCurrent?: () => boolean;}export interface FsSlotDeps {@@ -86,21 +89,21 @@ export interface FsSlotDeps {callInfo(callId: string): { ghostId: string; sessionId: string | null; scriptWorkdir: string | null } | null;/*** callId → 严格在途反查(生产 = cardService.inFlightCallInfoOf):已交卷/- * 已清扫的条目返回 null。脚本通道(root:'workdir' 无会话分支)必须走它——- * 目录授权上下文在工具调用结束后不得继续有效(用完即废);会话通道沿用- * callInfo 宽限窗口径(有 permission 裁决第二道闸,既有行为不变)。+ * 已清扫的条目返回 null。所有 workdir 写入必须走它——+ * 目录授权上下文在工具调用结束后不得继续有效(用完即废)。* channel 用于拒绝话术分流(会话通道的无会话调用 ≠ 脚本通道);* scriptWritePath(脚本声明的 out_file)非空时只放行该路径。*/inFlightCallInfo(callId: string): {ghostId: string;sessionId: string | null;+ sessionInstanceId?: string;scriptWorkdir: string | null;scriptWritePath: string | null;channel: 'session' | 'script';} | null;- /** sessionId → 会话快照(生产查 localDb sessions 行;查无返回 null)。 */- getSessionSnapshot(sessionId: string): Promise<FsSessionSnapshot | null>;+ /** sessionId + instance → 活跃会话权限快照;查无或权限切换中返回 null。 */+ getSessionSnapshot(sessionId: string, sessionInstanceId?: string): Promise<FsSessionSnapshot | null>;/*** workdir 写确认卡(生产 = GhostGrantConfirmBridge.request;桥未就绪时* 调用方注入的实现应直接回拒绝,不抛)。@@ -122,12 +125,13 @@ export interface FsSlotDeps {};}-/** workdir 写入的三档裁决。 */-export type FsWorkdirVerdict = 'allow' | 'confirm' | 'deny';+/** workdir 写入裁决。 */+export type FsWorkdirVerdict = 'allow' | 'review' | 'confirm' | 'deny';/*** 会话 permission 模式 → workdir 写入裁决(claude / codex 共用,见文件头)。- * - acceptEdits / bypassPermissions / auto:文件编辑免批 → 意识直写;+ * - acceptEdits / bypassPermissions:文件编辑免批 → 意识直写;+ * - auto:将真实写入目标交给当前会话的统一审阅器;* - ask / default:agent 编辑要逐条批 → 意识写也弹确认卡;* - plan(历史遗留值)与 planModeEnabled:只读规划期 → 拒;* - 未知模式(未来新增):保守走确认,不静默放行。@@ -137,8 +141,9 @@ export function workdirWriteVerdict(permissionMode: string, planModeEnabled: booswitch (permissionMode) {case 'acceptEdits':case 'bypassPermissions':- case 'auto':return 'allow';+ case 'auto':+ return 'review';case 'ask':case 'default':return 'confirm';@@ -282,7 +287,16 @@ export class GhostFsSlot {*/private readonly workdirGrants = new Set<string>();- constructor(private readonly deps: FsSlotDeps) {}+ private sessionSnapshotResolver: FsSlotDeps['getSessionSnapshot'];++ constructor(private readonly deps: FsSlotDeps) {+ this.sessionSnapshotResolver = deps.getSessionSnapshot;+ }++ /** Maker 初始化后注入实时会话权限,保持插件运行时不反向依赖 Maker。 */+ setSessionSnapshotResolver(resolve: FsSlotDeps['getSessionSnapshot']): void {+ this.sessionSnapshotResolver = resolve;+ }/** 处理一条 fs-request(ghost-pipe:send 的 invoke 返回值即本结果)。 */async handleFsRequest(ghostId: string, payload: unknown): Promise<GhostPipeFsResult> {@@ -525,9 +539,15 @@ export class GhostFsSlot {let session: FsSessionSnapshot | null = null;let workingDir: string;let scriptWritePath: string | null = null;+ let sessionInstanceId: string | undefined;if (info.sessionId) {workdirSource = 'session';- session = await this.deps.getSessionSnapshot(info.sessionId);+ const inFlight = this.deps.inFlightCallInfo(callId);+ if (inFlight?.ghostId !== ghostId || inFlight.sessionId !== info.sessionId) {+ return fail('调用已交卷或已过期,工作目录写盘授权已失效');+ }+ sessionInstanceId = inFlight.sessionInstanceId;+ session = await this.sessionSnapshotResolver(info.sessionId, sessionInstanceId);if (!session) return fail('会话不存在,无法定位工作目录');if (session.remoteHostId) {return fail('当前会话是 SSH 远程工作区,工作目录在远端机器,意识写文件暂不支持(请改用 root:"data" 私有目录)');@@ -599,15 +619,29 @@ export class GhostFsSlot {// 会话通道继续往下(session 与 sessionId 在上方分支均已判空;此守卫只做类型收窄与防御)。if (!session || !info.sessionId) return fail('本次调用无会话上下文,无法定位工作目录');- const verdict = workdirWriteVerdict(session.permissionMode, session.planModeEnabled);+ let verdict = workdirWriteVerdict(session.permissionMode, session.planModeEnabled);if (verdict === 'deny') {return fail('当前会话处于计划/只读模式,不允许写工作目录');}+ const automaticReview = verdict === 'review';+ if (automaticReview) {+ let decision: AutoReviewDecision;+ try {+ decision = await session.reviewAction?.({+ kind: 'file-write', path: target, resolvedPath: target, resolvedWritableRoots: [realWorkdir],+ }) ?? { verdict: 'ask', unavailable: true };+ } catch {+ decision = { verdict: 'ask', unavailable: true };+ }+ if (session.isCurrent?.() === false) return fail('调用已交卷或已过期,工作目录写盘授权已失效');+ if (decision.verdict === 'block') return fail(decision.reason ?? 'Automatic review denied this file write.');+ verdict = decision.verdict === 'allow' ? 'allow' : 'confirm';+ }let confirmedMemoryKey: string | null = null;if (verdict === 'confirm') {const parentDir = path.dirname(target);const memoryKey = `${info.sessionId} ${ghostId} ${foldCase(parentDir)}`;- if (!this.workdirGrants.has(memoryKey)) {+ if (automaticReview || !this.workdirGrants.has(memoryKey)) {const decision = await this.deps.requestWriteConfirm(info.sessionId, {ghostId,ghostName: ghost.manifest.name || ghostId,@@ -621,19 +655,20 @@ export class GhostFsSlot {if (decision.reason === 'cancelled') return fail('用户拒绝了本次工作目录写入');return fail('确认通道未就绪或会话已关闭,本次工作目录写入未执行');}- confirmedMemoryKey = memoryKey;+ if (!automaticReview) confirmedMemoryKey = memoryKey;}}- // 未声明 fs 的插件只是在当前 Agent 调用期间借用会话文件权限。前面的+ // 插件只在当前 Agent 调用期间借用会话文件权限。前面的// session/path/confirm await 都可能给调用留下交卷窗口,不能把入口处的// 在途结果缓存到真正落盘时;mkdir 与 writeFile 各自都是文件副作用,// 因此分别在调用前复核同一 callId 仍绑定当前插件和会话。const stillHasLiveAgentWorkdirAuthorization = (): boolean => {- if (ghost.manifest.fs === true) return true;+ if (session?.isCurrent?.() === false) return false;const inFlight = this.deps.inFlightCallInfo(callId);return inFlight?.ghostId === ghostId&& inFlight.channel === 'session'+ && inFlight.sessionInstanceId === sessionInstanceId&& inFlight.sessionId === info.sessionId;};if (!stillHasLiveAgentWorkdirAuthorization()) {diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.tsindex a16119eee4..1a155287c8 100644--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts@@ -82,6 +82,8 @@ export type GhostOauthAccountStatus = 'connected' | 'expired';*/export interface GhostOauthAccountView {id: string;+ /** 用户昵称,仅用于展示和选账号,不参与 OAuth 身份合并。 */+ nickname?: string;label: string | null;status: GhostOauthAccountStatus;isDefault: boolean;@@ -249,6 +251,9 @@ function refreshTokenKey(secretKey: string, accountId: string): string {function avatarKey(secretKey: string, accountId: string): string {return `${secretKey}-avatar-${accountId}`;}+function nicknameKey(secretKey: string, accountId: string): string {+ return `${secretKey}-nickname-${accountId}`;+}function clientIdKey(secretKey: string): string {return `${secretKey}-client-id`;}@@ -760,9 +765,31 @@ export class GhostOauthAccountManager {listAccounts(ghostId: string, secretKey: string, decl?: GhostOauthDecl): GhostOauthAccountView[] {const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));- return manifest.accounts.map((a) =>- toView(a, manifest.defaultAccountId, this.readAvatar(ghostId, secretKey, a.id), decl?.scopes),- );+ return manifest.accounts.map((a) => {+ const nickname = this.deps.vault.read(ghostId, nicknameKey(secretKey, a.id));+ return {+ ...toView(a, manifest.defaultAccountId, this.readAvatar(ghostId, secretKey, a.id), decl?.scopes),+ ...(nickname ? { nickname } : {}),+ };+ });+ }++ /** 独立账号元数据:重连/旧版清单重写不会覆盖昵称,不修改凭据或身份。 */+ renameAccount(+ ghostId: string,+ secretKey: string,+ accountId: string,+ nickname: string,+ ): 'saved' | 'not-found' | 'invalid' | 'write-failed' {+ if (typeof nickname !== 'string' || nickname.length > 80) return 'invalid';+ if (Array.from(nickname).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {+ return 'invalid';+ }+ const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));+ if (!manifest.accounts.some((a) => a.id === accountId)) return 'not-found';+ return this.deps.vault.store(ghostId, nicknameKey(secretKey, accountId), nickname.trim())+ ? 'saved'+ : 'write-failed';}/** 默认账号相对当前声明缺失的 scope;空数组 = 无需重连或判不准。 */@@ -822,6 +849,7 @@ export class GhostOauthAccountManager {const remaining = manifest.accounts.filter((a) => a.id !== accountId);this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, accountId));this.deps.vault.remove(ghostId, avatarKey(secretKey, accountId));+ this.deps.vault.remove(ghostId, nicknameKey(secretKey, accountId));this.tokenCache.delete(this.cacheKey(ghostId, secretKey, accountId));this.deps.vault.store(ghostId,diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts b/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.tsindex 9d96c225a3..e8dd47db7d 100644--- a/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts+++ b/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts@@ -78,7 +78,7 @@ export function executeGhostSetupInlineSubmission(secret.source !== 'gh-cli' &&secret.source !== 'oidc-token',);- const nodeDecl = manifest.node?.secretBindings?.find((secret) => secret.key === secretKey);+ const nodeDecl = manifest.node?.secretBindings?.find((secret) => secret.key === secretKey && !secret.oauthSecret);const decl = networkDecl ?? nodeDecl;if (!decl) {return {diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.tsindex eb9bfd3f71..7484845c0e 100644--- a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts+++ b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts@@ -107,6 +107,7 @@ function deriveRequirementGroups(manifest: GhostManifest): GhostSetupRequirementimplicit.push({ kind: 'secret', key: s.key });}for (const s of manifest.node?.secretBindings ?? []) {+ if (s.oauthSecret) continue;implicit.push({ kind: 'secret', key: s.key });}for (const c of manifest.network?.connections ?? []) {diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex c09c4c1825..98722e0e8c 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1749,6 +1749,14 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {getGhost: findAvailableGhost,ownerScope: ghostOwnerScope,readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),+ resolveOauthSecret: async (ghostId, secretKey, accountId) => {+ const ghost = findAvailableGhost(ghostId);+ const source = ghost+ ? withRuntimeFiloGoogleClient(ghost.manifest).network?.secrets?.find((s) => s.key === secretKey)+ : undefined;+ if (source?.source !== 'oauth' || !source.oauth) return { ok: false, error: 'INVALID_DECLARATION' };+ return getGhostOauthAccountManager().getFreshAccessToken(ghostId, secretKey, source.oauth, accountId);+ },sendToGhost: (ghostId, payload) => {sendToGhostLogic(ghostId, payload);},@@ -5263,7 +5271,7 @@ let fsSlotSingleton: GhostFsSlot | null = null;/*** fs 槽单例(写文件,2026-07-14):deps 全部懒取现查——意识清单实扫、- * session 快照现查 localDb(用户会话中途切 permission 模式,下一单即生效)、+ * 会话权限由 Maker 注入的活跃 Session 读取器现查、* 确认卡桥现取(未初始化时按"确认通道未就绪"拒,不抛)。*/export function getGhostFsSlot(): GhostFsSlot {@@ -5274,10 +5282,11 @@ export function getGhostFsSlot(): GhostFsSlot {// callId → 归属/会话反查:与卡片供片同一本账(ghost_call 派单时// cardService.registerCall 登记),不信意识自报。callInfo: (callId) => getGhostCardService().callInfoOf(callId),- // 严格在途反查:脚本通道(无会话)的 workdir 写盘授权走它——交卷即失效,+ // 严格在途反查:所有 workdir 写盘授权走它——交卷即失效,// 不享宽限窗(目录授权上下文用完即废,与 workspace 槽同一判据)。inFlightCallInfo: (callId) => getGhostCardService().inFlightCallInfoOf(callId),- getSessionSnapshot: (sessionId) => getSessionFsSnapshot(sessionId),+ // Maker 未装配实时权限读取器前不能用数据库中的旧 Full Access 放行。+ getSessionSnapshot: async () => null,requestWriteConfirm: async (sessionId, payload) => {const bridge = getGhostGrantConfirmBridge();if (!bridge) return { confirmed: false, reason: 'session_closed' };@@ -6452,7 +6461,7 @@ export function registerGhostIpc(): void {const ghost = findAvailableGhost(ghostId);if (!ghost) return { status: 404 };const networkSecretDecls = ghost.manifest.network?.secrets ?? [];- const nodeSecretDecls = ghost.manifest.node?.secretBindings ?? [];+ const nodeSecretDecls = (ghost.manifest.node?.secretBindings ?? []).filter((s) => !s.oauthSecret);const userSecretKeys = networkSecretDecls// Host 派生与 oauth(主机托管授权)都没有"用户填值"这回事,// 不进 /secrets 收单键集(oauth 的 client 凭证走 /oauth 端点)。diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.tsindex 62de4f2be6..3b33c0a5c6 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts@@ -145,6 +145,10 @@ export interface GhostNodeRuntimeBrokerDeps {* 未保存或保险库不可用。调用方不得记录返回值。*/readSecret?: (ghostId: string, secretKey: string) => string | null;+ /** 只解析本插件显式引用的 OAuth 槽;不交付 refresh token。 */+ resolveOauthSecret?: (ghostId: string, secretKey: string, accountId?: string) => Promise<+ { ok: true; accessToken: string } | { ok: false; error: string }+ >;spawnProcess?: (entryPath: string, cwd: string, ghostId: string) => NodeWorkerProcess;/** 代启原样 stdio 子进程(childSpawn;缺省用 utilityProcess 适配器)。 */spawnChildProcess?: (@@ -795,10 +799,22 @@ export class GhostNodeRuntimeBroker {// getGhost 确认插件当前已启用——这是按需插件的"后更新/重启边界",// 清除 stop() 留下的停止标记,使按需进程可以恢复启动。this.stoppedGhosts.delete(ghostId);+ const requestGeneration = this.stopGeneration.get(ghostId) ?? 0;+ const requestManifest = JSON.stringify(ghost.manifest);+ const requestStillCurrent = (): boolean => {+ const current = this.deps.getGhost(ghostId);+ return !this.destroyed && current?.enabled === true+ && (this.stopGeneration.get(ghostId) ?? 0) === requestGeneration+ && JSON.stringify(current.manifest) === requestManifest;+ };if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {return errorResult('INVALID_REQUEST', 'node-request 载荷必须是对象');}const request = payload as Record<string, unknown>;+ if (request.authAccount !== undefined &&+ (typeof request.authAccount !== 'string' || request.authAccount.length === 0 || request.authAccount.length > 64)) {+ return errorResult('INVALID_REQUEST', 'authAccount 必须是 1–64 字符的账号 id');+ }if (request.type !== 'node-request') {return errorResult('INVALID_REQUEST', '请求类型必须是 node-request');}@@ -885,7 +901,28 @@ export class GhostNodeRuntimeBroker {clearHostSecrets(hostSecrets);return errorResult('PERMISSION_DENIED', 'Plugin owner boundary is not stable');}- const value = this.deps.readSecret?.(ghostId, binding.key) ?? null;+ let value: string | null;+ if (binding.oauthSecret !== undefined) {+ const source = ghost.manifest.network?.secrets?.find((s) => s.key === binding.oauthSecret);+ if (source?.source !== 'oauth' || !source.oauth || !this.deps.resolveOauthSecret) {+ clearHostSecrets(hostSecrets);+ return errorResult('PERMISSION_DENIED', 'Node OAuth 凭证声明无效或当前客户端不支持');+ }+ const resolved = await this.deps.resolveOauthSecret(+ ghostId, binding.oauthSecret, request.authAccount as string | undefined,+ );+ if (!requestStillCurrent() || !this.ownerScopeUsable(ghostId, ownerScopeSnapshot)) {+ clearHostSecrets(hostSecrets);+ return errorResult('PERMISSION_DENIED', 'Plugin owner boundary is not stable');+ }+ if (!resolved.ok) {+ clearHostSecrets(hostSecrets);+ return errorResult('PERMISSION_DENIED', '账号不可用,请在插件详情页检查授权');+ }+ value = resolved.accessToken;+ } else {+ value = this.deps.readSecret?.(ghostId, binding.key) ?? null;+ }if (value === null) {clearHostSecrets(hostSecrets);return errorResult(@@ -909,6 +946,10 @@ export class GhostNodeRuntimeBroker {try {entry = await this.ensureWorker(ghost, entryRel, ownerScopeSnapshot);this.assertOwnerScopeUsable(ghostId, ownerScopeSnapshot);+ if (!requestStillCurrent()) {+ clearHostSecrets(hostSecrets);+ return errorResult('PERMISSION_DENIED', '插件已停止或更新,请重新发起调用');+ }} catch (error) {clearHostSecrets(hostSecrets);if (error instanceof WorkerStartError && error.ownerBoundary) {@@ -933,6 +974,7 @@ export class GhostNodeRuntimeBroker {}}if (hostSecrets) {+ if (!requestStillCurrent()) return errorResult('PERMISSION_DENIED', '插件已停止或更新,请重新发起调用');for (const v of Object.values(hostSecrets)) {if (v) entry.exposedSecretValues.add(v);}@@ -1231,6 +1273,7 @@ export class GhostNodeRuntimeBroker {/** 停用、更新或卸载一个插件时立即停止其名下**全部** Node 进程。 */stop(ghostId: string): void {+ this.stopGeneration.set(ghostId, (this.stopGeneration.get(ghostId) ?? 0) + 1);this.stoppedGhosts.add(ghostId);for (const starting of [...(this.startingChildren.get(ghostId) ?? [])]) {this.stopStartingChild(starting);@@ -1426,6 +1469,8 @@ export class GhostNodeRuntimeBroker {/** stop(ghostId) 置入:在途重试检测到后立即中止,不继续拉新进程。 */private readonly stoppedGhosts = new Set<string>();+ /** 阻止刷新 OAuth 令牌期间跨停用/升级边界交付旧调用。 */+ private readonly stopGeneration = new Map<string, number>();/** 每次 handleExit 递增,settleExit 仅在世代未推进时发布 crashed。 */private readonly exitGen = new Map<string, number>();diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.tsindex a061f958ad..6e7f30b138 100644--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts@@ -51,6 +51,7 @@ function fakeManager(})),disconnectAccount: vi.fn(),setDefaultAccount: vi.fn(() => true),+ renameAccount: vi.fn(() => 'saved' as const),reportInsufficientScopes: vi.fn(() => 'stored' as const),...overrides,};@@ -76,6 +77,40 @@ function call(params: {});}+describe('PUT /oauth/<key>/accounts/<id>/nickname', () => {+ it('只向当前插件的目标账号写昵称', async () => {+ const manager = fakeManager();+ const outcome = await call({+ method: 'PUT', pathname: '/oauth/acct/accounts/acc-1/nickname',+ body: JSON.stringify({ nickname: '公司邮箱' }), manager,+ });+ expect(outcome.status).toBe(204);+ expect(manager.renameAccount).toHaveBeenCalledWith(GHOST, 'acct', 'acc-1', '公司邮箱');+ });++ it('拒绝非法请求,不调用账号管理器', async () => {+ const manager = fakeManager();+ const pathname = '/oauth/acct/accounts/acc-1/nickname';+ for (const body of ['{}', '{broken', '{"nickname":42}', '{"nickname":"x","account":"acc-2"}']) {+ expect((await call({ method: 'PUT', pathname, body, manager })).status).toBe(400);+ }+ expect((await call({ method: 'POST', pathname, manager })).status).toBe(405);+ expect((await call({ method: 'PUT', pathname: '/oauth/other/accounts/acc-1/nickname', manager })).status).toBe(404);+ expect(manager.renameAccount).not.toHaveBeenCalled();+ });++ it.each([['not-found', 404], ['invalid', 400], ['write-failed', 500]] as const)(+ '%s 不伪报保存成功', async (result, status) => {+ const outcome = await call({+ method: 'PUT', pathname: '/oauth/acct/accounts/acc-1/nickname',+ body: JSON.stringify({ nickname: '公司邮箱' }),+ manager: fakeManager({ renameAccount: () => result }),+ });+ expect(outcome.status).toBe(status);+ },+ );+});+describe('GET /oauth', () => {it('回全部 oauth 凭证槽状态,零令牌字节', async () => {const manager = fakeManager();diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.tsindex 5ab29af614..480ea4d5e8 100644--- a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts@@ -69,6 +69,7 @@ export interface GhostOauthEndpointManager {): Promise<GhostOauthConnectResult>;disconnectAccount(ghostId: string, secretKey: string, accountId: string): void;setDefaultAccount(ghostId: string, secretKey: string, accountId: string): boolean;+ renameAccount(ghostId: string, secretKey: string, accountId: string, nickname: string): 'saved' | 'not-found' | 'invalid' | 'write-failed';/** 'unchanged' = 证据已在库未重写(调用方跳过广播);false = 无默认账号或写失败。 */reportInsufficientScopes(ghostId: string,@@ -317,6 +318,24 @@ export async function handleGhostOauthRequest(args: {}}+ if (action === 'accounts' && segments.length === 4 && segments[3] === 'nickname') {+ if (method !== 'PUT') return { status: 405 };+ const parsed = await readJsonBody();+ if (!parsed.ok) return { status: parsed.status };+ const nickname = parsed.body.nickname;+ if (typeof nickname !== 'string' || Object.keys(parsed.body).some((key) => key !== 'nickname')) return { status: 400 };+ try {+ const result = await runMutation(() => manager.renameAccount(ghostId, secretKey, segments[2], nickname));+ if (result === 'not-found') return { status: 404 };+ if (result === 'invalid') return { status: 400 };+ if (result === 'write-failed') return { status: 500 };+ notifyChanged(secretKey);+ return { status: 204 };+ } catch {+ return { status: 500 };+ }+ }+if (action === 'accounts' && segments.length === 3) {if (method !== 'DELETE') return { status: 405 };const accountId = segments[2];diff --git a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.tsindex 4a33987208..822209f840 100644--- a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts+++ b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts@@ -13,9 +13,10 @@* 判定顺序(从最窄到最宽):* 1. READ_ONLY_MCP_TOOLS —— 精确到工具的只读发现入口,server 未整体可信也放行* 2. cindy_contacts —— 按内层 action 细粒度判定(见 contacts/approval.ts)- * 3. cindy-art ghost_call —— 第一方作图/视频内层工具静默;其它插件仍逐次确认+ * 3. cindy-art ghost_call —— 第一方作图/视频内层工具静默;其它插件继续走会话审批* 4. TRUSTED_MCP_SERVERS —— 已 review 的第一方 server,整体静默- * 5. 其余 —— 逐次弹窗(第三方 server、cindy_ssh、其它 ghost_call…)+ * 5. 其余 —— 进入会话审批(第三方 server、cindy_ssh、其它 ghost_call…)+ * 风险分类不覆盖会话档位:Full Access 免操作审批,Auto 走统一审阅,Ask 才交用户确认。*/import type {@@ -76,7 +77,7 @@ const READ_ONLY_MCP_TOOLS: ReadonlySet<string> = new Set([** 这里不能按 `cindy_` 前缀放行:namespace 只表示品牌归属,不代表新 provider* 已完成权限 review。SSH(在已配置主机上跑任意命令)、插件宿主 `cindy`- * (`ghost_call` 转发到第三方插件沙箱)与第三方 server 都不在表内,继续逐次确认;+ * (`ghost_call` 转发到第三方插件沙箱)与第三方 server 都不在表内,继续走会话审批;* Contacts 走 inner-tool 细粒度策略。*/const TRUSTED_MCP_SERVERS: ReadonlySet<string> = new Set([diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 818a99a098..9f69bcb76e 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -321,6 +321,7 @@ import {captureSessionRecycleScope,clearSessionContextInDb,createSessionRemoteHostIdReader,+ getSessionFsSnapshot,getSessionRowSnapshot,getSessionRowSnapshotStrict,persistSessionFields,@@ -9565,6 +9566,31 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 的会话聚焦通道。注入方式与 setGhostAgentTurnRunner 同款倒置,避免// cindy-brain 反向依赖 maker-ipc / localDb 形成模块环。setGhostLibraryExtraDirSync(syncLibraryReadonlyExtraDir);+ getGhostFsSlot().setSessionSnapshotResolver(async (sessionId, instanceId) => {+ const session = getMaker().getSession(sessionId);+ if (!instanceId || !session || session.instanceId !== instanceId) return null;+ const permission = session.stablePermissionModeState;+ if (!permission) return null;+ const workDir = session.workDir;+ const isCurrent = () => getMaker().getSession(sessionId) === session+ && session.workDir === workDir+ && session.stablePermissionModeState?.generation === permission.generation;+ const snapshot = await getSessionFsSnapshot(sessionId);+ if (!snapshot || !isCurrent()) return null;+ return {+ ...snapshot,+ workingDir: workDir,+ remoteHostId: session.remoteHostId,+ permissionMode: permission.mode ?? 'ask',+ isCurrent,+ reviewAction: async (action) => {+ const decision = await session.reviewHostPermissionAction(action);+ return isCurrent()+ ? decision+ : { verdict: 'block', reason: 'Task or permissions changed; retry with the current scope.' };+ },+ };+ });setGhostWorkspaceSessionService({reviewPermissionAction: async (sessionId, instanceId, action) => {const session = getMaker().getSession(sessionId);diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.tsindex 4ae27c8874..f185b412e3 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts@@ -2122,6 +2122,21 @@ describe('Full Access 插件文件交接', () => {describe('Host Auto review', () => {+ it.each(['claude-code', 'codex', 'pi'] as const)('%s media reveal follows Full access and a later switch to Ask', async (agentKind) => {+ let permissionMode = 'bypassPermissions';+ const reviewAction = vi.fn();+ liveGrantStateMock.mockImplementation(() => ({ permissionMode, remoteHostId: null, reviewAction }));+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;+ callCindyMediaMock.mockResolvedValue({ ok: true, url, local_path: process.execPath, mime_type: 'image/png' });+ const deps = makeDeps(agentKind, 'full-media');+ expect(await deps.callMedia?.({ action: 'resolve_local_path', url })).toMatchObject({ ok: true });+ expect(confirmRequestMock).not.toHaveBeenCalled();+ expect(reviewAction).not.toHaveBeenCalled();+ permissionMode = 'ask';+ await deps.callMedia?.({ action: 'resolve_local_path', url });+ expect(confirmRequestMock).toHaveBeenCalledOnce();+ });+it.each(['lookup', 'review'] as const)('media %s failure falls back to real confirmation', async (failure) => {const reviewAction = vi.fn(async () => { throw new Error('review unavailable'); });liveGrantStateMock.mockImplementation(() => {diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.tsindex ec26e5aa65..e19e0b5ee8 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -462,7 +462,7 @@ async function requestGrantConfirm(params: {}/**- * 媒体仓路径揭示按当前 Auto 审阅或既有人工确认授权;审阅故障回退确认。+ * 媒体仓路径揭示沿用当前会话权限;远端权限不能授权控制端的本机路径。*/async function requestMediaPathRevealConfirm(params: {sessionId: string | null;@@ -481,6 +481,9 @@ async function requestMediaPathRevealConfirm(params: {if (params.sessionInstanceId && params.getLiveSessionGrantState) {try {const live = params.getLiveSessionGrantState(params.sessionId, params.sessionInstanceId);+ if (live?.permissionMode === 'bypassPermissions' && !live.remoteHostId) {+ return { ok: true };+ }if (live?.permissionMode === 'auto' && live.reviewAction) {const decision = await live.reviewAction(toolAutoReviewAction('cindy_media.resolve_local_path', {path: params.absPath, mimeType: params.mimeType,diff --git a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsxindex f66801c636..fc787d0910 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx@@ -1,4 +1,4 @@-import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';+import { useEffect, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { CircleAlert, LayoutGrid, MoonStar } from 'lucide-react';import type { WebviewTag } from 'electron';@@ -13,13 +13,11 @@ import {observeHostTheme,} from './ghostPanelTheme';import {- GHOST_SETTINGS_LAYOUT_REVISION,- loadGhostSettingsSnapshot,- saveGhostSettingsSnapshot,- snapshotMatchesContext,- snapshotMatchesWidth,- type GhostSettingsSnapshot,-} from './ghostSettingsSnapshot';+ GHOST_SETTINGS_HEIGHT_MIN,+ GHOST_SETTINGS_HEIGHT_MAX,+ loadGhostSettingsHeight,+ saveGhostSettingsHeight,+} from './ghostSettingsHeight';/*** 意识「自定义设置区」卡片(settingsHtml 渲染通道):设置页详情里@@ -34,12 +32,9 @@ import {* 两次兜后到的布局/字体;声明了 settingsHeight 则固定该值,并保持作者布局* 完全不受宿主响应式规则干预。*- * 视觉连续性(规则 7):guest 首帧不可能与宿主同帧(独立渲染进程,- * attach→装载→绘制天然晚数帧)——追不平就贴快照:渲染稳定后把 guest 画面- * capturePage 存起来(ghostSettingsSnapshot,跨 app 重启可用),下次进入- * 首帧直接显示这张位图(高度也用它留位),webview 在图底下透明装载,主题- * CSS 落地后撤图换真身——像素一致,肉眼无感。快照失配(首开 / 版本 / 主题 /- * 宽度 / DPR 变化)时退回老路径:透明占位 + 一次性淡入,没有半成品帧。+ * 重开时仅缓存高度留位,不保存或重放 guest 画面:昵称、账号状态、菜单等+ * 都可能在尺寸不变时更新,旧截图不能冒充当前界面。每次挂载创建新 guest,+ * 主题与布局注入完成后展示真实页面,卸载时销毁 guest 与所有宿主监听。* 凭证输入不在这里:input:'host' 凭证仍宿主渲染;input:'ghost' 凭证由本区* 收单后经 /secrets 只写通道入库,意识读不回明文。*/@@ -47,8 +42,8 @@ import {/** 量到内容高之前的占位高(透明期的留位,不是内容下限)。 */const AUTO_HEIGHT_PLACEHOLDER = 160;/** 量高结果的 clamp 区间:矮内容真收下去(48 兜非法/塌零),高内容 800 封顶。 */-const AUTO_HEIGHT_MIN = 48;-const AUTO_HEIGHT_MAX = 800;+const AUTO_HEIGHT_MIN = GHOST_SETTINGS_HEIGHT_MIN;+const AUTO_HEIGHT_MAX = GHOST_SETTINGS_HEIGHT_MAX;/*** 自适应高度设置 guest 的结构 CSS(dom-ready 注入,id 守卫幂等):@@ -86,24 +81,6 @@ const AUTO_HEIGHT_MEASURE_SCRIPT = `(function(){var de=document.documentElement,*/const GHOST_SETTINGS_RESIZE_PING = '__xdt_ghost_settings_resize__';-/** 揭示(webview opacity 1)到撤快照图的间隔:盖过 0.12s 淡入 + 一帧余量。 */-const SNAPSHOT_SWAP_DELAY_MS = 180;-/** 渲染稳定后到拍快照的静默期(等 measure / 字体 / 主题注入全部尘埃落定)。 */-const SNAPSHOT_CAPTURE_DEBOUNCE_MS = 800;-/**- * 快照兜底撤图时限:贴图后 guest 迟迟到不了揭示点(装载失败 / attach 被拒 /- * guest 挂起)就撤图退回透明占位——旧世界的这类失败是诚实的空白,绝不能让- * 一张位图冒充活界面无限期骗人。- */-const SNAPSHOT_FAILSAFE_MS = 5000;--/**- * 自适应模式下各意识上次量得的高度(渲染进程会话级缓存):重开详情页时- * 先按上次高度留位,首帧即终态,不再每次都从最小高再长一截。- * 冷启动(本会话没量过)时退到持久化快照里的高度,再退占位高。- */-const lastMeasuredHeights = new Map<string, number>();-/** 沉睡态提示(attach 闸只放行唤醒的意识,沉睡时不建 webview,否则必被拒成白屏)。 */function AsleepHint({ appearance }: { appearance: 'settings' | 'plugin' }): ReactNode {const { t } = useTranslation();@@ -175,40 +152,12 @@ function SettingsWebviewBody({const fixedHeight = manifest.settingsHeight;const buildSettingsThemeCss =appearance === 'plugin' ? buildGhostPluginSettingsThemeCss : buildGhostSettingsThemeCss;- // 首帧贴的快照(仅 mount 时决定一次;版本/主题/DPR 现场比对,宽度等布局后- // 由下方 layout effect 补验)。失配 = null,走透明占位 + 淡入的老路径。- const [snapshot, setSnapshot] = useState<GhostSettingsSnapshot | null>(() => {- const snap = loadGhostSettingsSnapshot(dataOwnerId, manifest.id);- if (!snap) return null;- const ctx = {- version: manifest.version,- themeCss: buildSettingsThemeCss(),- dpr: window.devicePixelRatio,- };- return snapshotMatchesContext(snap, ctx) ? snap : null;- });- // 自适应模式的量高结果;初值:本会话量高缓存 → 持久化快照高度(只认同- // 版本——换版后界面可能全变,旧高度不可信;主题/DPR 不影响布局高,不卡)- // → 占位高。前两级命中时首帧即终态,零跳变。固定高度声明时本状态不参与。- const [autoHeight, setAutoHeight] = useState(() => {- const cached = lastMeasuredHeights.get(`${dataOwnerId ?? ''}:${manifest.id}`);- if (cached !== undefined) return cached;- const snap = loadGhostSettingsSnapshot(dataOwnerId, manifest.id);- return snap && snap.version === manifest.version ? snap.height : AUTO_HEIGHT_PLACEHOLDER;- });-- // 快照宽度校验只能等容器布局后做——放 layout effect(首次 paint 前同步跑),- // 失配在第一帧画出来之前就撤图,不会闪一张错位图。- useLayoutEffect(() => {- if (!snapshot) return;- const host = hostRef.current;- if (!host) return;- if (!snapshotMatchesWidth(snapshot, host.getBoundingClientRect().width)) {- setSnapshot(null);- }- // 仅首帧校验:后续容器宽度变化(拖窗口)时快照多半已撤;没撤也只是- // 位图被拉伸 180ms,随换真身消失,不值得挂 ResizeObserver。- }, []);+ // 仅复用同 owner、同插件版本的高度;账号文字和菜单由新 guest 实时渲染。+ const [autoHeight, setAutoHeight] = useState(+ () =>+ loadGhostSettingsHeight(dataOwnerId, manifest.id, manifest.version) ??+ AUTO_HEIGHT_PLACEHOLDER,+ );useEffect(() => {if (crashed || !settingsHtml) return;@@ -217,95 +166,28 @@ function SettingsWebviewBody({const webview = document.createElement('webview') as WebviewTag;webview.setAttribute('partition', partitionClaim);webview.setAttribute('src', `${GHOST_SCHEME}://${manifest.id}/${settingsHtml}`);- // 先透明占位:guest 装载与主题注入完成前不露面(一次性淡入,非常驻动画)。- // 有快照时快照图盖在上层,这段透明期用户看到的就是"成品画面"。- webview.setAttribute(- 'style',- 'display:flex;flex:1 1 auto;width:100%;height:100%;opacity:0;transition:opacity 0.12s ease;',- );+ // 先透明留位,主题与布局注入完成后直接展示真实页面,不覆盖历史画面。+ webview.setAttribute('style', 'display:flex;flex:1 1 auto;width:100%;height:100%;opacity:0;');let disposed = false;let themeTimer: ReturnType<typeof setTimeout> | null = null;- let snapshotSwapTimer: ReturnType<typeof setTimeout> | null = null;- let captureTimer: ReturnType<typeof setTimeout> | null = null;- // 兜底撤图:超时未揭示(装载失败/挂起)就把快照图撤掉退回透明占位,- // 不让位图冒充活界面;正常揭示路径先行撤图后,这里触发是幂等 no-op。- const snapshotFailsafeTimer = setTimeout(() => {- if (!disposed) setSnapshot(null);- }, SNAPSHOT_FAILSAFE_MS);const measureTimers: Array<ReturnType<typeof setTimeout>> = [];// 状态机见 createGhostThemeInjector:换肤误触发去重、dom-ready 无条件重灌。// 基线用设置卡片色(buildGhostSettingsThemeCss),与宿主卡片无缝。const injector = createGhostThemeInjector(webview, buildSettingsThemeCss);- // 拍快照(debounce):等渲染尘埃落定后把 guest 画面存进快照缓存,给下次- // 进入贴首帧用。guest 内部滚动过(内容超 800 clamp)时跳过——快照永远- // 存"从头开始"的画面,与下次装载的初始滚动位一致。失败静默:快照只是- // 体验增强,拍不成不影响任何功能。- const scheduleCapture = () => {- if (captureTimer !== null) clearTimeout(captureTimer);- captureTimer = setTimeout(() => {- captureTimer = null;- void (async () => {- if (disposed) return;- try {- // 三道拍摄前置检查(一次往返,任一命中即跳过本次拍摄):- // ① guest 内部滚动过——快照永远存"从头开始"的画面(见上);- // ② 任一文本类输入框有未保存内容;③ 焦点落在可编辑元素上- // (input / textarea / contenteditable,正在输入中)。②③ 是凭证- // 泄漏防线:设置区就是意识收 API key 的地方,输入中的明文绝不能- // 以位图形式落进快照(localStorage 未加密)。宁可这次不拍(下次- // 进入退回淡入路径),不冒泄漏面。守卫跑在不受信 guest 里只防- // 意外不防恶意——恶意意识本来就能读到用户输进它页面的一切,- // 快照不为它新增任何能力。- const state: unknown = await webview.executeJavaScript(- '(function(){var s=window.scrollY||document.documentElement.scrollTop||0;var d=false;var els=document.querySelectorAll("input,textarea");for(var i=0;i<els.length;i++){var e=els[i];var t=(e.type||"").toLowerCase();if(t==="checkbox"||t==="radio"||t==="button"||t==="submit"||t==="range")continue;if(e.value){d=true;break}}var a=document.activeElement;if(a&&(a.tagName==="INPUT"||a.tagName==="TEXTAREA"||a.isContentEditable))d=true;return{scrolled:s>0,dirty:d}})()',- );- if (disposed) return;- const flags = state as { scrolled?: unknown; dirty?: unknown } | null;- if (!flags || flags.scrolled !== false || flags.dirty !== false) return;- const image = await webview.capturePage();- if (disposed) return;- const rect = host.getBoundingClientRect();- if (rect.width <= 0 || rect.height <= 0) return;- saveGhostSettingsSnapshot(dataOwnerId, manifest.id, {- dataUrl: image.toDataURL(),- width: rect.width,- height: rect.height,- dpr: window.devicePixelRatio,- themeCss: buildSettingsThemeCss(),- version: manifest.version,- layoutRevision: GHOST_SETTINGS_LAYOUT_REVISION,- capturedAt: Date.now(),- });- } catch {- // capturePage / executeJavaScript 在 guest 半途销毁等场景会抛,忽略。- }- })();- }, SNAPSHOT_CAPTURE_DEBOUNCE_MS);- };const scheduleInjectTheme = () => {if (themeTimer !== null) return;themeTimer = setTimeout(() => {themeTimer = null;if (disposed) return;injector.inject();- // 换肤后的画面是新配色,旧快照已失配——重新拍一张。- scheduleCapture();}, 50);};- // 淡入揭示(幂等):挂在 dom-ready 后首个 executeJavaScript 回程上——+ // 揭示(幂等):挂在 dom-ready 后首个 executeJavaScript 回程上——// 同一 webContents 的 IPC 有序,该回程返回时 onDomReady 里先发的- // insertCSS 必已作用于 guest,首个可见帧就是成品样式。贴着快照时再等- // 一拍撤图(guest 与位图像素一致,交换无感);随后择机拍新快照。+ // insertCSS 必已作用于 guest,首个可见帧就是成品样式。const reveal = () => {if (disposed) return;webview.style.opacity = '1';- if (snapshotSwapTimer === null) {- snapshotSwapTimer = setTimeout(() => {- snapshotSwapTimer = null;- if (!disposed) setSnapshot(null);- }, SNAPSHOT_SWAP_DELAY_MS);- }- scheduleCapture();};// 自适应量高:宿主主动 executeJavaScript 读 guest 文档高度(零桥模型// 不破——是嵌入方读,不是 guest 上行);返回值不受信,非数字丢弃、@@ -318,7 +200,7 @@ function SettingsWebviewBody({.then((h: unknown) => {if (disposed || typeof h !== 'number' || !Number.isFinite(h)) return;const clamped = Math.max(AUTO_HEIGHT_MIN, Math.min(AUTO_HEIGHT_MAX, Math.ceil(h)));- lastMeasuredHeights.set(`${dataOwnerId ?? ''}:${manifest.id}`, clamped);+ saveGhostSettingsHeight(dataOwnerId, manifest.id, manifest.version, clamped);setAutoHeight((cur) => (cur === clamped ? cur : clamped));}).catch(() => {})@@ -338,8 +220,6 @@ function SettingsWebviewBody({resizeDebounce = setTimeout(() => {resizeDebounce = null;measure();- // 内容尺寸变了 = 画面变了,快照跟着刷新。- scheduleCapture();}, 80);};const onDomReady = () => {@@ -370,33 +250,21 @@ function SettingsWebviewBody({const onGone = () => {if (!disposed) setCrashed(true);};- // 装载失败(资源缺失 / 供片闸拒绝等):立刻撤快照图,失败就诚实地空白,- // 与旧世界同款表现(errorCode -3 = ABORTED,导航中断不算失败;子资源- // 失败不撤——主文档还活着,交给 5s 兜底判生死)。- const onFailLoad = (event: Electron.DidFailLoadEvent) => {- if (disposed || event.errorCode === -3 || !event.isMainFrame) return;- setSnapshot(null);- };webview.addEventListener('dom-ready', onDomReady);webview.addEventListener('console-message', onConsoleMessage);webview.addEventListener('render-process-gone', onGone);- webview.addEventListener('did-fail-load', onFailLoad);const unobserveTheme = observeHostTheme(scheduleInjectTheme);host.appendChild(webview);return () => {disposed = true;injector.dispose();if (themeTimer !== null) clearTimeout(themeTimer);- if (snapshotSwapTimer !== null) clearTimeout(snapshotSwapTimer);- if (captureTimer !== null) clearTimeout(captureTimer);- clearTimeout(snapshotFailsafeTimer);for (const timer of measureTimers) clearTimeout(timer);unobserveTheme();if (resizeDebounce !== null) clearTimeout(resizeDebounce);webview.removeEventListener('dom-ready', onDomReady);webview.removeEventListener('console-message', onConsoleMessage);webview.removeEventListener('render-process-gone', onGone);- webview.removeEventListener('did-fail-load', onFailLoad);webview.remove();};// version 入依赖:原位更新换版后 webview 重挂载,设置区立刻跑新代码。@@ -432,19 +300,7 @@ function SettingsWebviewBody({fixedHeight === undefined && 'overflow-hidden',)}style={{ height: fixedHeight ?? autoHeight }}- >- {/* 首帧快照(上层盖住透明装载期的 webview;pointer-events 穿透,撤图前- 的点击落到底下已就绪的真身上)。webview 由 effect 手动 appendChild- 进同一容器,React 只管理这张 img 的增删,互不干扰。 */}- {snapshot ? (- <img- src={snapshot.dataUrl}- alt=""- draggable={false}- className="pointer-events-none absolute inset-0 z-10 h-full w-full"- />- ) : null}- </div>+ />);}diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsxindex 808f9012ed..435f5e84ba 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx@@ -1,10 +1,10 @@/**- * Regression coverage for Plugin settings guest layout ownership.+ * Regression coverage for Plugin settings guest layout ownership and fresh-page lifecycle.* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md* @vitest-environment jsdom*/-import { render, waitFor } from '@testing-library/react';+import { act, cleanup, render, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const authState = vi.hoisted(() => ({@@ -14,6 +14,10 @@ const authState = vi.hoisted(() => ({import type { InstalledGhost } from '../../../shared/ghost';import { GhostSettingsWebview } from '../GhostSettingsWebview';+import {+ __resetGhostSettingsHeightCacheForTest,+ loadGhostSettingsHeight,+} from '../ghostSettingsHeight';vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),@@ -26,20 +30,29 @@ vi.mock('@/contexts/AuthContext', () => ({beforeEach(() => {authState.mode = 'cloud';authState.dataOwnerId = 'owner-a';+ localStorage.clear();+ __resetGhostSettingsHeightCacheForTest();});afterEach(() => {+ cleanup();+ vi.useRealTimers();vi.restoreAllMocks();});function renderSettings(settingsHeight?: number, measuredHeight?: number) {- const executeJavaScript = vi.fn().mockImplementation((script: unknown) =>- Promise.resolve(- measuredHeight !== undefined && String(script).includes('var bottom=r.bottom')- ? measuredHeight- : undefined,- ),- );+ const capturePage = vi.fn();+ const executeJavaScript = vi+ .fn()+ .mockImplementation((script: unknown) =>+ Promise.resolve(+ measuredHeight !== undefined && String(script).includes('var bottom=r.bottom')+ ? measuredHeight+ : String(script).includes('scrolled:')+ ? { scrolled: false, dirty: false }+ : undefined,+ ),+ );const originalCreateElement = document.createElement.bind(document);vi.spyOn(document, 'createElement').mockImplementation(((@@ -52,7 +65,7 @@ function renderSettings(settingsHeight?: number, measuredHeight?: number) {executeJavaScript,insertCSS: vi.fn().mockResolvedValue('theme-css'),removeInsertedCSS: vi.fn().mockResolvedValue(undefined),- capturePage: vi.fn(),+ capturePage,});}return element;@@ -78,7 +91,7 @@ function renderSettings(settingsHeight?: number, measuredHeight?: number) {const host = view.container.querySelector<HTMLElement>('[data-ghost-webview]');if (!host) throw new Error('Expected settings webview host');- return { executeJavaScript, ghost, host, view, webview };+ return { capturePage, executeJavaScript, ghost, host, view, webview };}describe('GhostSettingsWebview layout ownership', () => {@@ -133,4 +146,61 @@ describe('GhostSettingsWebview layout ownership', () => {expect(ownerBHost).not.toBeNull();expect(ownerBHost?.style.height).toBe('160px');});++ it('reopens a fresh guest with height-only spacing, without replaying or capturing old UI', async () => {+ vi.useFakeTimers();+ const legacyKey = 'ghostSettings.snapshot.v2.owner-a:example-settings-layout';+ localStorage.setItem(+ legacyKey,+ JSON.stringify({+ height: 432,+ version: '1.0.0',+ dataUrl: 'data:image/png;base64,stale-nickname-and-open-menu',+ }),+ );+ const { capturePage, ghost, host, view, webview } = renderSettings(undefined, 432);+ expect(host.style.height).toBe('432px');+ expect(host.querySelector('img')).toBeNull();+ expect(localStorage.getItem(legacyKey)).toBeNull();+ await act(() => vi.advanceTimersByTimeAsync(2000));+ expect(capturePage).not.toHaveBeenCalled();+ view.unmount();++ const reopened = render(<GhostSettingsWebview ghost={ghost} />);+ const freshGuest = reopened.container.querySelector('webview');+ expect(freshGuest).not.toBe(webview);+ expect(webview.isConnected).toBe(false);+ expect(+ reopened.container.querySelector<HTMLElement>('[data-ghost-webview]')?.style.height,+ ).toBe('432px');+ expect(reopened.container.querySelector('img')).toBeNull();+ freshGuest?.dispatchEvent(new Event('dom-ready'));+ await act(() => vi.advanceTimersByTimeAsync(2000));+ expect(capturePage).not.toHaveBeenCalled();+ });++ it('does not persist an asynchronous measurement after its guest is unmounted', async () => {+ const { executeJavaScript, ghost, view } = renderSettings();+ let finishMeasurement!: (height: number) => void;+ const pendingHeight = new Promise<number>((resolve) => {+ finishMeasurement = resolve;+ });+ executeJavaScript.mockImplementation((script: unknown) =>+ String(script).includes('var bottom=r.bottom') ? pendingHeight : Promise.resolve(undefined),+ );+ await waitFor(() =>+ expect(+ executeJavaScript.mock.calls.some(([script]) =>+ String(script).includes('var bottom=r.bottom'),+ ),+ ).toBe(true),+ );+ view.unmount();+ await act(async () => {+ finishMeasurement(432);+ });+ expect(+ loadGhostSettingsHeight('owner-a', ghost.manifest.id, ghost.manifest.version),+ ).toBeNull();+ });});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsHeight.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsHeight.test.tsnew file mode 100644index 0000000000..4700ed4052--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsHeight.test.ts@@ -0,0 +1,137 @@+// @vitest-environment jsdom+/** 设置页布局缓存:仅保留高度,迁移时移除历史画面,保持 owner/版本隔离。 */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ __resetGhostSettingsHeightCacheForTest,+ loadGhostSettingsHeight,+ pruneGhostSettingsHeights,+ saveGhostSettingsHeight,+} from '../ghostSettingsHeight';++const heightKey = 'ghostSettings.height.v1.owner-a:g1';+const legacyKey = 'ghostSettings.snapshot.v2.owner-a:g1';+const legacySnapshot = {+ height: 240,+ version: '1.0.0',+ dataUrl: 'data:image/png;base64,old-account-and-menu',+ width: 720,+ themeCss: ':root { --surface: #111; }',+};++beforeEach(() => {+ localStorage.clear();+ __resetGhostSettingsHeightCacheForTest();+});++afterEach(() => vi.restoreAllMocks());++describe('settings height cache', () => {+ it('persists only height and version and supports cold reads', () => {+ saveGhostSettingsHeight('owner-a', 'g1', '1.0.0', 240);+ expect(JSON.parse(localStorage.getItem(heightKey)!)).toEqual({ height: 240, version: '1.0.0' });+ __resetGhostSettingsHeightCacheForTest();+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(240);+ expect(loadGhostSettingsHeight('owner-a', 'g1', '2.0.0')).toBeNull();+ });++ it('isolates owners and plugins without claiming unowned legacy data', () => {+ localStorage.setItem('ghostSettings.snapshot.g1', JSON.stringify(legacySnapshot));+ saveGhostSettingsHeight('owner-a', 'g1', '1.0.0', 240);+ saveGhostSettingsHeight('owner-a', 'g2', '1.0.0', 320);+ saveGhostSettingsHeight('owner-b', 'g1', '1.0.0', 432);+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(240);+ expect(loadGhostSettingsHeight('owner-a', 'g2', '1.0.0')).toBe(320);+ expect(loadGhostSettingsHeight('owner-b', 'g1', '1.0.0')).toBe(432);+ expect(loadGhostSettingsHeight('owner-c', 'g1', '1.0.0')).toBeNull();+ expect(loadGhostSettingsHeight(null, 'g1', '1.0.0')).toBeNull();+ saveGhostSettingsHeight(null, 'g1', '1.0.0', 500);+ pruneGhostSettingsHeights(null, []);+ expect(localStorage.getItem('ghostSettings.snapshot.g1')).not.toBeNull();+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(240);+ });++ it('migrates only layout fields and removes the obsolete bitmap', () => {+ localStorage.setItem(legacyKey, JSON.stringify(legacySnapshot));+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(240);+ expect(localStorage.getItem(legacyKey)).toBeNull();+ expect(JSON.parse(localStorage.getItem(heightKey)!)).toEqual({ height: 240, version: '1.0.0' });+ });++ it('does not overwrite a newer height with legacy metadata', () => {+ localStorage.setItem(legacyKey, JSON.stringify(legacySnapshot));+ localStorage.setItem(heightKey, JSON.stringify({ height: 432, version: '2.0.0' }));+ expect(loadGhostSettingsHeight('owner-a', 'g1', '2.0.0')).toBe(432);+ expect(localStorage.getItem(legacyKey)).toBeNull();+ });++ it.each([+ '{oops',+ 'null',+ '{"height":"240","version":"1.0.0"}',+ '{"height":-1,"version":"1.0.0"}',+ ])('ignores invalid metadata and clears corrupt old snapshots: %s', (raw) => {+ localStorage.setItem(heightKey, raw);+ localStorage.setItem(legacyKey, raw);+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBeNull();+ expect(localStorage.getItem(legacyKey)).toBeNull();+ });++ it('clamps untrusted heights and ignores non-finite measurements', () => {+ saveGhostSettingsHeight('owner-a', 'g1', '1.0.0', 1);+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(48);+ saveGhostSettingsHeight('owner-a', 'g1', '1.0.0', 10000);+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(800);+ saveGhostSettingsHeight('owner-a', 'g1', '1.0.0', NaN);+ saveGhostSettingsHeight('owner-a', 'g1', '1.0.0', Infinity);+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(800);+ });++ it('deduplicates unchanged measurements and retains memory when persistence fails', () => {+ const write = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new Error('QuotaExceededError');+ });+ saveGhostSettingsHeight('owner-a', 'g1', '1.0.0', 432);+ saveGhostSettingsHeight('owner-a', 'g1', '1.0.0', 432);+ expect(write).toHaveBeenCalledTimes(1);+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(432);+ });++ it('removes old screenshots even when migrating height cannot be persisted', () => {+ localStorage.setItem(legacyKey, JSON.stringify(legacySnapshot));+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new Error('QuotaExceededError');+ });+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(240);+ expect(localStorage.getItem(legacyKey)).toBeNull();+ });++ it('prunes only current-owner orphans and migrates installed plugins, including disabled ones', () => {+ const otherOwnerKey = 'ghostSettings.snapshot.v2.owner-a-extra:g1';+ localStorage.setItem(otherOwnerKey, JSON.stringify(legacySnapshot));+ localStorage.setItem(legacyKey, JSON.stringify(legacySnapshot));+ localStorage.setItem('ghostSettings.snapshot.v2.owner-a:old', JSON.stringify(legacySnapshot));+ saveGhostSettingsHeight('owner-a', 'orphan', '1.0.0', 432);+ saveGhostSettingsHeight('owner-b', 'orphan', '1.0.0', 500);++ pruneGhostSettingsHeights('owner-a', ['g1']);++ expect(localStorage.getItem(legacyKey)).toBeNull();+ expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:old')).toBeNull();+ expect(localStorage.getItem('ghostSettings.height.v1.owner-a:orphan')).toBeNull();+ expect(loadGhostSettingsHeight('owner-a', 'g1', '1.0.0')).toBe(240);+ expect(loadGhostSettingsHeight('owner-a', 'orphan', '1.0.0')).toBeNull();+ expect(loadGhostSettingsHeight('owner-b', 'orphan', '1.0.0')).toBe(500);+ expect(localStorage.getItem(otherOwnerKey)).not.toBeNull();+ });++ it('uses the same encoded owner boundary for loading and pruning', () => {+ saveGhostSettingsHeight('owner:a/b', 'g1', '1.0.0', 432);+ __resetGhostSettingsHeightCacheForTest();+ expect(loadGhostSettingsHeight('owner:a/b', 'g1', '1.0.0')).toBe(432);+ pruneGhostSettingsHeights('owner:a', []);+ expect(loadGhostSettingsHeight('owner:a/b', 'g1', '1.0.0')).toBe(432);+ pruneGhostSettingsHeights('owner:a/b', []);+ expect(loadGhostSettingsHeight('owner:a/b', 'g1', '1.0.0')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsSnapshot.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsSnapshot.test.tsdeleted file mode 100644index a492f286d5..0000000000--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsSnapshot.test.ts+++ /dev/null@@ -1,208 +0,0 @@-// @vitest-environment jsdom-/**- * ghostSettingsSnapshot 单测:存取往返、损坏数据容错、体积上限与总量预算、- * TTL 过期、孤儿清理、匹配判定(版本 / 主题 / DPR / 宽度容差)。- */-import { beforeEach, describe, expect, it, vi } from 'vitest';--import {- __resetGhostSettingsSnapshotCacheForTest,- GHOST_SETTINGS_LAYOUT_REVISION,- loadGhostSettingsSnapshot,- pruneGhostSettingsSnapshots,- saveGhostSettingsSnapshot,- snapshotMatchesContext,- snapshotMatchesWidth,- SNAPSHOT_WIDTH_TOLERANCE,- type GhostSettingsSnapshot,-} from '../ghostSettingsSnapshot';--function makeSnapshot(overrides: Partial<GhostSettingsSnapshot> = {}): GhostSettingsSnapshot {- return {- dataUrl: 'data:image/png;base64,abc',- width: 1200,- height: 240,- dpr: 2,- themeCss: ':root { --surface: #111; }',- version: '1.1.1',- layoutRevision: GHOST_SETTINGS_LAYOUT_REVISION,- capturedAt: Date.now(),- ...overrides,- };-}--beforeEach(() => {- localStorage.clear();- __resetGhostSettingsSnapshotCacheForTest();-});--describe('存取往返', () => {- it('save 后 load 返回同一内容,且写进了 localStorage', () => {- const snap = makeSnapshot();- saveGhostSettingsSnapshot('owner-a', 'g1', snap);- __resetGhostSettingsSnapshotCacheForTest();- expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toEqual(snap);- expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g1')).toBeTruthy();- });-- it('不同意识 id 互不串台', () => {- saveGhostSettingsSnapshot('owner-a', 'g1', makeSnapshot({ version: '1.0.0' }));- saveGhostSettingsSnapshot('owner-a', 'g2', makeSnapshot({ version: '2.0.0' }));- expect(loadGhostSettingsSnapshot('owner-a', 'g1')?.version).toBe('1.0.0');- expect(loadGhostSettingsSnapshot('owner-a', 'g2')?.version).toBe('2.0.0');- });-- it('不同 owner 的同 ghostId 互不读取,旧的无 owner 快照不自动认领', () => {- const ownerASnapshot = makeSnapshot({ version: 'owner-a-version' });- saveGhostSettingsSnapshot('owner-a', 'shared-ghost', ownerASnapshot);- localStorage.setItem(- 'ghostSettings.snapshot.shared-ghost',- JSON.stringify(makeSnapshot({ version: 'legacy-unowned' })),- );-- expect(loadGhostSettingsSnapshot('owner-a', 'shared-ghost')).toEqual(ownerASnapshot);- expect(loadGhostSettingsSnapshot('owner-b', 'shared-ghost')).toBeNull();-- const ownerBSnapshot = makeSnapshot({ version: 'owner-b-version' });- saveGhostSettingsSnapshot('owner-b', 'shared-ghost', ownerBSnapshot);- expect(loadGhostSettingsSnapshot('owner-b', 'shared-ghost')).toEqual(ownerBSnapshot);- expect(loadGhostSettingsSnapshot('owner-a', 'shared-ghost')).toEqual(ownerASnapshot);- });-- it('没有存量时返回 null', () => {- expect(loadGhostSettingsSnapshot('owner-a', 'nope')).toBeNull();- });-});--describe('容错', () => {- it('localStorage 里是坏 JSON 时按没有处理', () => {- localStorage.setItem('ghostSettings.snapshot.v2.owner-a:g1', '{oops');- expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();- });-- it('形不对(缺字段 / 类型错 / 非图片 dataUrl)按没有处理', () => {- localStorage.setItem(- 'ghostSettings.snapshot.v2.owner-a:g1',- JSON.stringify({- dataUrl: 'javascript:alert(1)',- width: 1,- height: 1,- dpr: 1,- themeCss: '',- version: '1',- capturedAt: Date.now(),- }),- );- expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();- __resetGhostSettingsSnapshotCacheForTest();- localStorage.setItem(- 'ghostSettings.snapshot.v2.owner-a:g1',- JSON.stringify({ ...makeSnapshot(), width: 'wide' }),- );- expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();- __resetGhostSettingsSnapshotCacheForTest();- // 老格式(缺 capturedAt)同样作废。- const legacy: Partial<GhostSettingsSnapshot> = { ...makeSnapshot() };- delete legacy.capturedAt;- localStorage.setItem('ghostSettings.snapshot.v2.owner-a:g1', JSON.stringify(legacy));- expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();-- __resetGhostSettingsSnapshotCacheForTest();- const preLayoutRevision: Partial<GhostSettingsSnapshot> = { ...makeSnapshot() };- delete preLayoutRevision.layoutRevision;- localStorage.setItem('ghostSettings.snapshot.v2.owner-a:g1', JSON.stringify(preLayoutRevision));- expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();- });-- it('localStorage 写失败(配额满)时静默降级为仅内存缓存', () => {- const spy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {- throw new Error('QuotaExceededError');- });- try {- const snap = makeSnapshot();- expect(() => saveGhostSettingsSnapshot('owner-a', 'g1', snap)).not.toThrow();- // 本会话内存缓存仍可读。- expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toEqual(snap);- } finally {- spy.mockRestore();- }- });-});--describe('存储预算', () => {- it('单条超大位图只存内存不落 localStorage,并清掉同 id 旧持久快照', () => {- saveGhostSettingsSnapshot('owner-a', 'g1', makeSnapshot());- expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g1')).toBeTruthy();- const snap = makeSnapshot({ dataUrl: `data:image/png;base64,${'a'.repeat(500_000)}` });- saveGhostSettingsSnapshot('owner-a', 'g1', snap);- expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g1')).toBeNull();- expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toEqual(snap);- });-- it('总量超预算时按拍摄时间淘汰最旧的其它快照', () => {- const big = (tag: string) => `data:image/png;base64,${tag.repeat(390_000)}`;- // 5 条 ~390k 快照(总预算 2M):写第 6 条时应从最旧开始腾位。- for (let i = 0; i < 5; i++) {- saveGhostSettingsSnapshot('owner-a', `g${i}`, makeSnapshot({ dataUrl: big('a'), capturedAt: 1000 + i }));- }- saveGhostSettingsSnapshot('owner-a', 'gNew', makeSnapshot({ dataUrl: big('b'), capturedAt: 9999 }));- // 最新的必须在;最旧的 g0(至少)被淘汰;总量回到预算内。- expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:gNew')).toBeTruthy();- expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g0')).toBeNull();- let total = 0;- for (let i = 0; i < localStorage.length; i++) {- const key = localStorage.key(i)!;- if (key.startsWith('ghostSettings.snapshot.v2.owner-a:')) total += localStorage.getItem(key)!.length;- }- expect(total).toBeLessThanOrEqual(2_000_000);- });-- it('TTL 过期的快照按没有处理并顺手清盘', () => {- const stale = makeSnapshot({ capturedAt: Date.now() - 15 * 24 * 60 * 60 * 1000 });- localStorage.setItem('ghostSettings.snapshot.v2.owner-a:g1', JSON.stringify(stale));- expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();- expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g1')).toBeNull();- });-- it('prune 按已装清单清孤儿(含内存缓存),在装的不动', () => {- saveGhostSettingsSnapshot('owner-a', 'keep', makeSnapshot());- saveGhostSettingsSnapshot('owner-a', 'orphan', makeSnapshot());- pruneGhostSettingsSnapshots('owner-a', ['keep', 'not-yet-snapshotted']);- expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:keep')).toBeTruthy();- expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:orphan')).toBeNull();- expect(loadGhostSettingsSnapshot('owner-a', 'orphan')).toBeNull();- expect(loadGhostSettingsSnapshot('owner-a', 'keep')).toBeTruthy();- });-- it('prune 只清当前 owner,不触碰其他 owner 的同名快照', () => {- saveGhostSettingsSnapshot('owner-a', 'orphan', makeSnapshot({ version: 'a' }));- saveGhostSettingsSnapshot('owner-b', 'orphan', makeSnapshot({ version: 'b' }));-- pruneGhostSettingsSnapshots('owner-a', []);-- expect(loadGhostSettingsSnapshot('owner-a', 'orphan')).toBeNull();- expect(loadGhostSettingsSnapshot('owner-b', 'orphan')?.version).toBe('b');- });-});--describe('匹配判定', () => {- const ctx = { version: '1.1.1', themeCss: ':root { --surface: #111; }', dpr: 2 };-- it('插件版本 / 宿主布局版本 / 主题 / DPR 全等才命中', () => {- expect(snapshotMatchesContext(makeSnapshot(), ctx)).toBe(true);- expect(snapshotMatchesContext(makeSnapshot({ version: '1.1.2' }), ctx)).toBe(false);- expect(snapshotMatchesContext(makeSnapshot({ layoutRevision: 2 }), ctx)).toBe(false);- expect(- snapshotMatchesContext(makeSnapshot({ themeCss: ':root { --surface: #eee; }' }), ctx),- ).toBe(false);- expect(snapshotMatchesContext(makeSnapshot({ dpr: 1 }), ctx)).toBe(false);- });-- it('宽度在容差内命中,超出作废', () => {- const snap = makeSnapshot({ width: 1200 });- expect(snapshotMatchesWidth(snap, 1200)).toBe(true);- expect(snapshotMatchesWidth(snap, 1200 + SNAPSHOT_WIDTH_TOLERANCE)).toBe(true);- expect(snapshotMatchesWidth(snap, 1200 - SNAPSHOT_WIDTH_TOLERANCE)).toBe(true);- expect(snapshotMatchesWidth(snap, 1200 + SNAPSHOT_WIDTH_TOLERANCE + 1)).toBe(false);- });-});diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsxindex dac4709f74..9bf3c853b5 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx@@ -17,7 +17,7 @@ import {import { extractIpcError } from '../utils/ipcError';import { GhostChipPanelBody, GhostPanelError } from './ghostPanelBody';import { ghostInstallErrorKey } from './installErrorKey';-import { pruneGhostSettingsSnapshots } from './ghostSettingsSnapshot';+import { pruneGhostSettingsHeights } from './ghostSettingsHeight';import { useGhostRuntimeState } from './runtimeStates';import { getDataOwnerGeneration } from '../contexts/dataOwnerGeneration';@@ -171,14 +171,14 @@ const registeredFingerprints = new Map<string, string>();* 独占承载(features/plugin/GhostPagePanelHost),离开插件页即卸载。*/export function syncGhostPanelRegistrations(ghosts: InstalledGhost[]): void {- // 顺手清设置区快照缓存的孤儿(卸载的意识不该在 localStorage 留位图);+ // 清理已卸载插件的高度缓存,并将当前 owner 的旧截图缓存收敛为纯高度;// 本函数是"已装清单"的唯一同步点(启动 + ghosts:changed),挂这里最省。- // 注意用全量清单(含沉睡)——沉睡只是不注册面板,快照仍然有效。- pruneGhostSettingsSnapshots(+ // 注意用全量清单(含沉睡)——沉睡只是不注册面板,高度仍可复用。+ pruneGhostSettingsHeights(getDataOwnerGeneration().dataOwnerId,ghosts.map((g) => g.manifest.id),);- // 气泡状态对齐(与快照 prune 不同:停用/失格的要强制还原,不只清卸载)——+ // 气泡状态对齐(与高度 prune 不同:停用/失格的要强制还原,不只清卸载)——// 气泡是"面板不可见 + 唯一恢复入口",失格后必须回停靠,不留死角。reconcileGhostPanelBubbles(ghosts);const seen = new Set<string>();diff --git a/apps/desktop/src/renderer/cindy-brain/ghostSettingsHeight.ts b/apps/desktop/src/renderer/cindy-brain/ghostSettingsHeight.tsnew file mode 100644index 0000000000..a5b863df09--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/ghostSettingsHeight.ts@@ -0,0 +1,145 @@+/**+ * 插件设置页只缓存布局高度,不保存页面图片、账号文字或临时交互状态。+ * 缓存按 data owner / 插件隔离,仅供同版本重开时留位,真实尺寸仍由 guest 量得。+ */+interface HeightRecord {+ height: number;+ version: string;+}++export const GHOST_SETTINGS_HEIGHT_MIN = 48;+export const GHOST_SETTINGS_HEIGHT_MAX = 800;++const STORAGE_PREFIX = 'ghostSettings.height.v1.';+const LEGACY_PREFIX = 'ghostSettings.snapshot.v2.';+const memoryCache = new Map<string, HeightRecord>();++function scopedKey(dataOwnerId: string, ghostId: string): string {+ return `${encodeURIComponent(dataOwnerId)}:${ghostId}`;+}++/** 只提取布局字段;旧记录里的 dataUrl 等页面内容不得进入新缓存。 */+function parseHeight(raw: string | null): HeightRecord | null {+ if (!raw) return null;+ try {+ const value: unknown = JSON.parse(raw);+ if (typeof value !== 'object' || value === null) return null;+ const { height, version } = value as Record<string, unknown>;+ if (+ typeof height !== 'number' ||+ !Number.isFinite(height) ||+ height <= 0 ||+ typeof version !== 'string'+ )+ return null;+ return {+ height: Math.max(+ GHOST_SETTINGS_HEIGHT_MIN,+ Math.min(GHOST_SETTINGS_HEIGHT_MAX, Math.ceil(height)),+ ),+ version,+ };+ } catch {+ return null;+ }+}++function removePersisted(key: string): void {+ try {+ localStorage.removeItem(key);+ } catch {+ // 布局缓存不可用不影响插件功能。+ }+}++function readHeight(key: string): HeightRecord | null {+ const cached = memoryCache.get(key);+ if (cached) return cached;+ let record: HeightRecord | null = null;+ try {+ record = parseHeight(localStorage.getItem(STORAGE_PREFIX + key));+ if (!record) {+ // 仅从已明确归属当前 owner 的旧快照保留高度,不认领无 owner 的 v1 快照。+ record = parseHeight(localStorage.getItem(LEGACY_PREFIX + key));+ if (record) localStorage.setItem(STORAGE_PREFIX + key, JSON.stringify(record));+ }+ } catch {+ // 持久化不可用时仍可复用已读取的高度。+ } finally {+ // 不论旧数据是否有效,都不再保留此 owner 的历史页面图片。+ removePersisted(LEGACY_PREFIX + key);+ }+ if (record) memoryCache.set(key, record);+ return record;+}++export function loadGhostSettingsHeight(+ dataOwnerId: string | null,+ ghostId: string,+ version: string,+): number | null {+ if (!dataOwnerId) return null;+ const record = readHeight(scopedKey(dataOwnerId, ghostId));+ return record?.version === version ? record.height : null;+}++export function saveGhostSettingsHeight(+ dataOwnerId: string | null,+ ghostId: string,+ version: string,+ height: number,+): void {+ if (!dataOwnerId || !Number.isFinite(height) || height <= 0) return;+ const key = scopedKey(dataOwnerId, ghostId);+ const record = {+ height: Math.max(+ GHOST_SETTINGS_HEIGHT_MIN,+ Math.min(GHOST_SETTINGS_HEIGHT_MAX, Math.ceil(height)),+ ),+ version,+ };+ const previous = memoryCache.get(key);+ if (previous?.height === record.height && previous.version === version) return;+ memoryCache.set(key, record);+ removePersisted(LEGACY_PREFIX + key);+ try {+ localStorage.setItem(STORAGE_PREFIX + key, JSON.stringify(record));+ } catch {+ // 配额满或存储禁用时只保留会话内高度。+ }+}++/** 启动/插件清单变化时迁移当前 owner 的旧缓存并清理已卸载插件的布局记录。 */+export function pruneGhostSettingsHeights(+ dataOwnerId: string | null,+ installedGhostIds: Iterable<string>,+): void {+ if (!dataOwnerId) return;+ const ownerPrefix = `${encodeURIComponent(dataOwnerId)}:`;+ const keep = new Set(installedGhostIds);+ const keys = new Set([...memoryCache.keys()].filter((key) => key.startsWith(ownerPrefix)));+ try {+ for (let i = 0; i < localStorage.length; i++) {+ const key = localStorage.key(i);+ for (const prefix of [STORAGE_PREFIX, LEGACY_PREFIX]) {+ if (key?.startsWith(prefix + ownerPrefix)) keys.add(key.slice(prefix.length));+ }+ }+ } catch {+ // 仍清理当前 owner 的会话内孤儿缓存。+ }+ for (const key of keys) {+ if (keep.has(key.slice(ownerPrefix.length))) {+ readHeight(key);+ } else {+ memoryCache.delete(key);+ removePersisted(STORAGE_PREFIX + key);+ }+ removePersisted(LEGACY_PREFIX + key);+ }+}++/** 仅测试用:模拟 renderer 重启后的冷读取。 */+export function __resetGhostSettingsHeightCacheForTest(): void {+ memoryCache.clear();+}diff --git a/apps/desktop/src/renderer/cindy-brain/ghostSettingsSnapshot.ts b/apps/desktop/src/renderer/cindy-brain/ghostSettingsSnapshot.tsdeleted file mode 100644index 915edf1a91..0000000000--- a/apps/desktop/src/renderer/cindy-brain/ghostSettingsSnapshot.ts+++ /dev/null@@ -1,267 +0,0 @@-/**- * 意识「自定义设置区」的快照缓存(视觉连续性,设计规范规则 7):- * webview 是独立渲染进程,从创建到画出首帧天然要几百毫秒,追不平宿主——- * 于是在设置区渲染稳定后把 guest 的最终画面截成位图存下来(内存 + localStorage,- * 跨 app 重启可用);下次进入详情页首帧直接贴这张图(像素与真内容一致),- * webview 在图底下装载,就绪后无缝撤图换真身。用户看不到空白帧与高度跳变。- *- * 快照只是"上一次的画面",不承载任何真实状态:失配(插件版本 / 宿主布局版本 /- * 主题 / 宽度 / DPR 任一变化)或过期(TTL)就整张作废走老的淡入路径。- * 位图来自宿主对 guest 的 capturePage(嵌入方主动读,零桥模型不破),- * 内容不受信也无所谓——它只被当成 <img> 的像素,不进任何执行上下文。- *- * 存储纪律:localStorage 是整个 renderer 30+ 个功能共享的 ~10MB 配额,- * 本模块自设总预算(单条超限只留内存、总量超限按拍摄时间淘汰最旧),- * 并提供按已装清单清孤儿的 prune(意识卸载后快照没有存在的理由)。- */--/** 一张已存的设置区快照:位图 + 拍摄时的匹配上下文。 */-export interface GhostSettingsSnapshot {- /** capturePage 产物的 data URL(image/png)。 */- dataUrl: string;- /** 拍摄时设置区容器的 CSS 宽度(px);宽度变了内容会重排,快照作废。 */- width: number;- /** 拍摄时设置区容器的 CSS 高度(px);兼作冷启动的高度留位初值。 */- height: number;- /** 拍摄时的 devicePixelRatio(跨屏拖动后位图清晰度对不上,作废重拍)。 */- dpr: number;- /** 拍摄时注入 guest 的主题 CSS 全文(主题换肤后旧配色快照作废)。 */- themeCss: string;- /** 拍摄时的意识版本(原位更新后界面可能全变,作废)。 */- version: string;- /** 拍摄时的宿主设置布局版本(注入规则变化后旧位图作废)。 */- layoutRevision: number;- /** 拍摄时刻(epoch ms):TTL 过期判定 + 总量超预算时的 LRU 淘汰序。 */- capturedAt: number;-}--/** 快照匹配上下文(进入详情页时的现场值,与存量快照逐项比对)。 */-export interface GhostSettingsSnapshotContext {- version: string;- themeCss: string;- dpr: number;-}--// v1 只有 ghostId,无法证明快照属于哪个 owner;保留但永不读取/迁移。-const STORAGE_PREFIX = 'ghostSettings.snapshot.v2.';--/** 宿主设置 guest 的布局契约版本;布局注入改变时递增以主动淘汰旧快照。 */-export const GHOST_SETTINGS_LAYOUT_REVISION = 3;--/**- * 单条持久化体积上限(字符数,localStorage 按 UTF-16 计):设置区是纯色底 +- * 文字控件,PNG data URL 正常远小于此;超限说明画面异常复杂,只留内存缓存。- */-const MAX_PERSIST_CHARS = 400_000;--/** 全部快照的持久化总预算(字符数):写入前超预算就按 capturedAt 淘汰最旧。 */-const TOTAL_PERSIST_BUDGET_CHARS = 2_000_000;--/** 快照有效期:太久没进过的设置页,画面参考价值低,过期作废顺手清盘。 */-const SNAPSHOT_TTL_MS = 14 * 24 * 60 * 60 * 1000;--/** 宽度容差(px):亚像素/滚动条级别的差异不重排内容,视同命中。 */-export const SNAPSHOT_WIDTH_TOLERANCE = 2;--/** 内存读写穿透缓存(null = 已确认 localStorage 里没有,避免反复 parse)。 */-const memoryCache = new Map<string, GhostSettingsSnapshot | null>();--/** 结构校验:localStorage 内容可能被外部改坏,逐字段验形,不合格当没有。 */-function isValidSnapshot(value: unknown): value is GhostSettingsSnapshot {- if (typeof value !== 'object' || value === null) return false;- const v = value as Record<string, unknown>;- return (- typeof v.dataUrl === 'string' &&- v.dataUrl.startsWith('data:image/') &&- typeof v.width === 'number' &&- Number.isFinite(v.width) &&- typeof v.height === 'number' &&- Number.isFinite(v.height) &&- typeof v.dpr === 'number' &&- Number.isFinite(v.dpr) &&- typeof v.themeCss === 'string' &&- typeof v.version === 'string' &&- v.layoutRevision === GHOST_SETTINGS_LAYOUT_REVISION &&- typeof v.capturedAt === 'number' &&- Number.isFinite(v.capturedAt)- );-}--function snapshotKey(dataOwnerId: string, ghostId: string): string {- return `${encodeURIComponent(dataOwnerId)}:${ghostId}`;-}--function parseSnapshotKey(key: string): { dataOwnerId: string; ghostId: string } | null {- const separator = key.lastIndexOf(':');- if (separator <= 0 || separator === key.length - 1) return null;- try {- const dataOwnerId = decodeURIComponent(key.slice(0, separator));- const ghostId = key.slice(separator + 1);- if (!dataOwnerId || !ghostId) return null;- return { dataOwnerId, ghostId };- } catch {- return null;- }-}--/** 静默删一条持久化快照(localStorage 不可用时忽略)。 */-function removePersisted(dataOwnerId: string, ghostId: string): void {- const key = snapshotKey(dataOwnerId, ghostId);- try {- localStorage.removeItem(STORAGE_PREFIX + key);- } catch {- // ignore- }-}--/** 读取某意识的存量快照(内存 → localStorage;损坏/缺失/过期返回 null)。 */-export function loadGhostSettingsSnapshot(- dataOwnerId: string | null,- ghostId: string,-): GhostSettingsSnapshot | null {- if (!dataOwnerId) return null;- const key = snapshotKey(dataOwnerId, ghostId);- const cached = memoryCache.get(key);- if (cached !== undefined) return cached;- let snapshot: GhostSettingsSnapshot | null = null;- try {- const raw = localStorage.getItem(STORAGE_PREFIX + key);- if (raw) {- const parsed: unknown = JSON.parse(raw);- if (isValidSnapshot(parsed)) {- if (Date.now() - parsed.capturedAt > SNAPSHOT_TTL_MS) {- removePersisted(dataOwnerId, ghostId);- } else {- snapshot = parsed;- }- }- }- } catch {- // localStorage 不可用或 JSON 损坏:视同没有快照,走老的淡入路径。- }- memoryCache.set(key, snapshot);- return snapshot;-}--/** 遍历所有新版持久快照键;旧的无 owner 快照不会进入回调。 */-function forEachPersisted(- fn: (identity: { key: string; dataOwnerId: string; ghostId: string }, raw: string) => void,-): void {- try {- const keys: string[] = [];- for (let i = 0; i < localStorage.length; i++) {- const key = localStorage.key(i);- if (key && key.startsWith(STORAGE_PREFIX)) keys.push(key);- }- for (const key of keys) {- const raw = localStorage.getItem(key);- const scopedKey = key.slice(STORAGE_PREFIX.length);- const identity = parseSnapshotKey(scopedKey);- if (raw !== null && identity) fn({ key: scopedKey, ...identity }, raw);- }- } catch {- // localStorage 不可用:静默(持久化本就是 best-effort)。- }-}--/**- * 存快照(内存必存;持久化 best-effort):单条超限只留内存;写入前按- * capturedAt 淘汰最旧的其它快照直到总量回到预算内;写失败静默降级仅内存。- */-export function saveGhostSettingsSnapshot(- dataOwnerId: string | null,- ghostId: string,- snapshot: GhostSettingsSnapshot,-): void {- if (!dataOwnerId) return;- const key = snapshotKey(dataOwnerId, ghostId);- memoryCache.set(key, snapshot);- if (snapshot.dataUrl.length > MAX_PERSIST_CHARS) {- // 单条超限只留内存;同 id 更早的持久快照顺手清掉——它已确认过时,- // 重启后贴一张旧画面不如诚实走淡入。- removePersisted(dataOwnerId, ghostId);- return;- }- const serialized = JSON.stringify(snapshot);- // 总量预算:收集其它快照的体积与拍摄时间,超预算从最旧开始腾位。- const others: Array<{ id: string; size: number; capturedAt: number }> = [];- forEachPersisted((identity, raw) => {- if (identity.key === key) return;- let capturedAt = 0;- try {- const parsed: unknown = JSON.parse(raw);- if (isValidSnapshot(parsed)) capturedAt = parsed.capturedAt;- } catch {- // 坏数据当最旧(capturedAt 0),优先被淘汰。- }- others.push({ id: identity.key, size: raw.length, capturedAt });- });- let total = serialized.length + others.reduce((sum, o) => sum + o.size, 0);- if (total > TOTAL_PERSIST_BUDGET_CHARS) {- others.sort((a, b) => a.capturedAt - b.capturedAt);- for (const victim of others) {- if (total <= TOTAL_PERSIST_BUDGET_CHARS) break;- const identity = parseSnapshotKey(victim.id);- if (identity) removePersisted(identity.dataOwnerId, identity.ghostId);- memoryCache.delete(victim.id);- total -= victim.size;- }- }- try {- localStorage.setItem(STORAGE_PREFIX + key, serialized);- } catch {- // 配额满等写失败:内存缓存仍生效(本会话内复用),不影响功能。- }-}--/**- * 按"当前已装意识清单"清理孤儿快照(卸载后的快照没有存在理由)。- * 由意识清单同步点(启动 + ghosts:changed)顺手调用,幂等。- */-export function pruneGhostSettingsSnapshots(- dataOwnerId: string | null,- installedGhostIds: Iterable<string>,-): void {- if (!dataOwnerId) return;- const keep = new Set(installedGhostIds);- const orphanIds: string[] = [];- forEachPersisted((identity) => {- if (identity.dataOwnerId === dataOwnerId && !keep.has(identity.ghostId)) {- orphanIds.push(identity.ghostId);- }- });- for (const id of orphanIds) {- removePersisted(dataOwnerId, id);- const key = snapshotKey(dataOwnerId, id);- memoryCache.delete(key);- }- for (const key of [...memoryCache.keys()]) {- const identity = parseSnapshotKey(key);- if (identity?.dataOwnerId === dataOwnerId && !keep.has(identity.ghostId)) {- memoryCache.delete(key);- }- }-}--/** 上下文匹配:插件版本 / 宿主布局版本 / 主题 CSS / DPR 全等才允许贴图。 */-export function snapshotMatchesContext(- snapshot: GhostSettingsSnapshot,- ctx: GhostSettingsSnapshotContext,-): boolean {- return (- snapshot.version === ctx.version &&- snapshot.layoutRevision === GHOST_SETTINGS_LAYOUT_REVISION &&- snapshot.themeCss === ctx.themeCss &&- snapshot.dpr === ctx.dpr- );-}--/** 宽度匹配(容器实际宽度要等首帧布局后才知道,单独一步校验)。 */-export function snapshotMatchesWidth(snapshot: GhostSettingsSnapshot, hostWidth: number): boolean {- return Math.abs(snapshot.width - hostWidth) <= SNAPSHOT_WIDTH_TOLERANCE;-}--/** 仅测试用:清空内存缓存,让用例重新走 localStorage 读取路径。 */-export function __resetGhostSettingsSnapshotCacheForTest(): void {- memoryCache.clear();-}diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 1faba1453e..83b97b6d0f 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -4933,6 +4933,13 @@ describe('ghostPermissionProjectionFingerprint', () => {expect(ghostNodeSecretAuthorizationWithinCap(reviewed.manifest, changedHint.manifest)).toBe(false,);+ const oauthRebind = structuredClone(reviewed.manifest);+ oauthRebind.node!.secretBindings![0]!.oauthSecret = 'mail_account';+ expect(ghostNodeSecretAuthorizationWithinCap(reviewed.manifest, oauthRebind)).toBe(false);+ const differentAccountSource = structuredClone(oauthRebind);+ differentAccountSource.node!.secretBindings![0]!.oauthSecret = 'other_account';+ expect(ghostNodeSecretAuthorizationWithinCap(oauthRebind, differentAccountSource)).toBe(false);+ expect(ghostNodeSecretAuthorizationWithinCap(oauthRebind, structuredClone(oauthRebind))).toBe(true);});it('语义相同时指纹稳定(与字段/条目顺序无关)', () => {diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 30515dbb4c..6659d2f4cf 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -255,6 +255,8 @@ export function isGhostNodeMcpReservedMethod(method: string): boolean {* Worker 获得明文后仍可能主动回传或泄露。未声明 entry 时只允许主入口。*/export interface GhostNodeSecretBinding {+ /** 引用本插件 network.secrets 中的 OAuth key;仅注入短期 access token。 */+ oauthSecret?: string;/** 凭证键(插件内唯一):小写字母开头,允许小写/数字/下划线,1–32。 */key: string;/** 给用户看的名称(插件详情与设置状态使用)。 */@@ -1975,12 +1977,12 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItconst targetEntry = binding.entry ?? manifest.node.entry;const stableMethods = [...binding.methods].sort();items.unshift({- key: `node:secret:${binding.key}:${targetEntry}:${stableMethods.join(',')}`,+ key: `node:secret:${binding.key}:${targetEntry}:${stableMethods.join(',')}${binding.oauthSecret ? `:oauth:${binding.oauthSecret}` : ''}`,kind: 'node',labelKey: 'nodeSecret',labelArgs: { name: binding.label },detailKey: 'nodeSecretDetail',- detail: binding.methods.join('\n'),+ detail: [binding.oauthSecret ? `OAuth: ${binding.oauthSecret}` : '', ...binding.methods].filter(Boolean).join('\n'),});}if (manifest.node.lifecycle === 'resident') {@@ -2586,6 +2588,7 @@ export function ghostNodeSecretAuthorizationWithinCap();if (!cap ||+ binding.oauthSecret !== cap.oauthSecret ||binding.label !== cap.label ||!binding.methods.every((method) => cap.methods.includes(method))) {@@ -4452,7 +4455,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {}const binding = bindingRaw as Record<string, unknown>;const unknownBindingField = Object.keys(binding).find(- (key) => !['key', 'label', 'methods', 'entry', 'hint', 'url'].includes(key),+ (key) => !['key', 'label', 'methods', 'entry', 'hint', 'url', 'oauthSecret'].includes(key),);if (unknownBindingField) {return {@@ -4569,7 +4572,12 @@ export function validateGhostManifest(value: unknown): ManifestValidation {};}}+ if (binding.oauthSecret !== undefined &&+ (typeof binding.oauthSecret !== 'string' || !/^[a-z][a-z0-9_]{0,31}$/.test(binding.oauthSecret))) {+ return { ok: false, reason: 'node.secretBindings[].oauthSecret 必须是本插件 OAuth 凭证键' };+ }nodeSecretBindings.push({+ ...(binding.oauthSecret !== undefined ? { oauthSecret: binding.oauthSecret as string } : {}),key: binding.key,label: binding.label,methods,@@ -5794,6 +5802,13 @@ export function validateGhostManifest(value: unknown): ManifestValidation {// setup 就绪声明:引用必须指向已声明的凭证/连接(悬空引用在装包期拒,// 不留到运行期才发现作者写错);kv 引用要求 settingsHtml(没有设置页// 没人填参数);Host 派生源没有用户配置动作,引用它属结构性误解,直接拒装。+ for (const binding of node?.secretBindings ?? []) {+ if (binding.oauthSecret === undefined) continue;+ const source = network?.secrets?.find((secret) => secret.key === binding.oauthSecret);+ if (source?.source !== 'oauth' || !source.oauth) {+ return { ok: false, reason: 'node.secretBindings[].oauthSecret 必须引用本插件已声明的 OAuth 凭证' };+ }+ }let setup: GhostSetupDecl | undefined;if (raw.setup !== undefined) {if (!isPlainObject(raw.setup)) {@@ -5827,7 +5842,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {},] as const,),- ...(node?.secretBindings ?? []).map((s) => [s.key, { hostDerivedSource: null }] as const),+ ...(node?.secretBindings ?? []).filter((s) => !s.oauthSecret).map((s) => [s.key, { hostDerivedSource: null }] as const),]);const connectionKeys = new Set((network?.connections ?? []).map((c) => c.key));const groups: GhostSetupGroup[] = [];@@ -6419,6 +6434,8 @@ export const GHOST_NODE_REQUEST_MAX_TOTAL_MS = 15 * 60_000;/** 上行:main.js 通过主机中继调用随包 Node 工作进程。 */export interface GhostPipeNodeRequest {type: 'node-request';+ /** OAuth 注入的本插件账号 id;缺省使用对应 OAuth 槽的默认账号。 */+ authAccount?: string;/** JSON-RPC 方法名;mcp-stdio 时使用 tools/list、tools/call 等 MCP 方法。 */method: string;params?: unknown;diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.mdindex faf2b986cd..1e556e9c99 100644--- a/docs/dev-rules/credentials-and-local-storage.md+++ b/docs/dev-rules/credentials-and-local-storage.md@@ -20,6 +20,13 @@- 运行时需要持久化秘密时,复用现有 Main/宿主管理的 credential store 或 Electron`safeStorage` 边界。不要新增自定义明文凭证文件,也不要把秘密下放给 Renderer、插件或不受信任页面。+- 可信 Node Worker 的显式例外:`node.secretBindings[].oauthSecret` 只能引用本插件+ 已声明的 OAuth key。Host 根据本次 `authAccount`(省略时为默认账号)刷新并注入+ 短期 access token;不得注入 refresh token、返回 Renderer/Agent、写日志或落盘。+ Worker 启动第三方 CLI 时仅用该次子进程环境传递,不修改全局环境或复用他账号配置。+ 这是高权限 Node 的受审查信任边界,不是系统沙箱或对恶意 Worker 的隔离保证。+ 实现与回归见 [nodeRuntimeBroker.ts](../../apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts)+ 和 [nodeRuntimeBroker.test.ts](../../apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts)。- access token 等只需短期使用的秘密优先保留在内存中。日志、错误、遥测和调试输出不得包含凭证明文、完整鉴权头或可直接复用的授权材料。- 测试只使用明显无效的假凭证,不读取或复制开发者真实的 `HOME`、Agent home、diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 260c748b4c..57f6ab6d52 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -32,10 +32,12 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi与 Claude Code/Codex 一致,Pi 会话的 Full Access 也会让插件 `ghost_call` 的`attachments`/`dir`/`save_dir` 在 Host 侧免去额外过户确认;实现必须现读活跃 Session的稳定状态并同时匹配其 runtime instance identity;权限切换或关闭在途、远程/缺会话/- 实例不匹配/查询失败均 fail closed,且不得扩到 workspace、Setup、安装/更新、OAuth、- Secret/凭证等其它授权面。instance 仅作为 opaque query 写入 Host 生成的 Pi MCP URL;桥接+ 实例不匹配/查询失败均 fail closed。工作区草稿、工作目录写入和媒体路径揭示等操作审批+ 同样沿用会话权限;MCP 逐次审批标记不得覆盖 Full Access。Setup、OAuth、Secret 的信息+ 输入与安装/更新策略保持原边界。instance 仅作为 opaque query 写入 Host 生成的 Pi MCP URL;桥接注册表不匹配时返回 401。旧 URL 缺 instance 时可兼容普通会话工具,但必须向工具隐藏instance,使 Full Access 自动交接保持 fail closed。+ 会话审批及切档回归见 [pi-auto-review-dispatch.test.ts](../../packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts)。- **MCP 桥**:`piEnvironment.ts` 把 in-process MCP providers 暴露成 localhost streamable-HTTP,并把用户显式配置的外部 HTTP / Streamable HTTP MCP 作为 direct remote server 装入;旧式SSE transport 不在此链支持(但 Streamable HTTP 的 SSE response framing 受支持)。外部 URLdiff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 10ad2972c8..1abe3bdc10 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -300,9 +300,15 @@自动批准须区分 Full Access 与 AI 审阅来源,不得伪装为用户点击,也不得写入人工目录授权记忆。附件自动交接必须写独立 `ghost-tool-grant`,不得写 `ghost-grant`;这是回退兼容边界——旧客户端只认识后者,降级时必须 fail closed,不能把新版自动交接误读成人工永久- 授权。切回 Ask 后新请求恢复确认。Auto 的工作区草稿创建和媒体路径揭示也逐动作送审,- 审阅期间任务实例、轮次或权限变化时旧 allow 失效。Full Access 旁路**不适用于** workspace 创建、插件- Setup、OAuth、Secret/凭证或其它运行时确认边界,也不改变第 3.1 节的安装/更新策略。+ 授权。切回 Ask 后新请求恢复确认。在途插件操作统一沿用当前会话的操作审批:包括工作区+ 草稿创建、工作目录写入和媒体路径揭示,Full Access 不额外审批,Auto 进入现有统一审阅器,+ Ask 沿用原确认流程。MCP 的 `prompt-each-time` 仅限制授权记忆,不得覆盖 Full Access,+ 也不得跳过 Auto 审阅。审批期间实例、权限或调用归属失效时,旧 allow 不可执行。+ 这不扩大本轮来源/执行范围、不改变跨主机路径归属,不替用户填写 Setup、OAuth、Secret+ 等必要信息,也不改变第 3.1 节的安装/更新策略。自主面板或后台调用不得借用前台会话权限。+ 实现与回归见 [Session.reviewHostPermissionAction](../../packages/maker-core/src/session.ts)、+ [fsSlot.test.ts](../../apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts) 和+ [ghostWorkdirGate.test.ts](../../apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts)。`dir`/`save_dir` 批准的是裁决时解析到的 canonical realpath 快照;出票必须使用该规范路径并在票据库内重新解析核对,路径映射已变化时拒绝并要求重新确认。出票后真正读/写时仍须再次核对根与目标真身;保存文件必须排他创建且不跟随最终 symlink,不能让短命票据留下消费期diff --git a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.tsindex dcde05104c..0b14d5f78a 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts@@ -999,7 +999,7 @@ describe('prompt-each-time never turns into a persisted grant', () => {await handle.close();});- it('denies a pending forced prompt when the session switches to a laxer mode', async () => {+ it('Full access overrides a pending prompt-each-time MCP approval', async () => {const { handle, canUseTool } = await startSession(() => 'prompt-each-time', {// 决策永不返回:请求挂起,等模式切换来结算。decide: () => undefined,@@ -1014,8 +1014,16 @@ describe('prompt-each-time never turns into a persisted grant', () => {// CC agent 实现了 setPermissionMode (接口上可选是因为其他 agent 可缺省)。await handle.setPermissionMode!('bypassPermissions');- // 切到 Full access 也不能替用户批准这一次高风险调用。- expect((await pending).behavior).toBe('deny');+ expect((await pending).behavior).toBe('allow');+ await handle.close();+ });++ it('Full access allows MCP calls without an extra resolver or classifier approval', async () => {+ const policy = vi.fn(() => 'prompt-each-time' as const);+ const { handle, canUseTool } = await startSession(policy, { permissionMode: 'bypassPermissions', bare: true });+ expect(await canUseTool('mcp__cindy_contacts__call_tool', { name: 'contacts_delete' }, { toolUseID: 'full-mcp' }))+ .toMatchObject({ behavior: 'allow' });+ expect(policy).not.toHaveBeenCalled();await handle.close();});diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 162891ab0d..0bef2bd55c 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -1863,8 +1863,8 @@ export class ClaudeCodeAgent extends BaseAgent {kind: InteractionRequest['kind'];resolve: (d: InteractionDecision) => void;settled: boolean;- /** prompt-each-time 高风险审批: 切到宽松模式时也不接受 dismissAllPending('allow')。 */- forcePrompt?: boolean;+ /** 本轮来源/执行范围约束独立于 MCP 的逐次审批偏好。 */+ turnPolicyForcePrompt?: boolean;/** Auto 审阅故障降级来的确认:系统收口不能当成用户点了拒绝。 */unavailableHandoff?: boolean;/** 目录授权变化会使这次文件读写审批的根快照失效。 */@@ -1884,7 +1884,7 @@ export class ClaudeCodeAgent extends BaseAgent {*/async function dispatchInteraction(req: InteractionRequest,- opts?: { forcePrompt?: boolean; directorySensitive?: boolean },+ opts?: { turnPolicyForcePrompt?: boolean; directorySensitive?: boolean },): Promise<InteractionDecision> {if (!interactionResolver) {return safeDefaultDecision(req.kind, 'no_resolver_attached');@@ -1895,7 +1895,7 @@ export class ClaudeCodeAgent extends BaseAgent {kind: req.kind,resolve,settled: false,- ...(opts?.forcePrompt ? { forcePrompt: true } : {}),+ ...(opts?.turnPolicyForcePrompt ? { turnPolicyForcePrompt: true } : {}),...(opts?.directorySensitive ? { directorySensitive: true } : {}),...(req.kind === 'permission' && isAutoReviewUnavailableMetadata(req.metadata)? { unavailableHandoff: true }@@ -1928,12 +1928,7 @@ export class ClaudeCodeAgent extends BaseAgent {const entries = Array.from(pendingInteractions.entries());for (const [requestId, entry] of entries) {if (entry.settled) continue;- // forcePrompt(prompt-each-time 高风险审批)不接受"切到宽松模式"的批量放行 ——- // 没拿到用户对这一次调用的明确确认就 fail-closed 拒绝, 与 Codex 侧同名逻辑- // 一致。否则用户在 pending 期间切到 auto / bypassPermissions, 一个破坏性的- // contacts 调用就被自动 allow 了。- const effectiveResolveAs: 'allow' | 'deny' =- resolveAs === 'allow' && entry.forcePrompt === true ? 'deny' : resolveAs;+ const effectiveResolveAs = resolveAs === 'allow' && entry.turnPolicyForcePrompt ? 'deny' : resolveAs;const decision = effectiveResolveAs === 'allow' && entry.kind !== 'ask_user_question'? ({ kind: entry.kind, behavior: 'allow' } as InteractionDecision): safeDefaultDecision(entry.kind, reason);@@ -1975,31 +1970,16 @@ export class ClaudeCodeAgent extends BaseAgent {* "Codex 静默执行 / Claude 每次调用都弹窗"的分叉(浏览器自动化这类高频 server* 一次调研能攒出上百个权限请求)。* auto-approve → 静默放行, 不打扰用户- * prompt-each-time → 照常弹窗, 且全程禁止持久化授权(suggestion 不下发、- * decision 带回来的 permissionUpdates 也丢弃、切到宽松- * 模式时 pending 请求 fail-closed)+ * prompt-each-time → Ask 逐次确认且不持久化授权;Auto 交统一审阅器;+ * Full access 不弹窗,已挂起的普通审批也随新档位结算* prompt / 未注入 → 完全维持原有权限链* 策略抛错或返回非法值时按最保守的 prompt-each-time 处理(与 Codex 侧一致)。** 本地 canUseTool 与远端 onApprovalRequest 都走这里 —— 否则同一套 MCP 配置在* SSH 会话里又会退回"逐次弹窗 + 没有 forced prompt 保护"的老行为。*- * **已知差异(bypassPermissions)**: 该档位下 SDK 直接跳过全部权限检查- * (allowDangerouslySkipPermissions, 见 SDK PermissionMode 文档), canUseTool 根本- * 不会被调用, 所以这里的 prompt-each-time 拦不住 Full access 会话 —— 那是该档位- * 本身的语义("Accepts all permissions"), 不是本函数的兜底范围。Codex 侧的- * forcePrompt 走自己的 approval 通道, 在 Full access 下仍会弹, 两端在这一档不等价。- *- * 抹平它的两条路都不便宜(结论来自 cc 2.1.219 的 cli.js 权限判定 `zd8`):- * - PreToolUse hook: hook 无条件执行(先于权限判定), 且 hook 返回 deny 会在 `zd8`- * 首个分支直接阻断、不看 permissionMode —— 所以 hook 能在 Full access 下**拒绝**;- * 但 hook 返回 ask 会落到正常权限管线, 而该管线在 bypass 下就是放行, 所以做不到- * Codex 那样的"仍然弹窗询问"。只能把高风险 action 变成硬拒绝, 用户在自己选了- * Full access 之后反而做不了这些操作, 体验上不可接受。- * - 让 Full access 停在可回调档(default) + canUseTool 里模拟放行普通工具: 能拿到- * 真 parity, 但 Full access 的判定语义会整体改变(settings 的 deny 规则、沙箱网络- * 等不经 canUseTool 的检查都会重新生效), 必须实机验证后才能上。- * 因此本轮如实保留差异, 不做半吊子拦截。+ * SDK 的 bypassPermissions 原生跳过操作审批;Host 回调同样遵循当前档位,+ * 不通过 hook 或 MCP 风险分类重新引入 Full access 特殊审批。*/const classifyMcpApprovalPolicy = (toolName: string,@@ -2184,6 +2164,9 @@ export class ClaudeCodeAgent extends BaseAgent {: 'This downstream source was not selected.',};}+ if (mutablePermissionMode === 'bypassPermissions' && !forceTurnConfirmation(toolName, input)) {+ return { behavior: 'allow', updatedInput: input };+ }// Auto can resolve allow/block without a UI. Other modes retain the// existing fail-closed behavior when no interaction surface is attached.const canReviewWithoutUi = mutablePermissionMode === 'auto';@@ -2306,7 +2289,7 @@ export class ClaudeCodeAgent extends BaseAgent {unavailableHandoff? annotatePermissionRequestForUnavailableReview(permissionRequest): permissionRequest,- { forcePrompt, directorySensitive: directorySensitivePermission },+ { turnPolicyForcePrompt, directorySensitive: directorySensitivePermission },);notifyIfAutoReviewConfirmUndelivered(unavailableHandoff, decision);if (decision.kind !== 'permission') {@@ -3310,7 +3293,7 @@ export class ClaudeCodeAgent extends BaseAgent {const REMOTE_APPROVAL_TIMEOUT_MS = 110_000;async function dispatchWithTimeout(req: InteractionRequest,- dispatchOpts?: { forcePrompt?: boolean },+ dispatchOpts?: { turnPolicyForcePrompt?: boolean },): Promise<InteractionDecision> {let timer: NodeJS.Timeout | undefined;try {@@ -3524,7 +3507,7 @@ export class ClaudeCodeAgent extends BaseAgent {remoteUnavailableHandoff? annotatePermissionRequestForUnavailableReview(remotePermissionRequest): remotePermissionRequest,- { forcePrompt: remoteForcePrompt },+ { turnPolicyForcePrompt: remoteTurnPolicyForcePrompt },);} catch {if (remoteUnavailableHandoff) autoReviewConfirmUndeliveredNotice.notify();diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 918fa0ce70..a7dc55712f 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -14118,9 +14118,8 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});- it('still prompts for prompt-each-time inner MCP calls in Full access mode', async () => {- // 回归:宽松档曾无条件 accept, 让高风险 inner tool(contacts_delete 等)- // 绕过逐次确认;Full access 也必须保留 forcePrompt 护栏。+ it('Full access overrides prompt-each-time inner MCP approval policy', async () => {+ // MCP 风险分类不能覆盖用户显式选择的会话权限。const agent = new CodexAgent(createDeps({}, {getMcpToolApprovalPolicy: () => 'prompt-each-time',}));@@ -14153,13 +14152,13 @@ describe('CodexAgent MCP thread context hooks', () => {requestedSchema: {},});- expect(resolver).toHaveBeenCalledTimes(1);- expect(result).toEqual({ action: 'decline', content: null, _meta: null });+ expect(resolver).not.toHaveBeenCalled();+ expect(result).toEqual({ action: 'accept', content: null, _meta: null });await handle.close();});- it('declines pending prompt-each-time approvals when permission mode switches to auto', async () => {- // Auto 也不能批量放行 forcePrompt 高风险审批,必须 fail-closed 关闭挂起请求。+ it.each(['auto', 'bypassPermissions'] as const)('pending MCP approvals follow a switch to %s', async (mode) => {+ // Full 批准挂起请求;Auto 不能将尚未审阅的旧请求批量批准。const agent = new CodexAgent(createDeps({}, {getMcpToolApprovalPolicy: () => 'prompt-each-time',}));@@ -14191,14 +14190,14 @@ describe('CodexAgent MCP thread context hooks', () => {});if (!handle.setPermissionMode) throw new Error('expected setPermissionMode');- await handle.setPermissionMode('auto');+ await handle.setPermissionMode(mode);- await expect(responsePromise).resolves.toEqual({ action: 'decline', content: null, _meta: null });+ await expect(responsePromise).resolves.toEqual({ action: mode === 'auto' ? 'decline' : 'accept', content: null, _meta: null });await expect(nextEvent(iterator)).resolves.toMatchObject({type: 'interaction_dismissed',data: {- reason: 'permission_mode_changed_to_auto',- resolvedAs: 'deny',+ reason: `permission_mode_changed_to_${mode}`,+ resolvedAs: mode === 'auto' ? 'deny' : 'allow',},});pendingDecision.resolve({ kind: 'permission', behavior: 'allow' });@@ -16242,7 +16241,7 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});- it('keeps host dynamic tool calls behind the existing MCP approval policy', async () => {+ it.each(['ask', 'bypassPermissions'] as const)('host dynamic tool approvals follow %s', async (permissionMode) => {const disclosure = {title: 'Allow the Agent to connect to and control this simulator?',description:@@ -16272,20 +16271,21 @@ describe('CodexAgent MCP thread context hooks', () => {sessionId: 'session-ios-dynamic-approval',model: 'gpt-5.4',workingDir: '/repo',- permissionMode: 'bypassPermissions',+ permissionMode,});- handle.setInteractionResolver(async (request) => {+ const resolver = vi.fn(async (request: InteractionRequest) => {expect(request).toMatchObject({kind: 'permission',- toolUseId: 'call-ios',toolName: 'dynamic:cindy_ios_simulator:call_tool',+ input: { serverName: 'cindy_ios_simulator', toolName: 'call_tool', toolParams: { name: 'attach_device', args: { udid: 'SIM-1' } } },title: disclosure.title,description: disclosure.description,});if (request.kind !== 'permission') throw new Error('expected permission request');expect(request.suggestions).toBeUndefined();- return { kind: 'permission', behavior: 'deny' };+ return { kind: 'permission' as const, behavior: 'deny' as const };});+ handle.setInteractionResolver(resolver);const handlers = host.getThreadHandlers();if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall handler');@@ -16300,16 +16300,20 @@ describe('CodexAgent MCP thread context hooks', () => {},{ requestId: 'request-ios' },);- expect(result).toEqual({- contentItems: [{ type: 'inputText', text: 'Cindy could not approve this tool call: interaction_resolver_error' }],- success: false,- });+ expect(result.success).toBe(permissionMode === 'bypassPermissions');+ expect(result.contentItems).toEqual([{+ type: 'inputText',+ text: permissionMode === 'bypassPermissions'+ ? '{"ok":true}'+ : 'User denied this tool call via Cindy.',+ }]);+ expect(resolver).toHaveBeenCalledTimes(permissionMode === 'ask' ? 1 : 0);expect(presentation).toHaveBeenCalledWith({serverName: 'cindy_ios_simulator',toolName: 'call_tool',toolParams: { name: 'attach_device', args: { udid: 'SIM-1' } },});- expect(callTool).not.toHaveBeenCalled();+ expect(callTool).toHaveBeenCalledTimes(permissionMode === 'ask' ? 0 : 1);await handle.close();});diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 5a529f5ecd..40d611a056 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -6644,8 +6644,8 @@ export class CodexAgent extends BaseAgent {reviewing?: boolean;turnId: string | null;itemId?: string;- /** prompt-each-time 高风险审批: 宽松模式也必须弹 UI, dismissAllPending('allow') 不得放行 */- forcePrompt?: boolean;+ /** 本轮来源/执行范围约束独立于 MCP 的逐次审批偏好。 */+ turnPolicyForcePrompt?: boolean;/** Auto 审阅故障降级来的确认:系统收口不能当成用户点了拒绝。 */unavailableHandoff?: boolean;onSystemDenied?: (reason: string) => void;@@ -6921,20 +6921,19 @@ export class CodexAgent extends BaseAgent {: 'The permission confirmation could not be completed. No user rejection was received.';emitAutoReviewRuntimeNotice(`[${code}] ${text}`);};- let forcePrompt =- opts?.forcePrompt === true ||- (req.kind === 'permission' &&- forceTurnConfirmation(req.toolName, req.input));+ const turnPolicyForcePrompt = req.kind === 'permission'+ && forceTurnConfirmation(req.toolName, req.input);+ let forcePrompt = opts?.forcePrompt === true || turnPolicyForcePrompt;let unavailableHandoff = false;let approvalRequest = req;// Full access 的普通审批不应打断用户。Auto 在已验证路由上由 app-server// auto_review 负责;fallback 路由则由 user reviewer 把越界请求发回客户端,// 再由 Cindy reviewer 静默裁决。- // forcePrompt 高风险 MCP inner tool- // retains its independent confirmation outside Auto.+ // MCP 的逐次审批标记不能覆盖用户选择的 Full access。+ // 独立的本轮执行范围约束仍由 turn policy 决定。if (- !forcePrompt &&- mutablePermissionMode === 'bypassPermissions'+ mutablePermissionMode === 'bypassPermissions' &&+ !turnPolicyForcePrompt) {return Promise.resolve('accept');}@@ -7025,7 +7024,7 @@ export class CodexAgent extends BaseAgent {settled: false,turnId,...(opts?.itemId ? { itemId: opts.itemId } : {}),- forcePrompt,+ turnPolicyForcePrompt,...(unavailableHandoff ? { unavailableHandoff: true } : {}),onSystemDenied: (reason) => reportMcpDenial('system', reason, false),};@@ -7081,7 +7080,7 @@ export class CodexAgent extends BaseAgent {/*** 强制 resolve 所有挂起的 approval, emit interaction_dismissed 让 UI 关 dialog。* 调用场景: setPermissionMode 切换 / close session。- * - resolveAs='allow' (mode 切到 bypass; forcePrompt 仍 fail-closed): decision='accept'+ * - resolveAs='allow' (mode 切到 bypass): decision='accept'* - resolveAs='deny' (mode 切到 ask/auto 或 close): decision='decline'*/function dismissAllPending(reason: string, resolveAs: 'allow' | 'deny', preserveReviewing = false): void {@@ -7091,11 +7090,7 @@ export class CodexAgent extends BaseAgent {if (entry.settled || (preserveReviewing && entry.reviewing)) continue;entry.settled = true;pendingApprovals.delete(requestId);- // forcePrompt(prompt-each-time 高风险审批)不接受"切到宽松模式"的批量放行——- // 没拿到用户对这一次调用的明确确认就 fail-closed 拒绝, 与 awaitApprovalDecision- // 里宽松模式仍强制弹 UI 的语义一致。- const effectiveResolveAs: 'allow' | 'deny' =- resolveAs === 'allow' && entry.forcePrompt === true ? 'deny' : resolveAs;+ const effectiveResolveAs = resolveAs === 'allow' && entry.turnPolicyForcePrompt ? 'deny' : resolveAs;if (effectiveResolveAs === 'deny') entry.onSystemDenied?.(reason);if (effectiveResolveAs === 'deny' && entry.unavailableHandoff && entry.kind !== 'mcpServerElicitation') {autoReviewConfirmUndeliveredNotice.notify();@@ -8419,8 +8414,7 @@ export class CodexAgent extends BaseAgent {? codexSessionApprovalSuggestions(): undefined,},- // prompt-each-time:Full access 也必须逐次弹 UI,否则高风险 inner tool- // (contacts delete/merge/系统回写)会被 awaitApprovalDecision 首分支静默放行。+ // 逐次标记只限制 Ask/Auto 的授权记忆,不覆盖 Full access。{forcePrompt:turnPolicyForcePrompt || approvalPolicy === 'prompt-each-time',diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex 387fdf5c30..106e049608 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -4745,10 +4745,9 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {});/**- * 放宽档位不得替用户批准他还没表态的**高风险**调用:prompt-each-time 的挂起卡在切到- * Full access 时仍按 fail-closed 拒绝(与 CC / Codex 的 forcePrompt 语义一致)。+ * MCP 逐次审批不能覆盖 Full access;已挂起的操作审批也按新档位结算。*/- it('keeps a pending prompt-each-time card fail-closed even when the mode widens', async () => {+ it('allows a pending prompt-each-time card when switching to Full access', async () => {const handle = await start('ask', undefined, false, {serverNames: ['cindy_ssh'],policy: () => 'prompt-each-time',@@ -4762,7 +4761,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {expect(await waitForResponse('r27')).toEqual({type: 'extension_ui_response',id: 'r27',- confirmed: false,+ confirmed: true,});});@@ -4776,8 +4775,6 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {policy: () => 'prompt-each-time',});handle.setInteractionResolver?.(async () => {- // 用户点「拒绝」的同一时刻切到 Full access。- await handle.setPermissionMode?.('bypassPermissions');return { kind: 'permission', behavior: 'deny' } as never;});firePermissionRequest('r25', 'mcp__cindy_ssh__ssh_exec', {@@ -4788,6 +4785,8 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {id: 'r25',confirmed: false,});+ await handle.setPermissionMode?.('bypassPermissions');+ expect(await waitForResponse('r25')).toMatchObject({ confirmed: false });});/**diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex ff43fd0bbc..d7608822fe 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -3749,7 +3749,7 @@ export class PiAgent extends BaseAgent {* turn's prompt still fails closed to deny.*/settle: PiPendingPromptSettle;- /** 高风险审批(MCP prompt-each-time、灰区 ask、审查中收紧):放宽档位不得批量放行。 */+ /** 来源/本轮范围约束或非操作审批,不随 Full access 自动结算。 */forcePrompt: boolean;/** Auto 审阅故障降级来的确认:系统收口不能当成用户点了拒绝。 */unavailableHandoff?: boolean;@@ -3786,8 +3786,7 @@ export class PiAgent extends BaseAgent {});continue;}- // 放宽档位不能替用户批准他还没表态的高风险调用:没拿到这一次的明确确认就 fail-closed- // (与 CC / Codex 的同名逻辑一致 —— 否则 pending 期间切档能让破坏性调用自动过)。+ // 普通操作审批沿用新档位;来源/本轮范围等独立约束不能因此被扩大。const effectiveResolveAs: 'allow' | 'deny' = resolveAs === 'allow' && entry.forcePrompt ? 'deny' : resolveAs;if (effectiveResolveAs === 'deny' && entry.unavailableHandoff) {autoReviewConfirmUndeliveredNotice.notify();@@ -4275,6 +4274,7 @@ export class PiAgent extends BaseAgent {const requestUserDecision = async (options: { forcePrompt: boolean; unavailableHandoff?: boolean },): Promise<PiPermissionResolution | null> => {+ if (permissionMode === 'bypassPermissions' && !adopted && !turnPolicyForcePrompt) return 'allow';// Session wires the resolver immediately after handle creation. Keep a// very fast Ask/gray request pending until that wiring exists instead// of turning startup ordering into a denial. The runner timeout remains@@ -4290,7 +4290,7 @@ export class PiAgent extends BaseAgent {resolve(resolution);};unregister = registerPendingPrompt(requestId, {- forcePrompt: options.forcePrompt,+ forcePrompt: adopted || turnPolicyForcePrompt,...(options.unavailableHandoff ? { unavailableHandoff: true } : {}),// Durable child: losing the surface parks the question.deferWhenSurfaceLost: true,@@ -8200,15 +8200,14 @@ export class PiAgent extends BaseAgent {});};/**- * Full access 的普通工具语义是「不问、直接放行」;独立确认域不继承该语义。档位支持+ * Full access 的操作审批语义是「不问、直接放行」。档位支持* 会话中途热切换(bridge 每次 tool_call 现读 perm 文件),所以必须**按最新档位**判断,* 不能用请求冒泡那一刻的快照。*/const isFullAccessNow = (): boolean => getPermissionCtx().permissionMode === 'bypassPermissions';/**- * `forcePrompt` 标记高风险审批(MCP prompt-each-time、灰区 ask、审查中收紧档位):- * 等卡期间用户把档位放宽,这类**不**接受批量放行,仍按 fail-closed 拒绝 —— 与 CC /- * Codex 的 dismissAllPending 同口径。+ * MCP 逐次确认和 AI ask 不覆盖 Full access;来源/本轮范围约束与需要用户输入的+ * 交互仍保留。是否允许持久化决定,不等于是否继承会话权限。*/const requestUserConfirmation = async (opts?: {@@ -8218,22 +8217,18 @@ export class PiAgent extends BaseAgent {},): Promise<PiPermissionResolution> => {// 发起确认前:已切到 Full access 就不该再弹卡。- // 但 forcePrompt 代表不能被权限放宽追认的安全边界;若 host lease / 预检失效- // 真的让 policy turn 落进 Full access,宁可拒绝也不能静默放行。+ // 本轮范围仍由 policy 约束,不能把 MCP 风险标记当成第二份会话权限。if (isFullAccessNow() && opts?.requireExplicitDecision !== true) {- if (opts?.forcePrompt === true && opts.unavailableHandoff) {- notifyAutoReviewConfirmUndelivered();- }- return opts?.forcePrompt === true ? 'system-deny' : 'allow';+ return turnPolicyForcePrompt ? 'system-deny' : 'allow';}const outcome = await requestUserDecision({- forcePrompt: opts?.forcePrompt === true || opts?.requireExplicitDecision === true,+ forcePrompt: turnPolicyForcePrompt || opts?.requireExplicitDecision === true,...(opts?.unavailableHandoff ? { unavailableHandoff: true } : {}),});// 已有决策(用户明确表态,或切档时代为 settle)→ 以它为准,不再被档位二次翻转。if (outcome.decided) return outcome.resolution;// 拿不到决策:Full access 下按 bypass 语义放行,其余一律 fail-closed。- return opts?.forcePrompt === true+ return turnPolicyForcePrompt|| opts?.requireExplicitDecision === true|| !isFullAccessNow()? outcome.resolutiondiff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.tsindex 3d7d4577c2..127f176a62 100644--- a/packages/maker-core/src/session.close.test.ts+++ b/packages/maker-core/src/session.close.test.ts@@ -418,7 +418,7 @@ describe('Session close lifecycle', () => {describe('Host automatic review lifecycle', () => {- function setup(agentKind: 'pi' | 'codex' = 'pi') {+ function setup(agentKind: 'pi' | 'codex' = 'pi', permissionMode: 'auto' | 'ask' | 'bypassPermissions' = 'auto') {const events = createAsyncQueue<AgentEvent>();let running = false;const reviewGate = createDeferred();@@ -433,7 +433,7 @@ describe('Host automatic review lifecycle', () => {} as unknown as AgentSessionHandle;const session = new Session({ id: 'host-review', agentKind, workDir: '/repo', handle,capabilities: { permissionModes: [{ id: 'ask', displayName: 'Ask' }], setPermissionModeMidSession: { supported: true } } as never,- logger: createLogger(), permissionMode: 'auto', turnStallMs: 0,+ logger: createLogger(), permissionMode, turnStallMs: 0,});const emit = async (event: AgentEvent) => {if (event.type === 'done') running = false;@@ -446,6 +446,25 @@ describe('Host automatic review lifecycle', () => {return { session, review, reviewGate, closeGate, modeGate, emit };}const action = { kind: 'other' as const, description: 'plugin file handoff' };+ it.each(['bypassPermissions', 'ask'] as const)('Host operations follow %s without AI review', async (mode) => {+ const { session, review, closeGate } = setup('pi', mode);+ expect(await session.reviewHostPermissionAction(action)).toEqual({ verdict: mode === 'ask' ? 'ask' : 'allow' });+ expect(review).not.toHaveBeenCalled();+ closeGate.resolve();+ await session.close();+ expect(await session.reviewHostPermissionAction(action)).toMatchObject({ verdict: 'block' });+ });+ it('does not use Full access while the permission mode is changing', async () => {+ const { session, modeGate, closeGate } = setup('pi', 'bypassPermissions');+ const changing = session.setPermissionMode('ask');+ await vi.waitFor(() => expect(session.stablePermissionModeState).toBeNull());+ expect(await session.reviewHostPermissionAction(action)).toMatchObject({ verdict: 'block' });+ modeGate.resolve();+ await changing;+ expect(await session.reviewHostPermissionAction(action)).toEqual({ verdict: 'ask' });+ closeGate.resolve();+ await session.close();+ });it('returns the reviewer decision while the session is stable', async () => {const { session, reviewGate } = setup();reviewGate.resolve();diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 5e55976c06..87577d9bb7 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -1490,6 +1490,7 @@ export class Session {async reviewHostPermissionAction(action: ReviewableAction): Promise<AutoReviewDecision> {const permission = this.stablePermissionModeState;if (!permission) return { verdict: 'block', reason: 'Session permissions are changing or the task has closed.' };+ if (permission.mode === 'bypassPermissions') return { verdict: 'allow' };if (permission.mode !== 'auto') return { verdict: 'ask' };// Host steps can belong to a still-active descendant after the foreground// turn finishes. Guard Session authority here; root-turn generation is notdiff --git a/packages/plugin-protocol/src/__tests__/manifest.test.ts b/packages/plugin-protocol/src/__tests__/manifest.test.tsindex a708302fa8..ff19a016a3 100644--- a/packages/plugin-protocol/src/__tests__/manifest.test.ts+++ b/packages/plugin-protocol/src/__tests__/manifest.test.ts@@ -1182,6 +1182,29 @@ describe('Ghost manifest contract', () => {]);});+ it('accepts only plugin-local declared OAuth references for Node bindings', () => {+ const manifest = {+ ...validManifest, settingsHtml: 'settings.html', slots: ['tool', 'network', 'node'],+ network: { hosts: ['example.test'], secrets: [{+ key: 'mail_account', label: 'Mail', source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: { authorizeUrl: 'https://example.test/auth', tokenUrl: 'https://example.test/token', scopes: ['mail'] },+ }] },+ node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio', secretBindings: [{+ key: 'access_token', label: 'Mail', methods: ['run'], oauthSecret: 'mail_account',+ }] },+ };+ const result = validateGhostManifest(manifest);+ expect(result.ok).toBe(true);+ if (result.ok) expect(result.manifest.node?.secretBindings?.[0]?.oauthSecret).toBe('mail_account');+ const missing = structuredClone(manifest);+ missing.node.secretBindings[0].oauthSecret = 'other_plugin';+ expect(validateGhostManifest(missing).ok).toBe(false);+ const staticSource = structuredClone(manifest);+ staticSource.network.secrets[0].source = 'user';+ expect(validateGhostManifest(staticSource).ok).toBe(false);+ });+it('rejects unsafe Node secret bindings and shared credential-key collisions', () => {const base = {...validManifest,diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.tsindex 40ec213471..a32227ca9e 100644--- a/packages/plugin-protocol/src/manifest.ts+++ b/packages/plugin-protocol/src/manifest.ts@@ -239,6 +239,8 @@ export function isGhostNodeMcpReservedMethod(method: string): boolean {* Worker 获得明文后仍可能主动回传或泄露。未声明 entry 时只允许主入口。*/export interface GhostNodeSecretBinding {+ /** 引用本插件 network.secrets 中的 OAuth key;仅注入短期 access token。 */+ oauthSecret?: string;/** 凭证键(插件内唯一):小写字母开头,允许小写/数字/下划线,1–32。 */key: string;/** 给用户看的名称(插件详情与设置状态使用)。 */@@ -3148,7 +3150,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {}const binding = bindingRaw as Record<string, unknown>;const unknownBindingField = Object.keys(binding).find(- (key) => !['key', 'label', 'methods', 'entry', 'hint', 'url'].includes(key),+ (key) => !['key', 'label', 'methods', 'entry', 'hint', 'url', 'oauthSecret'].includes(key),);if (unknownBindingField) {return {@@ -3262,7 +3264,12 @@ export function validateGhostManifest(value: unknown): ManifestValidation {};}}+ if (binding.oauthSecret !== undefined &&+ (typeof binding.oauthSecret !== 'string' || !/^[a-z][a-z0-9_]{0,31}$/.test(binding.oauthSecret))) {+ return { ok: false, reason: 'node.secretBindings[].oauthSecret 必须是本插件 OAuth 凭证键' };+ }nodeSecretBindings.push({+ ...(binding.oauthSecret !== undefined ? { oauthSecret: binding.oauthSecret as string } : {}),key: binding.key,label: binding.label,methods,@@ -3594,6 +3601,13 @@ export function validateGhostManifest(value: unknown): ManifestValidation {// setup 引用必须在交付边界就与同一份 manifest 的凭证、连接和设置入口对齐;// 不能让服务端接受、Desktop 装入时才拒绝。+ for (const binding of node?.secretBindings ?? []) {+ if (binding.oauthSecret === undefined) continue;+ const source = network?.secrets?.find((secret) => secret.key === binding.oauthSecret);+ if (source?.source !== 'oauth' || !source.oauth) {+ return { ok: false, reason: 'node.secretBindings[].oauthSecret 必须引用本插件已声明的 OAuth 凭证' };+ }+ }let setup: GhostSetupDecl | undefined;if (raw.setup !== undefined) {if (!isPlainObject(raw.setup)) {@@ -3630,7 +3644,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {},] as const,),- ...(node?.secretBindings ?? []).map(+ ...(node?.secretBindings ?? []).filter((secret) => !secret.oauthSecret).map((secret) => [secret.key, { hostDerivedSource: null }] as const,),]);