Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): fence initial plans and remember task write consent refusals
Dashd056ec707123
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 3fb1977361..646daa0fbb 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -3916,6 +3916,8 @@ const r = await cindy.agent.requestSchedule({\`\`\`js// requestWriteAccess({taskId, mode: 'auto'}) 请求宿主原生确认,不能替用户确认。+// 拒绝或失败后,同一账号代际/安装修订/任务在当前宿主进程不再自动弹窗(更换 mode 也不重置)。+// 用户可从本机任务权限菜单“重新确认插件写权限”恢复原请求;插件不能清除拒绝记录。// 省略 mode 保留 acceptEdits;Auto 插件主任务的 Worker 使用 Auto,不改全局权限。const task = await cindy.tasks.create({ requestKey: 'experiment-1-create', title: 'My evaluation' });diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex c1eca86542..400d4a37c8 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1770,6 +1770,12 @@ export function getInstalledGhostName(id: string): string | null {return findAvailableGhost(id)?.manifest.name ?? null;}+/** Host-only identity for permission attempts; never a plugin-provided revision. */+export function getPluginTaskInstallRevision(id: string): string | null {+ const ghost = findAvailableGhost(id);+ return hasPluginTaskApproval(ghost) ? ghostInstallApprovalToken(ghost?.approval) : null;+}+let nodeRuntimeBrokerSingleton: GhostNodeRuntimeBroker | null = null;let nodeRuntimeStartAttemptContextReader: (() => NodeRuntimeStartAttemptContext) | null = null;const nodeRuntimeAppRunId = (() => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginPlanHistory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginPlanHistory.test.tsnew file mode 100644index 0000000000..b8a58cac59--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginPlanHistory.test.ts@@ -0,0 +1,40 @@+import { readFileSync } from 'node:fs';+import { expect, it, vi } from 'vitest';+import ts from 'typescript';+import { PluginTaskError } from '../pluginTaskService.js';+import { withSendToSessionLock, hasSendToSessionLock } from '../sendToSessionLock.js';+const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');+const compile = (text: string) => ts.transpileModule(text, {compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;+it.each(['empty', 'user', 'started', 'ended', 'worker', 'reserved', 'unavailable'])('checks durable plan admission after persistence: %s', async state => {+ const start=source.indexOf('assertTeamPlanUnstarted: async taskId => {');+ const property=source.slice(start,source.indexOf('\n createSession:',start)).trim().replace(/,$/,'');+ const tables=['messages','sessions','orcaWorkers','orcaTeams','orcaWorkerCreationReservations'];+ const records=Object.fromEntries(tables.map(name=>[name,{name}]));+ let drained=false;+ const snapshot={client:{drizzle:{select:()=>{+ let table:{name:string};+ const query={from(value:{name:string}){table=value;return query;},innerJoin(){return query;},where(){return query;},async limit(){+ expect(drained).toBe(true);+ if(state==='unavailable')throw Error('unavailable');+ if(table.name==='sessions')return [{startedAt:state==='started'?0:null,endedAt:state==='ended'?1:null}];+ const populated:Record<string,string>={user:'messages',worker:'orcaWorkers',reserved:'orcaWorkerCreationReservations'};+ return table.name===populated[state]?[{id:'existing'}]:[];+ }};return query;+ }}}};+ const deps={snapshot,assertCurrent:vi.fn(),drainPersistQueue:async()=>{drained=true;},PluginTaskError,eq:vi.fn(),and:vi.fn(),gte:vi.fn(),...records};+ const check=new Function(...Object.keys(deps),compile(`return ({${property}}).assertTeamPlanUnstarted;`))(...Object.values(deps));+ if(state==='empty')await expect(check('task')).resolves.toBeUndefined();+ else await expect(check('task')).rejects.toThrow(state==='unavailable'?'unavailable':'Register the team plan');+});+it('holds the real send lock from directory validation through plan persistence',async()=>{+ const branch=source.slice(source.indexOf(" case 'setTeamPlan':"),source.indexOf(" case 'releaseWorker':"));+ const epoch={};const task={workingDir:'/root',revision:1};+ let release!:()=>void;const saving=new Promise<void>(resolve=>{release=resolve;});+ const save=vi.fn(async()=>{expect(hasSendToSessionLock('plan-history')).toBe(true);await saving;return {ok:true};});+ const deps={withSendToSessionLock,getCurrentDbClientSnapshot:()=>epoch,service:{get:async()=>task,setTeamPlan:save},readGhostErrandConfig:()=>({workingDir:'/root'}),isPluginTaskAuthorized:()=>true,isGhostPickedDir:()=>false,PluginTaskError,resolvePluginWorkerDirectory:async()=>{expect(hasSendToSessionLock('plan-history')).toBe(true);}};+ const run=new Function(...Object.keys(deps),compile(`return async function(pluginId,request){switch(request.kind){${branch}}}`))(...Object.values(deps));+ const pending=run('plugin',{kind:'setTeamPlan',taskId:'plan-history',plan:{items:[{workingDir:'/root'}]}});+ try {await vi.waitFor(()=>expect(save).toHaveBeenCalledOnce());expect(hasSendToSessionLock('plan-history')).toBe(true);}+ finally {release();await pending;}+ await vi.waitFor(()=>expect(hasSendToSessionLock('plan-history')).toBe(false));+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.tsindex d4e1bffbff..d79f0a4316 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts@@ -3,12 +3,15 @@ import { describe, expect, it, vi } from 'vitest';import ts from 'typescript';import { withSessionRestartLock, withSendToSessionLock, sendToSessionLocks } from '../sendToSessionLock.js';import { isPluginTaskPermissionAllowed, PluginTaskError } from '../pluginTaskService.js';+import { PluginWriteAccessGate } from '../pluginWriteAccessGate.js';// Execute the real switch branch with controlled Host boundaries.const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');const branch = source.slice(source.indexOf(" case 'requestWriteAccess': {"), source.indexOf(" case 'startTeam': {"));-const js = ts.transpileModule(`return async function(pluginId, request) { switch(request.kind) { ${branch} } }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+const js = ts.transpileModule(`return async function(pluginId, request, explicitWriteAccess = false, assertCallerCurrent = () => {}) { switch(request.kind) { ${branch} } }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;function fixture() {+ let identity = 'owner-epoch-install';+ const gate = new PluginWriteAccessGate();let cfg: Record<string, unknown> = { permissionMode: 'plan', model: 'old' };const history = { input: false, startedAt: null as number | null, endedAt: null as number | null };const messages = {id:'message-id',sessionId:'session-id',role:'role'}, sessions = {id:'session-id',activeTurnStartedAt:'started',lastTurnEndedAt:'ended'};@@ -22,10 +25,34 @@ function fixture() {const dialog = { showMessageBox: vi.fn(async () => ({ response: 0 })) };const write = vi.fn((_id: string, value: Record<string, unknown>) => { cfg = value; });const deps = { isPluginTaskPermissionAllowed, withSessionRestartLock, drainPersistQueue:drain,messages,sessions,eq:()=>true,and:()=>true,service, getCurrentDbClientSnapshot: () => epoch, readGhostErrandConfig: () => cfg, pluginPermissionRequests: slots, PluginTaskError, maker: { getSession: () => live }, inputCoordinator: { getQueueControlSnapshot: () => ({ pendingQueue: [] }) }, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampErrandPermissionMode: (x: string) => x, writeGhostErrandConfig: write, broadcastSessionPatched: vi.fn() };- const run = new Function(...Object.keys(deps), js)(...Object.values(deps));- return { run: (mode = 'acceptEdits') => run('plugin', { kind: 'requestWriteAccess', taskId: 'task', mode }), service, live, epoch, dialog, slots, write, history, drain, config: () => cfg, change: (next: Record<string, unknown>) => { cfg = next; } };+ const allDeps = {...deps, pluginWriteAccessGate:gate, pluginWriteAccessIdentity:()=>identity};+ const run = new Function(...Object.keys(allDeps), js)(...Object.values(allDeps));+ return { run: (mode = 'acceptEdits', explicit = false) => run('plugin', { kind: 'requestWriteAccess', taskId: 'task', mode }, explicit), gate, identity: (next: string) => {identity=next;}, service, live, epoch, dialog, slots, write, history, drain, config: () => cfg, change: (next: Record<string, unknown>) => { cfg = next; } };}describe('plugin write confirmation interleavings', () => {+ it('remembers refusal across modes and repeats, and only Host retry opens the original confirmation',async()=>{+ const f=fixture();f.dialog.showMessageBox.mockResolvedValueOnce({response:1});+ await expect(f.run()).resolves.toEqual({granted:false});+ await expect(f.run('auto')).resolves.toEqual({granted:false});+ await expect(f.run()).resolves.toEqual({granted:false});+ expect(f.gate.recoverable(JSON.stringify(['plugin','task']),'owner-epoch-install')).toBe('acceptEdits');+ expect(f.dialog.showMessageBox).toHaveBeenCalledOnce();expect(f.write).not.toHaveBeenCalled();+ await expect(f.run('acceptEdits',true)).resolves.toMatchObject({granted:true});+ expect(f.dialog.showMessageBox).toHaveBeenCalledTimes(2);+ });+ it('retains failed confirmation suppression, then permits a new owner/install identity',async()=>{+ const f=fixture();f.dialog.showMessageBox.mockRejectedValueOnce(new Error('dialog unavailable'));+ await expect(f.run()).rejects.toThrow('dialog unavailable');+ await expect(f.run()).resolves.toEqual({granted:false});+ f.identity('new-owner-install');+ await expect(f.run()).resolves.toMatchObject({granted:true});+ expect(f.dialog.showMessageBox).toHaveBeenCalledTimes(2);+ });+ it('rejects an install change while permission UI was open',async()=>{+ const f=fixture();f.dialog.showMessageBox.mockImplementationOnce(async()=>{f.identity('replacement');return {response:0};});+ await expect(f.run()).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ expect(f.live.setPermissionMode).not.toHaveBeenCalled();expect(f.write).not.toHaveBeenCalled();+ });it('tracks the permission commit only after confirmation and includes rollback', async () => {const f=fixture();let answer!:()=>void;f.dialog.showMessageBox.mockImplementationOnce(()=>new Promise(resolve=>{answer=()=>resolve({response:0});}));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccessHost.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccessHost.test.tsnew file mode 100644index 0000000000..1020615fa8--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccessHost.test.ts@@ -0,0 +1,42 @@+import { readFileSync } from 'node:fs';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';+import { PluginWriteAccessGate } from '../pluginWriteAccessGate.js';++const source=readFileSync(new URL('../register.ts',import.meta.url),'utf8');+const handler=source.slice(source.indexOf(' const pluginWriteAccessFromHost ='),source.indexOf(" ipcMain.handle('maker:get-plugin-write-access-recovery'"));+const js=ts.transpileModule(`${handler}\nreturn pluginWriteAccessFromHost;`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;+async function fixture(){+ const owner={client:{}};let current:unknown=owner,identity='approved';+ const gate=new PluginWriteAccessGate();await gate.request(JSON.stringify(['plugin','task']),identity,'auto',false,async()=>({granted:false}));+ const event={sender:{isDestroyed:()=>false},senderFrame:{}};+ const read=vi.fn(async()=>({operation:'create',pluginId:'plugin'}));+ const get=vi.fn(async()=>({}));+ const remote=vi.fn(()=>false),trusted=vi.fn(()=>{});+ const call=vi.fn(async(_id:string,_request:unknown,explicit:boolean,assert:()=>void)=>{expect(explicit).toBe(true);assert();return {granted:true};});+ const deps={isDeviceLinkInvoke:remote,assertTrustedAppRendererEvent:trusted,throwIpcError:(code:string,message:string)=>{throw Object.assign(new Error(message),{code});},getCurrentDbClientSnapshot:()=>current,createPluginTaskStore:()=>({get:read}),pluginTaskServiceForCurrentOwner:()=>({get}),pluginWriteAccessIdentity:()=>identity,pluginWriteAccessGate:gate,handlePluginTask:call};+ const run=new Function(...Object.keys(deps),js)(...Object.values(deps));+ return {run:(retry=true)=>run(event,'task',retry),read,get,remote,trusted,call,event,changeOwner:()=>{current={};},changeInstall:()=>{identity='new';}};+}+describe('local task permission recovery boundary',()=>{+ it('reads the original mode without granting and only explicit retry calls the common handler',async()=>{+ const f=await fixture();await expect(f.run(false)).resolves.toEqual({granted:false,available:true});expect(f.call).not.toHaveBeenCalled();+ await expect(f.run()).resolves.toMatchObject({granted:true,mode:'auto'});+ expect(f.call).toHaveBeenCalledWith('plugin',expect.objectContaining({taskId:'task',mode:'auto'}),true,expect.any(Function));+ });+ it.each(['remote','untrusted'] as const)('rejects %s before reading private task records',async kind=>{+ const f=await fixture();if(kind==='remote')f.remote.mockReturnValue(true);else f.trusted.mockImplementation(()=>{throw new Error('untrusted');});+ await expect(f.run()).rejects.toThrow();expect(f.read).not.toHaveBeenCalled();expect(f.call).not.toHaveBeenCalled();+ });+ it('rejects account replacement during task lookup',async()=>{+ const f=await fixture();f.get.mockImplementation(async()=>{f.changeOwner();return {};});+ await expect(f.run()).rejects.toMatchObject({code:'PERMISSION_DENIED'});expect(f.call).not.toHaveBeenCalled();+ });+ it.each(['install','window'] as const)('rechecks %s before the recovered native grant',async point=>{+ const f=await fixture();f.call.mockImplementation(async(_id,_request,_explicit,assert)=>{if(point==='install')f.changeInstall();else f.event.senderFrame={};assert();return {granted:true};});+ await expect(f.run()).rejects.toMatchObject({code:'PERMISSION_DENIED'});+ });+ it('does not let a different installation recover an old denied request',async()=>{+ const f=await fixture();f.changeInstall();await expect(f.run()).resolves.toMatchObject({available:false,granted:false});expect(f.call).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/pluginWriteAccessGate.ts b/apps/desktop/src/main/maker-ipc/pluginWriteAccessGate.tsnew file mode 100644index 0000000000..c292dee452--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/pluginWriteAccessGate.ts@@ -0,0 +1,24 @@+type Mode = 'acceptEdits' | 'auto';+/** Process-local refusal memory. Reloading a plugin does not renew an automatic attempt. */+export class PluginWriteAccessGate {+ private readonly attempts = new Map<string, { identity: string; mode: Mode; pending: boolean }>();++ recoverable(key: string, identity: string): Mode | null {+ const state = this.attempts.get(key);+ return state?.identity === identity && !state.pending ? state.mode : null;+ }++ async request<T extends { granted: boolean }>(key: string, identity: string, mode: Mode, explicit: boolean, attempt: () => Promise<T>): Promise<T | { granted: false }> {+ const previous = this.attempts.get(key);+ if (previous?.pending || (!explicit && previous?.identity === identity)) return { granted: false };+ const state = { identity, mode, pending: true };+ this.attempts.set(key, state);+ try {+ const result = await attempt();+ if (result.granted && this.attempts.get(key) === state) this.attempts.delete(key);+ return result;+ } finally {+ state.pending = false;+ }+ }+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex bb2ca83f1c..c1b0795d17 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,10 +1,11 @@import { isPluginTaskPermissionAllowed, assertPluginTaskResult, createPluginTaskService, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';import { resolvePluginWorkerDirectory } from './pluginWorkerDirectory.js';+import { PluginWriteAccessGate } from './pluginWriteAccessGate.js';import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';import { createPluginTaskStore } from './pluginTaskStore.js';import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';-import { setPluginTaskHandler, isPluginTaskAuthorized } from '../cindy-brain/index.js';-import type { PluginTaskRoute } from '../../shared/pluginTasks.js';+import { setPluginTaskHandler, isPluginTaskAuthorized, getPluginTaskInstallRevision } from '../cindy-brain/index.js';+import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';import { createHash as pluginTaskConfigHash } from 'node:crypto';import { createBotMessageTransport } from './botMessageTransport.js';import { setBotRemoteMessageService } from './botRemoteMessageReceiver.js';@@ -10164,6 +10165,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)readPermissionMode: pluginId => readGhostErrandConfig(pluginId).permissionMode,assertTeamPlanUnstarted: async taskId => {assertCurrent();+ await drainPersistQueue();+ assertCurrent();+ const [input] = await snapshot.client.drizzle.select({id: messages.id}).from(messages).where(and(eq(messages.sessionId, taskId), eq(messages.role, 'user'))).limit(1);+ const [task] = await snapshot.client.drizzle.select({startedAt: sessions.activeTurnStartedAt, endedAt: sessions.lastTurnEndedAt}).from(sessions).where(eq(sessions.id, taskId)).limit(1);+ assertCurrent();+ if (input || task?.startedAt != null || task?.endedAt != null) throw new PluginTaskError('TASK_BUSY', 'Register the team plan before sending input');const workers = await snapshot.client.drizzle.select({id:orcaWorkers.id}).from(orcaWorkers).innerJoin(orcaTeams,eq(orcaWorkers.teamId,orcaTeams.id)).where(eq(orcaTeams.leadSessionId,taskId)).limit(1);const reservations = await snapshot.client.drizzle.select({id:orcaWorkerCreationReservations.id}).from(orcaWorkerCreationReservations).innerJoin(orcaTeams,eq(orcaWorkerCreationReservations.teamId,orcaTeams.id)).where(and(eq(orcaTeams.leadSessionId,taskId),gte(orcaWorkerCreationReservations.expiresAt,Date.now()))).limit(1);assertCurrent();@@ -10277,6 +10284,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}};const pluginPermissionRequests = new Set<string>();+ const pluginWriteAccessGate = new PluginWriteAccessGate();+ const pluginWriteAccessIdentity = (pluginId: string) => {+ const owner = getCurrentDbClientSnapshot();+ const revision = getPluginTaskInstallRevision(pluginId);+ if (!owner || !revision) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin task approval unavailable');+ return JSON.stringify([owner.userId, owner.clientEpoch, revision]);+ };// Projection and release consume the same host-stamped completion evidence.const readPluginWorkerCompletion = async (epoch: NonNullable<ReturnType<typeof getCurrentDbClientSnapshot>>, sessionId: string, status: string) => {const [row] = await epoch.client.drizzle.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);@@ -10288,7 +10302,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');return {row, completedAt: pluginWorkerCompletedAt({status, working:flow.isWorking, queued:flow.queuedCount, paused:flow.queuePaused, startedAt:row?.activeTurnStartedAt ?? null, endedAt:row?.lastTurnEndedAt ?? null, clearedAt:row?.clearedAt, anchor})};};- setPluginTaskHandler(async (pluginId, request) => {+ const handlePluginTask = async (pluginId: string, request: PluginTaskRequest, explicitWriteAccess = false, assertCallerCurrent = () => {}): Promise<unknown> => {const service = pluginTaskServiceForCurrentOwner!();switch (request.kind) {case 'requestWriteAccess': {@@ -10296,8 +10310,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const task = await service.get(pluginId, request.taskId);const mode = request.mode ?? 'acceptEdits';const cfg = readGhostErrandConfig(pluginId);+ assertCallerCurrent();if (isPluginTaskPermissionAllowed(task.permissionMode, cfg.permissionMode) && (mode === 'acceptEdits' ? task.permissionMode === 'acceptEdits' || task.permissionMode === 'auto' : task.permissionMode === 'auto')) return { granted: true, task };if (pluginPermissionRequests.size) throw new PluginTaskError('TASK_BUSY', 'A permission request is already open');+ const identity = pluginWriteAccessIdentity(pluginId);+ const assertRequestCurrent = () => {+ assertCallerCurrent();+ if (snapshot !== getCurrentDbClientSnapshot() || identity !== pluginWriteAccessIdentity(pluginId)) throw new PluginTaskError('PERMISSION_DENIED', 'Permission request identity changed');+ };const before = JSON.stringify(cfg);const assertIdle = async () => {if (mode === 'acceptEdits') {@@ -10319,6 +10339,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)pluginPermissionRequests.add(pluginId);try {await assertIdle();+ assertRequestCurrent();+ // Busy/preflight failures have not asked the user anything; do not consume an attempt.+ return await pluginWriteAccessGate.request(JSON.stringify([pluginId, task.taskId]), identity, mode, explicitWriteAccess, async () => {const result = await dialog.showMessageBox({type: 'question', title: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoTitle' : 'pluginTaskWriteAccess.title'),message: t(mode === 'auto' ? 'pluginTaskWriteAccess.autoMessage' : 'pluginTaskWriteAccess.message').replace('{{name}}', getInstalledGhostName(pluginId) ?? pluginId),@@ -10328,20 +10351,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (result.response !== 0) return { granted: false };// Reuse the existing non-bailing runtime mutation fence; do not hold it over the dialog.return await service.completeOperation(() => withSessionRestartLock(task.taskId, async () => {+ assertRequestCurrent();if (snapshot !== getCurrentDbClientSnapshot() || before !== JSON.stringify(readGhostErrandConfig(pluginId))) throw new PluginTaskError('PERMISSION_DENIED', 'Account or permission settings changed');const fresh = await service.get(pluginId, task.taskId);if (fresh.revision !== task.revision) throw new PluginTaskError('TASK_BUSY', 'Task changed while awaiting permission');await assertIdle();+ assertRequestCurrent();const live = maker.getSession(task.taskId);let persisted = false;try {if (live) await live.setPermissionMode(mode);+ assertRequestCurrent();if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');const saved = await snapshot!.client.tx('bots.persistSessionPermission', {sessionId: task.taskId, mode});persisted = saved.updated;if (!saved.updated) throw new PluginTaskError('TASK_NOT_FOUND', 'Task not found');if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');const updatedTask = await service.get(pluginId, task.taskId);+ assertRequestCurrent();if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');const currentConfig = readGhostErrandConfig(pluginId);if (currentConfig.permissionMode !== cfg.permissionMode) throw new PluginTaskError('PERMISSION_DENIED', 'Permission settings changed');@@ -10354,6 +10381,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)throw error;}}));+ });} finally { pluginPermissionRequests.delete(pluginId); }}case 'startTeam': {@@ -10375,7 +10403,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertPluginTaskResult(result, 'Collaboration could not be started');return result;}- case 'setTeamPlan': {+ case 'setTeamPlan': return withSendToSessionLock(request.taskId, async () => {const epoch = getCurrentDbClientSnapshot();const task = await service.get(pluginId, request.taskId);const cfg = readGhostErrandConfig(pluginId);@@ -10387,7 +10415,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertCurrent();if (current.revision !== task.revision) throw new PluginTaskError('STALE_REVISION', 'Task changed during directory validation');return service.setTeamPlan(pluginId, request.taskId, request.plan);- }+ });case 'releaseWorker': {return service.completeOperation(async () => {const epoch = getCurrentDbClientSnapshot();@@ -10475,7 +10503,41 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)case 'cancel': return service.cancel(pluginId, request.runId);default: throw new PluginTaskError('UNSUPPORTED_CAPABILITY', 'Task operation is unavailable');}- });+ };+ setPluginTaskHandler(handlePluginTask);++ // Local task UI only. The plugin and device-link protocols have no recovery operation.+ const pluginWriteAccessFromHost = async (event: Electron.IpcMainInvokeEvent, taskId: unknown, retry: boolean) => {+ if (isDeviceLinkInvoke()) throwIpcError('PERMISSION_DENIED', 'Local task UI required');+ assertTrustedAppRendererEvent(event);+ if (typeof taskId !== 'string' || !taskId || taskId.length > 128) throwIpcError('INVALID_PARAMS', 'taskId required');+ const owner = getCurrentDbClientSnapshot();+ if (!owner) throwIpcError('INTERNAL', 'Task storage unavailable');+ const frame = event.senderFrame;+ const assertCallerCurrent = () => {+ if (owner !== getCurrentDbClientSnapshot() || event.sender.isDestroyed() || event.senderFrame !== frame) throwIpcError('PERMISSION_DENIED', 'Task UI changed');+ assertTrustedAppRendererEvent(event);+ };+ const receipt = await createPluginTaskStore(owner.client).get(taskId);+ assertCallerCurrent();+ if (!receipt || receipt.operation !== 'create') return { granted: false, available: false };+ try {+ await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId, taskId);+ assertCallerCurrent();+ const identity = pluginWriteAccessIdentity(receipt.pluginId);+ const mode = pluginWriteAccessGate.recoverable(JSON.stringify([receipt.pluginId, taskId]), identity);+ if (!retry || !mode) return { granted: false, available: !!mode };+ const result = await handlePluginTask(receipt.pluginId, {type:'tasks-request', kind:'requestWriteAccess', taskId, mode}, true, () => {+ assertCallerCurrent();+ if (identity !== pluginWriteAccessIdentity(receipt.pluginId)) throwIpcError('PERMISSION_DENIED', 'Plugin installation changed');+ }) as {granted: boolean};+ return { granted: result.granted, available: !result.granted, mode };+ } catch {+ throwIpcError('PERMISSION_DENIED', 'Plugin write permission could not be confirmed');+ }+ };+ ipcMain.handle('maker:get-plugin-write-access-recovery', (event, taskId: unknown) => pluginWriteAccessFromHost(event, taskId, false));+ ipcMain.handle('maker:retry-plugin-write-access', (event, taskId: unknown) => pluginWriteAccessFromHost(event, taskId, true));setGhostErrandRunner(createGhostErrandRunner({diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 9fe7b2ca9f..bdb1dcca2f 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -6703,6 +6703,10 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:set-effort', sessionId, effort),setPermissionMode: (sessionId: string, mode: string): Promise<void> =>ipcRenderer.invoke('maker:set-permission-mode', sessionId, mode),+ getPluginWriteAccessRecovery: (sessionId: string): Promise<{available: boolean}> =>+ ipcRenderer.invoke('maker:get-plugin-write-access-recovery', sessionId),+ retryPluginWriteAccess: (sessionId: string): Promise<{granted: boolean; mode?: 'acceptEdits' | 'auto'}> =>+ ipcRenderer.invoke('maker:retry-plugin-write-access', sessionId),setFastMode: (sessionId: string, enabled: boolean): Promise<void> =>ipcRenderer.invoke('maker:set-fast-mode', sessionId, enabled),setThinkingEnabled: (sessionId: string, enabled: boolean): Promise<void> =>diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex a1face06d3..cb626509ce 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -171,6 +171,7 @@ import {} from './sourceSwitch';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { PermissionSelector } from './PermissionSelector';+import { PluginWriteAccessRecovery } from './PluginWriteAccessRecovery';import { ExtraDirsButton, type CollaborationMenuConfig } from './ExtraDirsButton';import { expandHostCapabilityInvocation } from '../../cindy-brain/hostCapabilityInvocation';import {@@ -8951,6 +8952,7 @@ export function ChatInput({visualVariant={isCreateAgentVariant ? 'create-agent' : 'default'}/><PermissionSelector+ footer={sessionId && !getSessionDeviceId(sessionId) && !deviceLinkDeviceId && !sharedGuest ? <PluginWriteAccessRecovery key={sessionId} sessionId={sessionId} onGranted={onPermissionModeDidChange} /> : undefined}permissionMode={activePermissionMode}onPermissionModeChange={handlePermissionModeChange}vendorKey={vendorKey}diff --git a/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx b/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsxindex dd31095e75..a8f3378bf4 100644--- a/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from 'react';+import { useEffect, useRef, useState, type ReactNode } from 'react';import {Hand,CodeXml,@@ -22,6 +22,8 @@ import {import type { PermissionMode } from '@/lib/userPreferences.types';interface PermissionSelectorProps {+ /** Optional Host task action, mounted only while the menu is visible. */+ footer?: ReactNode;permissionMode: PermissionMode;onPermissionModeChange: (mode: PermissionMode) => void;vendorKey?: 'cc' | 'codex' | 'pi';@@ -99,6 +101,7 @@ function getModeTone(mode: PermissionMode): 'auto' | 'bypassPermissions' | null* 危险档配色只此一份,设置页不得再私搭一套下拉。*/export function PermissionSelector({+ footer,permissionMode,onPermissionModeChange,vendorKey = 'cc',@@ -404,6 +407,7 @@ export function PermissionSelector({)}>{optionsList}+ {open && !disabled ? footer : null}</PopoverContent></Popover>);@@ -423,6 +427,7 @@ export function PermissionSelector({trigger={triggerButton}>{optionsList}+ {open && !disabled ? footer : null}</MorphPopover>);}diff --git a/apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx b/apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsxnew file mode 100644index 0000000000..647bc0895a--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx@@ -0,0 +1,44 @@+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { toast } from '@/lib/toast';+import { Button } from '@/components/ui/button';++/** Mounted only while a local task's permission menu is open. No polling or automatic retry. */+export function PluginWriteAccessRecovery({ sessionId, onGranted }: {+ sessionId: string;+ onGranted?: (mode: 'acceptEdits' | 'auto') => void;+}) {+ const { t } = useTranslation();+ const [available, setAvailable] = useState(false);+ const [pending, setPending] = useState(false);+ const busy = useRef(false);+ const mounted = useRef(false);+ useEffect(() => {+ let active = true;+ mounted.current = true;+ setAvailable(false);+ void window.electronAPI.maker.getPluginWriteAccessRecovery(sessionId)+ .then(result => { if (active) setAvailable(result.available); })+ .catch(() => { if (active) setAvailable(false); });+ return () => { active = false; mounted.current = false; };+ }, [sessionId]);+ if (!available) return null;+ return <Button variant="secondary" tone="quiet" className="mt-1 w-full justify-start" disabled={pending} onClick={async () => {+ if (busy.current) return;+ busy.current = true;+ setPending(true);+ try {+ const result = await window.electronAPI.maker.retryPluginWriteAccess(sessionId);+ if (!mounted.current) return;+ if (result.granted && result.mode) {+ setAvailable(false);+ onGranted?.(result.mode);+ }+ } catch {+ if (mounted.current) toast.error(t('newChat.chatInput.permissionSwitchFailed'));+ } finally {+ busy.current = false;+ if (mounted.current) setPending(false);+ }+ }}>{t('newChat.chatInput.retryPluginWriteAccess')}</Button>;+}diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/PluginWriteAccessRecovery.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/PluginWriteAccessRecovery.test.tsxnew file mode 100644index 0000000000..8fa92d33bb--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/PluginWriteAccessRecovery.test.tsx@@ -0,0 +1,23 @@+/** @vitest-environment jsdom */+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import { PluginWriteAccessRecovery } from '../PluginWriteAccessRecovery';+vi.mock('react-i18next',()=>({useTranslation:()=>({t:(key:string)=>key})}));+vi.mock('@/lib/toast',()=>({toast:{error:vi.fn()}}));+afterEach(cleanup);+function setup(available=true){+ const read=vi.fn(async()=>({available}));+ const retry=vi.fn(async()=>({granted:true,mode:'auto' as const}));+ Object.defineProperty(window,'electronAPI',{configurable:true,value:{maker:{getPluginWriteAccessRecovery:read,retryPluginWriteAccess:retry}}});+ const granted=vi.fn();render(<PluginWriteAccessRecovery sessionId="task" onGranted={granted}/>);+ return {read,retry,granted};+}+it('does not automatically retry and exposes no action without a refused request',async()=>{+ const f=setup(false);await waitFor(()=>expect(f.read).toHaveBeenCalledWith('task'));+ expect(screen.queryByRole('button')).toBeNull();expect(f.retry).not.toHaveBeenCalled();+});+it('only an explicit click retries and a confirmed result refreshes the task permission',async()=>{+ const f=setup();const button=await screen.findByRole('button');expect(f.retry).not.toHaveBeenCalled();+ fireEvent.click(button);await waitFor(()=>expect(f.granted).toHaveBeenCalledWith('auto'));+ expect(f.retry).toHaveBeenCalledOnce();expect(screen.queryByRole('button')).toBeNull();+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 3583ec8a2b..5e5c63d8b8 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8691,6 +8691,7 @@"openSettings": "Open Settings"},"permissionSwitchFailed": "Permission mode change failed; the previous setting was kept",+ "retryPluginWriteAccess": "Confirm plugin write permission again","fullAccessConfirmation": {"title": "Enable Full access?","description": "Full access disables the workspace sandbox and skips routine approvals. Cindy can then do the following without asking:",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 1af036216c..7f66db4caa 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8689,6 +8689,7 @@"openSettings": "設定を開く"},"permissionSwitchFailed": "権限モードの変更に失敗したため、以前の設定を維持しました",+ "retryPluginWriteAccess": "プラグインの書き込み権限を再確認","fullAccessConfirmation": {"title": "Full access を有効にしますか?","description": "Full access はワークスペースのサンドボックスを無効にし、通常の承認を省略します。Cindy は確認なしで次の操作ができるようになります:",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex cccd9b00f6..27ff59e33c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8689,6 +8689,7 @@"openSettings": "설정 열기"},"permissionSwitchFailed": "권한 모드 변경에 실패해 이전 설정을 유지했습니다",+ "retryPluginWriteAccess": "플러그인 쓰기 권한 다시 확인","fullAccessConfirmation": {"title": "Full access를 활성화할까요?","description": "Full access는 작업 공간 샌드박스를 비활성화하고 일반 승인을 건너뜁니다. Cindy는 확인 없이 다음 작업을 할 수 있습니다:",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 11b5b20d87..5e0bd78816 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8689,6 +8689,7 @@"openSettings": "去设置"},"permissionSwitchFailed": "权限模式切换失败,已保留原设置",+ "retryPluginWriteAccess": "重新确认插件写权限","fullAccessConfirmation": {"title": "开启 Full access?","description": "Full access 会关闭工作区沙箱并跳过常规审批,Cindy 无需询问即可:",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex c539b15f33..7c61143f69 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -8689,6 +8689,7 @@"openSettings": "前往設定"},"permissionSwitchFailed": "權限模式切換失敗,已保留原設定",+ "retryPluginWriteAccess": "重新確認插件寫入權限","fullAccessConfirmation": {"title": "開啟 Full access?","description": "Full access 會關閉工作區沙箱並跳過常規審批,Cindy 無需詢問即可:",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex e644287a9c..d1a2a4da0e 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -6123,6 +6123,8 @@ interface ElectronAPI {// effort/mode 透传 string —— 合法值由 maker capabilities 决定, vite-env 不重复枚举setEffort: (sessionId: string, effort: string) => Promise<void>;setPermissionMode: (sessionId: string, mode: string) => Promise<void>;+ getPluginWriteAccessRecovery: (sessionId: string) => Promise<{available: boolean}>;+ retryPluginWriteAccess: (sessionId: string) => Promise<{granted: boolean; mode?: 'acceptEdits' | 'auto'}>;setFastMode: (sessionId: string, enabled: boolean) => Promise<void>;setThinkingEnabled: (sessionId: string, enabled: boolean) => Promise<void>;/** 计划模式一级开关(与 permissionMode 正交); DB 持久化由调用方另调 sessionService.update({ planModeEnabled }) */diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex 2c6dec5f06..55ba3056c0 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -44,6 +44,10 @@### 主任务协调评测+任务写权限请求在当前宿主进程中按账号代际、安装修订和任务记忆拒绝或失败,插件 reload 和更换请求模式不能恢复自动弹窗。用户可在本机任务权限菜单点击“重新确认插件写权限”,复用原请求模式和原生确认;在途请求不能并发。此专用 IPC 拒绝 device-link,并校验真实顶层窗口、账号与安装修订。已有效授予的权限直接复用,未改变普通权限切换行为或旧 errand。重启宿主后可再次首次询问。++首次协同计划检查落盘 user 消息与任务开始/结束时间;清空或回退对话不会抹除执行事实。目录核验到保存复用普通发送锁,同计划重放仍保持幂等。+`tasks.startTeam({taskId})` 为本插件拥有的普通任务启用 Orca Lead,复用现有协同入口及 Worker 权限确认。插件不能指定 Worker 权限绕过确认。确认返回后、实际启用前再次校验账号、插件授权、任务配置修订。`tasks.getTeam({taskId})` 只投影所属团队的 Worker 身份、实际模型配置、目录、队列和终态;不会将 Lead 一轮完成解释为整个团队完成。协同启动要求任务仍为 active;进入启动流程前和权限确认后的原生启动回调均重新检查,已归档任务不能借此创建或复用团队。不宣称与跨进程归档形成事务。