Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): serialize complete task permission changes
Dash59af390ce932
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.tsindex a89a87c72b..30b60b44bd 100644--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts@@ -2865,6 +2865,19 @@ describe('远程 set-* 持久化回流', () => {expect(persist).not.toHaveBeenCalled();});+ it('set-permission-mode commits inside the handler without a later duplicate write', async () => {+ const persist = vi.fn();+ setRemoteSettingsPersist(persist);+ const response = {};+ markRemoteSettingPersistedInsideHandler(response);+ registry.register('maker:set-permission-mode', () => response);+ const result = await runInvoke('ctrl-a', {+ channel: 'maker:set-permission-mode', args: ['sess-1', 'ask'],+ });+ expect(result).toEqual({ ok: true, result: response });+ expect(persist).not.toHaveBeenCalled();+ });+it('set-fast-mode → {fastMode}', async () => {const persist = vi.fn();setRemoteSettingsPersist(persist);diff --git a/apps/desktop/src/main/im/shared/permissionModeControl.ts b/apps/desktop/src/main/im/shared/permissionModeControl.tsindex 85b4f8bbfa..eed3760a52 100644--- a/apps/desktop/src/main/im/shared/permissionModeControl.ts+++ b/apps/desktop/src/main/im/shared/permissionModeControl.ts@@ -1,5 +1,7 @@import type { PermissionMode, PermissionModeDescriptor } from '@cindy/maker-core';import { requiresFullAccessConfirmation } from '@cindy/maker-shared/permission-mode';+import { getCurrentDbClientSnapshot } from '../../localDb/client/current.js';+import { withSessionPermissionChange } from '../../maker-ipc/sessionPermissionChange.js';import type { ImUiTextPack } from './types';@@ -46,46 +48,56 @@ export async function changeSessionPermissionMode(args: {return { kind: 'invalid', reason: `Unsupported permission mode: ${args.mode}` };}- const previousMode = await args.readPreviousMode();- if (!previousMode) return { kind: 'invalid', reason: 'Session not found' };-- if (!args.confirmedFullAccess && requiresFullAccessConfirmation(previousMode, args.mode)) {- return {- kind: 'confirmation-required',- mode: args.mode,- label: descriptor.displayName,- };- }+ const snapshot = getCurrentDbClientSnapshot();+ const assertCurrent = () => {+ if (snapshot !== getCurrentDbClientSnapshot()) throw new Error('Account changed during permission update');+ };+ return withSessionPermissionChange(args.sessionId, async () => {+ assertCurrent();+ const previousMode = await args.readPreviousMode();+ assertCurrent();+ if (!previousMode) return { kind: 'invalid', reason: 'Session not found' };- const live = args.getLiveSession();- let runtimeChanged = false;- try {- if (live) {- await live.setPermissionMode(args.mode);- runtimeChanged = true;+ if (!args.confirmedFullAccess && requiresFullAccessConfirmation(previousMode, args.mode)) {+ return {+ kind: 'confirmation-required',+ mode: args.mode,+ label: descriptor.displayName,+ };}- await args.persist(args.mode);- } catch (error) {- if (runtimeChanged && live) {- try {- await live.setPermissionMode(previousMode);- } catch {- // The original failure is more useful to the caller. Rollback remains- // best effort, matching the existing Feishu card behavior.++ const live = args.getLiveSession();+ let runtimeChanged = false;+ try {+ if (live) {+ await live.setPermissionMode(args.mode);+ runtimeChanged = true;}+ assertCurrent();+ await args.persist(args.mode);+ assertCurrent();+ } catch (error) {+ if (runtimeChanged && live && snapshot === getCurrentDbClientSnapshot()) {+ try {+ await live.setPermissionMode(previousMode);+ } catch {+ // The original failure is more useful to the caller. Rollback remains+ // best effort, matching the existing Feishu card behavior.+ }+ }+ return {+ kind: 'failed',+ reason: error instanceof Error ? error.message : String(error),+ };}+return {- kind: 'failed',- reason: error instanceof Error ? error.message : String(error),+ kind: 'changed',+ mode: args.mode,+ label: descriptor.displayName,+ live: Boolean(live),};- }-- return {- kind: 'changed',- mode: args.mode,- label: descriptor.displayName,- live: Boolean(live),- };+ });}export function resolvePermissionMode(diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.tsindex eed926ad2e..400f0b4950 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts@@ -1,34 +1,54 @@+import { Session } from '../../../../../../packages/maker-core/src/session.js';import { readFileSync } from 'node:fs';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';+import { withSessionPermissionChange } from '../sessionPermissionChange.js';+import { changeSessionPermissionMode } from '../../im/shared/permissionModeControl.js';+import type { PermissionMode } from '@cindy/maker-core';+const ownership = vi.hoisted(() => ({ current: null as unknown }));+vi.mock('../../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => ownership.current }));// 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, explicitWriteAccess = false, assertCallerCurrent = () => {}) { switch(request.kind) { ${branch} } }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+const settingSource = source.slice(source.indexOf(' ipcMain.handle(\n MAKER_INVOKE.SET_PERMISSION_MODE,'), source.indexOf(' ipcMain.handle(\n MAKER_INVOKE.SET_PLAN_MODE,'));+const settingJs = ts.transpileModule(settingSource, { 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 history = { input: false, startedAt: null as number | null, endedAt: null as number | null, permissionMode: 'plan' };const messages = {id:'message-id',sessionId:'session-id',role:'role'}, sessions = {id:'session-id',activeTurnStartedAt:'started',lastTurnEndedAt:'ended'};- const select = vi.fn(() => ({from:(table:unknown)=>({where:()=>({limit:async()=>table===messages ? (history.input ? [{id:'manual-input'}] : []) : [{startedAt:history.startedAt,endedAt:history.endedAt}]})})}));+ const select = vi.fn(() => ({from:(table:unknown)=>({where:()=>({limit:async()=>table===messages ? (history.input ? [{id:'manual-input'}] : []) : [{startedAt:history.startedAt,endedAt:history.endedAt,permissionMode:history.permissionMode}]})})}));const drain = vi.fn(async()=>{});- const epoch = { client: { tx: vi.fn(async () => ({ updated: true })), drizzle: {select} } };+ const epoch = { client: { tx: vi.fn(async (_name?: string, args?: {mode: string}) => {if(args) history.permissionMode=args.mode;return { updated: true };}), drizzle: {select} } };+ ownership.current = epoch; let cold = false, runtimeMode = 'plan';const task = { taskId: 'task', revision: 1, status: 'active', permissionMode: 'plan' };const service = { get: vi.fn(async () => task), listRuns: vi.fn(async () => ({ items: [] })), completeOperation: vi.fn(async <T>(operation: () => Promise<T>) => operation()) };- const live = { isTurnRunning: () => false, getTurnControlSnapshot: () => ({ pendingInteractionCount: 0 }), setPermissionMode: vi.fn(async () => {}) };+ const live = { isTurnRunning: () => false, getTurnControlSnapshot: () => ({ pendingInteractionCount: 0 }), setPermissionMode: vi.fn(async (mode: string) => {runtimeMode=mode;}) };const queue = { ensureQueueRestored: vi.fn(async (_id: string) => {}), isQueueRestored: vi.fn((_id: string) => true), getQueueControlSnapshot: vi.fn((_id: string) => ({ pendingQueue: [] as string[] })) };const slots = new Set<string>();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: queue, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampErrandPermissionMode: (x: string) => x, writeGhostErrandConfig: write, broadcastSessionPatched: vi.fn() };+ const deps = { isPluginTaskPermissionAllowed, withSessionPermissionChange, withSessionRestartLock, drainPersistQueue:drain,messages,sessions,eq:()=>true,and:()=>true,service, getCurrentDbClientSnapshot: () => ownership.current, readGhostErrandConfig: () => cfg, pluginPermissionRequests: slots, PluginTaskError, maker: { getSession: () => cold ? null : live }, inputCoordinator: queue, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampErrandPermissionMode: (x: string) => x, writeGhostErrandConfig: write, broadcastSessionPatched: vi.fn() };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), queue, gate, identity: (next: string) => {identity=next;}, service, live, epoch, dialog, slots, write, history, drain, config: () => cfg, change: (next: Record<string, unknown>) => { cfg = next; } };+ let setMode!: (event: unknown, sessionId: string, mode: string) => Promise<unknown>;+ let remote = false;+ const persistedResults = new WeakSet<object>();+ const settingDeps = {...deps, log:{warn:vi.fn()}, ipcMain:{handle:(_name:unknown,fn:typeof setMode)=>{setMode=fn;}}, MAKER_INVOKE:{SET_PERMISSION_MODE:'permission'}, isDeviceLinkInvoke:()=>remote, assertTrustedAppRendererEvent:()=>{}, assertReviewSettingsUnlocked:async()=>{}, isSessionPermissionMode:()=>true, throwIpcError:(code:string,message:string)=>{throw Object.assign(Error(message),{code});}, persistPermissionModeWithoutRuntime:async(_id:string,mode:string)=>(await epoch.client.tx('bots.persistSessionPermission',{mode})).updated, markRemoteSettingPersistedInsideHandler:(result:object)=>persistedResults.add(result)};+ new Function(...Object.keys(settingDeps), settingJs)(...Object.values(settingDeps));+ const setImMode = (mode: PermissionMode) => changeSessionPermissionMode({+ sessionId:'task', mode, modes:[{id:mode,displayName:mode}],+ readPreviousMode:async()=>history.permissionMode as PermissionMode,+ getLiveSession:()=>cold?null:live,+ persist:async next=>{await epoch.client.tx('bots.persistSessionPermission',{mode:next});},+ });+ return {setImMode, setMode:(mode:string)=>setMode({},'task',mode), persistedResults, remote:()=>{remote=true;}, cold:()=>{cold=true;}, runtimeMode:()=>runtimeMode, changeOwner:()=>{ownership.current={};}, run: (mode = 'acceptEdits', explicit = false) => run('plugin', { kind: 'requestWriteAccess', taskId: 'task', mode }, explicit), queue, 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.each(['auto','acceptEdits'].flatMap(mode=>['before','dialog','lastRead'].map(point=>({mode,point}))))('rejects independent Plan Mode at $point for $mode without reporting a grant',async ({point,mode})=>{@@ -229,3 +249,106 @@ it('rejects archival while confirmation is open even if revision is unchanged',aawait expect(f.run()).rejects.toMatchObject({code:'TASK_BUSY'});expect(f.live.setPermissionMode).not.toHaveBeenCalled();expect(f.epoch.client.tx).not.toHaveBeenCalled();expect(f.write).not.toHaveBeenCalled();});++describe('permission commits share the same order', () => {+ it.each(['local','remote','cold','im','im-cold'].flatMap(entry=>['runtime','database','lastRead'].filter(point=>!entry.includes('cold')||point!=='runtime').map(point=>({entry,point}))))('keeps a later Ask after plugin grant/rollback: $entry $point',async({entry,point})=>{+ const f=fixture();if(entry==='remote')f.remote();if(entry.includes('cold'))f.cold();+ let release!:()=>void,entered!:()=>void;+ const barrier=new Promise<void>(r=>{release=r;}), started=new Promise<void>(r=>{entered=r;});+ const pause=async()=>{entered();await barrier;};+ if(point==='runtime')f.live.setPermissionMode.mockImplementationOnce(pause);+ if(point==='database')f.epoch.client.tx.mockImplementationOnce(async(_name,args)=>{await pause();f.history.permissionMode=args!.mode;return {updated:true};});+ if(point==='lastRead')f.service.get.mockImplementationOnce(async()=>({taskId:'task',revision:1,status:'active',permissionMode:'plan'}))+ .mockImplementationOnce(async()=>({taskId:'task',revision:1,status:'active',permissionMode:'plan'}))+ .mockImplementationOnce(async()=>{await pause();throw Error('owner revoked');});+ const grant=f.run('auto').then(()=> 'granted',(e: Error)=>e.message);+ await started;+ const change=entry.startsWith('im')?f.setImMode('ask'):f.setMode('ask');+ // Let the ordinary handler reach its old runtime-only boundary before the+ // delayed plugin write, or queue behind the complete grant after the fix.+ await Promise.resolve();await Promise.resolve();+ release();await grant;const result=await change;+ expect(f.history.permissionMode).toBe('ask');+ if(!entry.includes('cold'))expect(f.runtimeMode()).toBe('ask');+ if(entry==='remote')expect(f.persistedResults.has(result as object)).toBe(true);+ });++ it('does not block a user downgrade while the plugin dialog is open',async()=>{+ const f=fixture();let answer!:()=>void;+ f.dialog.showMessageBox.mockImplementationOnce(()=>new Promise(r=>{answer=()=>r({response:1});}));+ const grant=f.run('auto');await vi.waitFor(()=>expect(answer).toBeTypeOf('function'));+ await f.setMode('ask');expect(f.history.permissionMode).toBe('ask');+ answer();await grant;+ });++ it('rejects a queued permission change after the account changes',async()=>{+ const f=fixture();let release!:()=>void;+ const prior=withSessionPermissionChange('task',()=>new Promise<void>(r=>{release=r;}));+ await vi.waitFor(()=>expect(release).toBeTypeOf('function'));+ const next=f.setMode('ask');const rejected=expect(next).rejects.toMatchObject({code:'PRECONDITION_FAILED'});+ f.changeOwner();release();await prior;await rejected;+ expect(f.live.setPermissionMode).not.toHaveBeenCalled();expect(f.epoch.client.tx).not.toHaveBeenCalled();+ });+});++it.each(['local','remote','cold','im','im-cold'])('recovers from a failed %s commit before accepting the next change',async entry=>{+ const f=fixture();if(entry==='remote')f.remote();if(entry.includes('cold'))f.cold();+ f.epoch.client.tx.mockRejectedValueOnce(Error('db failed'));+ const change=(mode:PermissionMode)=>entry.startsWith('im')?f.setImMode(mode):f.setMode(mode);+ const first=change('auto').catch(e=>e.message);+ const later=change('ask');+ if(entry.startsWith('im'))expect(await first).toMatchObject({kind:'failed'});else expect(await first).toBe('db failed');+ await later;+ expect(f.history.permissionMode).toBe('ask');+ if(!entry.includes('cold')){+ expect(f.live.setPermissionMode.mock.calls).toEqual([['auto'],['plan'],['ask']]);+ expect(f.runtimeMode()).toBe('ask');+ }+});+it.each(['local','remote','cold','im','im-cold'])('preserves repeated/ABA choices through %s',async entry=>{+ const f=fixture();if(entry==='remote')f.remote();if(entry.includes('cold'))f.cold();+ const change=(mode:PermissionMode)=>entry.startsWith('im')?f.setImMode(mode):f.setMode(mode);+ await Promise.all([change('ask'),change('auto'),change('ask'),change('ask')]);+ expect(f.epoch.client.tx.mock.calls.map(call=>call[1]?.mode)).toEqual(['ask','auto','ask','ask']);+ expect(f.history.permissionMode).toBe('ask');+ if(!entry.includes('cold'))expect(f.runtimeMode()).toBe('ask');+});+it.each(['queued','runtime','database'])('rejects IM ownership changes during %s without touching the new account',async point=>{+ const f=fixture();let release!:()=>void;+ let prior:Promise<void>|undefined;+ if(point==='queued'){+ prior=withSessionPermissionChange('task',()=>new Promise<void>(r=>{release=r;}));+ await vi.waitFor(()=>expect(release).toBeTypeOf('function'));+ }+ if(point==='runtime')f.live.setPermissionMode.mockImplementationOnce(async()=>{f.changeOwner();});+ if(point==='database')f.epoch.client.tx.mockImplementationOnce(async()=>{f.changeOwner();return {updated:true};});+ const next=f.setImMode('ask').catch(e=>({kind:'failed',reason:e.message}));+ if(point==='queued'){f.changeOwner();release();await prior;}+ expect(await next).toMatchObject({kind:'failed',reason:'Account changed during permission update'});+ expect(f.live.setPermissionMode).toHaveBeenCalledTimes(point==='queued'?0:1);+ expect(f.epoch.client.tx).toHaveBeenCalledTimes(point==='database'?1:0);+});++it('lets a real Session policy lease restore through the send fence while a permission commit waits',async()=>{+ const f=fixture(), transport=vi.fn(async()=>{});+ const logger={trace(){},debug(){},info(){},warn(){},error(){},fatal(){},child(){return logger;}};+ const session=new Session({id:'task',agentKind:'codex',workDir:'/fixture',permissionMode:'ask',turnStallMs:0,+ handle:{setPermissionMode:transport,setInteractionResolver(){},close:async()=>{}} as never,+ capabilities:{permissionModes:[{id:'ask'},{id:'bypassPermissions'}],setPermissionModeMidSession:{supported:true},+ turnPermissionPolicy:{unsupportedPermissionModes:['bypassPermissions']}} as never,logger});+ const releaseLease=session.acquireTurnLease();+ f.live.setPermissionMode.mockImplementation(mode=>session.setPermissionMode(mode as PermissionMode));+ let started!:()=>void;const entered=new Promise<void>(r=>{started=r;});+ f.live.setPermissionMode.mockImplementationOnce(mode=>{started();return session.setPermissionMode(mode as PermissionMode);});+ const change=f.setMode('bypassPermissions');+ try{+ await entered;+ expect(transport).not.toHaveBeenCalled();+ // The continuation's existing send fence and Host-owned restore stay free.+ await withSendToSessionLock('task',()=>session.setPermissionModeTracked('ask'));+ expect(transport).toHaveBeenCalledExactlyOnceWith('ask');+ expect(f.epoch.client.tx).not.toHaveBeenCalled();+ }finally{releaseLease();await change;await session.close();}+ expect(transport.mock.calls).toEqual([['ask'],['bypassPermissions']]);+ expect(f.history.permissionMode).toBe('bypassPermissions');+});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 489b571ad3..a839c2aaf6 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -80,6 +80,7 @@ import type {InteractionRequest,MainOwnedSendContext,Maker,+ PermissionMode,SendOrigin,Session,SessionSendOptions,@@ -488,6 +489,7 @@ import { ensureBotGroupLaneSession } from '../localDb/ipc/bots.js';import { restartBotRuntime } from './botRuntimeRestart.js';import { registerBotLifecycleHandlers } from './botLifecycleService.js';import { isSessionPermissionMode, persistPermissionModeWithoutRuntime } from './sessionPermissionPersistence.js';+import { withSessionPermissionChange } from './sessionPermissionChange.js';import { updateBotRoutineLifecycle } from '../routines/service.js';import {createBotCompactRuntimeRefreshCoordinator,@@ -10790,8 +10792,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)buttons: [t('pluginTaskWriteAccess.allow'), t('pluginTaskWriteAccess.cancel')], defaultId: 1, cancelId: 1,});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 () => {+ // Reserve permission order before the lifecycle/restart fence. Ordinary+ // permission writers never hold that fence while awaiting this queue.+ return await withSessionPermissionChange(task.taskId, () => 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);@@ -10824,7 +10827,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (persisted) await snapshot!.client.tx('bots.persistSessionPermission', {sessionId: task.taskId, mode: task.permissionMode});throw error;}- }));+ })));});} finally { pluginPermissionRequests.delete(pluginId); }}@@ -18975,21 +18978,53 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (typeof sessionId !== 'string' || typeof mode !== 'string') {throwIpcError('INVALID_PARAMS', 'sessionId + mode required');}- await assertReviewSettingsUnlocked(sessionId);if (!isSessionPermissionMode(mode)) {throwIpcError('INVALID_PARAMS', 'invalid permission mode');}- const sess = maker.getSession(sessionId);- if (!sess) {- const persisted = await persistPermissionModeWithoutRuntime(sessionId, mode);- if (!persisted) throwIpcError('NOT_FOUND', 'session not found');+ const snapshot = getCurrentDbClientSnapshot();+ const remote = isDeviceLinkInvoke();+ const assertOwnerCurrent = () => {+ if (!snapshot || snapshot !== getCurrentDbClientSnapshot()) {+ throwIpcError('PRECONDITION_FAILED', 'Account changed during permission update');+ }+ };+ return withSessionPermissionChange(sessionId, async () => {+ assertOwnerCurrent();+ await assertReviewSettingsUnlocked(sessionId);+ assertOwnerCurrent();+ const [row] = await snapshot!.client.drizzle.select({permissionMode: sessions.permissionMode})+ .from(sessions).where(eq(sessions.id, sessionId)).limit(1);+ assertOwnerCurrent();+ if (!row) throwIpcError('NOT_FOUND', 'session not found');+ const sess = maker.getSession(sessionId);+ let runtimeChanged = false;+ try {+ if (sess) {+ await sess.setPermissionMode(mode as PermissionMode);+ runtimeChanged = true;+ }+ assertOwnerCurrent();+ const saved = await snapshot!.client.tx('bots.persistSessionPermission', {sessionId, mode});+ if (!saved.updated) throwIpcError('NOT_FOUND', 'session not found');+ assertOwnerCurrent();+ } catch (error) {+ // Keep recovery inside the same permission operation so it cannot+ // overwrite a later user choice. Never recover into a new account.+ if (runtimeChanged && sess && snapshot === getCurrentDbClientSnapshot()) {+ await sess.setPermissionMode(row.permissionMode as PermissionMode).catch((rollbackError) => {+ log.warn('permission runtime rollback failed', {sessionId, error: String(rollbackError)});+ });+ }+ throw error;+ }broadcastSessionPatched(sessionId, { permissionMode: mode });+ if (remote) {+ const result = {};+ markRemoteSettingPersistedInsideHandler(result);+ return result;+ }return true;- }- await sess.setPermissionMode(- mode as 'ask' | 'default' | 'acceptEdits' | 'plan' | 'auto' | 'bypassPermissions',- );- return true;+ });},);diff --git a/apps/desktop/src/main/maker-ipc/sessionPermissionChange.ts b/apps/desktop/src/main/maker-ipc/sessionPermissionChange.tsnew file mode 100644index 0000000000..cf7070b602--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/sessionPermissionChange.ts@@ -0,0 +1,20 @@+/**+ * Orders complete user/plugin permission commits, including persistence and+ * rollback. This is separate from the send/restart fence: a runtime permission+ * change can wait for a running turn's policy lease to finish. That turn must+ * remain free to continue and restore its temporary policy.+ */+const permissionChanges = new Map<string, Promise<void>>();++export function withSessionPermissionChange<T>(+ sessionId: string,+ change: () => Promise<T>,+): Promise<T> {+ const previous = permissionChanges.get(sessionId) ?? Promise.resolve();+ const operation = previous.then(change);+ const settled = operation.then(() => undefined, () => undefined);+ permissionChanges.set(sessionId, settled);+ return operation.finally(() => {+ if (permissionChanges.get(sessionId) === settled) permissionChanges.delete(sessionId);+ });+}diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex 110c78f872..d67739f81b 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -1021,8 +1021,8 @@ describe('远程交互接线不变式', () => {'await sessionService.update(sessionId, { permissionMode: newMode });',);expect(runtimeSet).toBeGreaterThan(-1);- expect(persistSet).toBeGreaterThan(runtimeSet);- expect(src).toContain(+ expect(persistSet).toBe(-1);+ expect(src).not.toContain('await window.electronAPI.maker.setPermissionMode(sessionId, previousMode);',);expect(src).toContain('requiresFullAccessConfirmation(previousMode, newMode)');diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorXhighSSoT.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorXhighSSoT.test.tsindex cbc6b7c0bf..0804f5f58e 100644--- a/apps/desktop/src/renderer/__tests__/modelSelectorXhighSSoT.test.ts+++ b/apps/desktop/src/renderer/__tests__/modelSelectorXhighSSoT.test.ts@@ -68,7 +68,7 @@ function deriveActive(p: ChatInputDerivedProps): ChatInputDerived {}// ----------------------------------------------------------------------------// handler 契约镜像(ChatInput.tsx 的三个 handleXxxChange,2026-07-17 本地化后形态)+// handler 契约镜像(ChatInput.tsx 的 model / effort handler,2026-07-17 本地化后形态)// ---------------------------------------------------------------------------interface HandlerDeps {sessionId?: string;@@ -76,11 +76,8 @@ interface HandlerDeps {sessionUpdate: (id: string, patch: Record<string, unknown>) => Promise<void>;ipcSetEffort?: (id: string, eff: Effort) => Promise<void>;ipcSetModel?: (id: string, model: string) => Promise<void>;- ipcUpdatePerm?: (id: string, mode: PermissionMode) => Promise<void>;- currentPermissionMode?: PermissionMode;onModelDidChange?: (id: string) => void;onEffortDidChange?: (eff: Effort, sourceSessionId?: string) => void;- onPermissionModeDidChange?: (mode: PermissionMode) => void;}async function handleEffortChange(deps: HandlerDeps, newEffort: Effort): Promise<void> {@@ -100,26 +97,6 @@ async function handleEffortChange(deps: HandlerDeps, newEffort: Effort): Promise}}-async function handlePermissionModeChange(- deps: HandlerDeps,- newMode: PermissionMode,-): Promise<void> {- try {- if (deps.sessionId) {- await deps.ipcUpdatePerm?.(deps.sessionId, newMode);- try {- await deps.sessionUpdate(deps.sessionId, { permissionMode: newMode });- } catch (error) {- await deps.ipcUpdatePerm?.(deps.sessionId, deps.currentPermissionMode ?? 'ask');- throw error;- }- }- deps.onPermissionModeDidChange?.(newMode);- } catch (err) {- void err;- }-}-async function handleModelChange(deps: HandlerDeps,newModelId: string,@@ -247,68 +224,6 @@ describe('handleEffortChange: 上抛 onEffortDidChange 给父组件同步 SSoT',});});-describe('handlePermissionModeChange: 上抛 onPermissionModeDidChange', () => {- it('成功路径:上抛新 mode', async () => {- const sessionUpdate = vi.fn().mockResolvedValue(undefined);- const ipcUpdatePerm = vi.fn().mockResolvedValue(undefined);- const onPermissionModeDidChange = vi.fn();- await handlePermissionModeChange(- { sessionId: 'sess-1', sessionUpdate, ipcUpdatePerm, onPermissionModeDidChange },- 'bypassPermissions',- );- expect(sessionUpdate).toHaveBeenCalledWith('sess-1', { permissionMode: 'bypassPermissions' });- expect(ipcUpdatePerm).toHaveBeenCalledWith('sess-1', 'bypassPermissions');- expect(ipcUpdatePerm.mock.invocationCallOrder[0]).toBeLessThan(- sessionUpdate.mock.invocationCallOrder[0],- );- expect(onPermissionModeDidChange).toHaveBeenCalledWith('bypassPermissions');- });-- it('失败路径:sessionUpdate 抛错 → onPermissionModeDidChange 不调用', async () => {- const onPermissionModeDidChange = vi.fn();- const ipcUpdatePerm = vi.fn().mockResolvedValue(undefined);- await handlePermissionModeChange(- {- sessionId: 'sess-1',- sessionUpdate: vi.fn().mockRejectedValue(new Error('boom')),- ipcUpdatePerm,- currentPermissionMode: 'ask',- onPermissionModeDidChange,- },- 'bypassPermissions',- );- expect(ipcUpdatePerm.mock.calls).toEqual([- ['sess-1', 'bypassPermissions'],- ['sess-1', 'ask'],- ]);- expect(onPermissionModeDidChange).not.toHaveBeenCalled();- });-- it('permissionMode 都能上抛(确认对称化覆盖完整)', async () => {- const modes: PermissionMode[] = [- 'ask',- 'auto',- 'default',- 'acceptEdits',- 'bypassPermissions',- 'plan',- ];- for (const mode of modes) {- const onPermissionModeDidChange = vi.fn();- await handlePermissionModeChange(- {- sessionId: 'sess-x',- sessionUpdate: vi.fn().mockResolvedValue(undefined),- ipcUpdatePerm: vi.fn().mockResolvedValue(undefined),- onPermissionModeDidChange,- },- mode,- );- expect(onPermissionModeDidChange).toHaveBeenCalledWith(mode);- }- });-});-describe('handleModelChange: 同时上抛 onModelDidChange + onEffortDidChange', () => {it('跨模型回归:Opus → Sonnet effort 自动降级,两个 callback 都触发', async () => {const onModelDidChange = vi.fn();diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex a0f1ab585c..c9a15a937f 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -8224,19 +8224,8 @@ export function ChatInput({// 控制端纯镜像:运行时隧道 setPermissionMode,被控端持久化后广播回流更新分片。await makerApiFor(sessionId).setPermissionMode(sessionId, newMode);} else {- // runtime-first:运行时成功后才持久化,避免 UI/DB 先显示已切换而实际 agent 仍是旧档。+ // Host 串行完成运行时、持久化和失败恢复,界面只等待最终结果。await window.electronAPI.maker.setPermissionMode(sessionId, newMode);- try {- await sessionService.update(sessionId, { permissionMode: newMode });- } catch (persistError) {- // DB 写入失败时尽力恢复运行时,保持用户看到的旧设置与实际行为一致。- try {- await window.electronAPI.maker.setPermissionMode(sessionId, previousMode);- } catch (rollbackError) {- log.warn('permission runtime rollback failed:', rollbackError);- }- throw persistError;- }}}// SSoT: notify parent so it refreshes `session.permissionMode` → props update.diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botPermissionSwitch.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botPermissionSwitch.test.tsindex 58dee2e586..b4dad208d7 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botPermissionSwitch.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botPermissionSwitch.test.ts@@ -42,7 +42,7 @@ function fixture() {}describe('companion canonical task uses the standard live permission switch', () => {- it('applies ask to the running task before saving or reporting success', async () => {+ it('waits for the Host commit before reporting success without a second DB write', async () => {const f = fixture();let release!: () => void;f.runtime.mockImplementationOnce(() => new Promise<void>((resolve) => { release = resolve; }));@@ -52,7 +52,7 @@ describe('companion canonical task uses the standard live permission switch', ()expect(f.changed).not.toHaveBeenCalled();release();await pending;- expect(f.persist).toHaveBeenCalledWith('bot-canonical', { permissionMode: 'ask' });+ expect(f.persist).not.toHaveBeenCalled();expect(f.changed).toHaveBeenCalledWith('ask');});@@ -65,16 +65,26 @@ describe('companion canonical task uses the standard live permission switch', ()expect(f.error).toHaveBeenCalled();});- it('restores the running task when persistence fails', async () => {+ it('does not send a stale rollback after the Host rejects persistence', async () => {const f = fixture();- f.persist.mockRejectedValueOnce(new Error('database failed'));+ f.runtime.mockRejectedValueOnce(new Error('database failed'));await f.change('ask');expect(f.runtime.mock.calls).toEqual([- ['bot-canonical', 'ask'], ['bot-canonical', 'bypassPermissions'],+ ['bot-canonical', 'ask'],]);expect(f.changed).not.toHaveBeenCalled();});+ it.each(['ask', 'auto', 'default', 'acceptEdits', 'bypassPermissions', 'plan'])(+ 'reports %s only after the actual shared callback completes', async (mode) => {+ const f = fixture();+ await f.change(mode);+ expect(f.runtime).toHaveBeenCalledExactlyOnceWith('bot-canonical', mode);+ expect(f.persist).not.toHaveBeenCalled();+ expect(f.changed).toHaveBeenCalledWith(mode);+ },+ );+it('requires explicit confirmation before enabling full access', async () => {const f = fixture();f.confirm.mockResolvedValueOnce(false);diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex 7b77bdebaa..d82a46d3e8 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -61,6 +61,8 @@ Worker 创建后至首条输入真正接受,继续核对实际解析的目录任务写权限请求在当前宿主进程中按账号代际、安装修订和任务记忆拒绝或失败,插件 reload 和更换请求模式不能恢复自动弹窗。用户可在本机任务权限菜单点击“重新确认插件写权限”,复用原请求模式和原生确认;在途请求不能并发。此专用 IPC 拒绝 device-link,并校验真实顶层窗口、账号与安装修订。已有效授予的权限直接复用,未改变普通权限切换行为或旧 errand。重启宿主后可再次首次询问。+插件授权确认后的提交、本地/远程任务权限切换及 IM 权限命令,共用按任务排列的内存提交队列,覆盖运行态变更、数据库保存和失败回滚;较早操作不能在较晚用户选择完成后再回滚覆盖它。确认弹窗在队列外。普通权限切换不占发送/重启锁,原生群轮次的临时权限恢复和续跑仍可完成;插件提交仍保留原来的空闲检查与发送保护。界面与远程转发不再追加第二次权限保存。等待后及异步边界核对原账号实例,失败不延迟重试,不承诺跨账号补偿或跨重启事务。+首次协同计划检查落盘 user 消息与任务开始/结束时间;清空或回退对话不会抹除执行事实。目录核验到保存复用普通发送锁,同计划重放仍保持幂等。`tasks.startTeam({taskId})` 为本插件拥有的普通任务启用 Orca Lead,复用现有协同入口及 Worker 权限确认。插件不能指定 Worker 权限绕过确认。确认返回后检查原修订;团队查询、创建和 Lead 激活后复用同一准入回调,核对原账号、插件归属/批准、当前 Auto/Plan、任务路由与目录以及插件配置目录。正常成为 Lead 会改变包含角色的修订,原生阶段改比这些准入事实,不把本次角色变化误判为用户变更。`tasks.getTeam({taskId})` 只投影所属团队的 Worker 身份、实际模型配置、目录、队列和终态;不会将 Lead 一轮完成解释为整个团队完成。diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex f7701abf4b..49afb381cb 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -148,6 +148,7 @@ Hook 与本地 IM 共享消息级来源及上下文快照结构。本地所有| 差异 | 官方 | 个人 | 裁决与理由 ||---|---|---|---|| 桌面设置入口的区域与账号可见性 | 中国大陆版与国际版的云账号均显示官方 Telegram 入口;本地模式不显示需要 Cindy 账号的官方分栏 | 中国大陆版与国际版的个人、组织及本地模式均显示个人 Telegram 入口 | 2026-09-29 按 Dash 的跨版本入口一致要求,`ImBotSection.tsx` 与 `imBotVisibility.ts` 不再按区域或个人账号隐藏两侧入口;设置搜索由 `ImBotSection.settings-search.ts` 同步。两侧仍是独立机器人,官方入口需要云账号,个人入口由用户自配凭证;这项架构差异不应再造成中国大陆版缺入口。 |+| 已有任务的权限切换提交 | 沿现有官方入口,不改服务端权限流程 | 个人 IM 的 `/permission` 与卡片选择共用桌面本地/远程设置和插件授权的任务内提交顺序,包含运行态、保存及失败回滚 | 2026-10-01 Dash 批准:避免较早插件授权或回滚覆盖较晚的用户 Ask。确认 UI 在队列外,群轮次临时权限恢复与续跑不等待此队列;不统一两套 bot 的权限策略,也不新增持久化或后台重试。 || 群轮次权限档 | 完全按用户配的走 | Auto 对渠道策略命中的动作先交 AI 三态审阅;Ask 保留逐次确认;「完全访问」只让 owner 触发的轮次按该档直接执行,非 owner 的群消息继续保留逐轮策略并 fail-closed | Chris 2026-09-04 实踩裁决:个人 bot 的群任务已经明确设成 Pi + Grok + Full access,Cindy 侧能继续对话,Telegram 却因额外挂的逐轮策略与 Full access 互斥而在模型启动前拒绝每条消息。**owner 明确选择的完全访问必须正常执行,但不能把这份授权扩给同群其他成员**;个人侧在 `bypassPermissions` 下仅对 owner 触发的 policy 通过 `turnPolicyOptionalForMode` 取缔逐轮策略,非 owner 的授权边界与群历史 lane 隔离照常保留;scheduler 的创建、修改、前置脚本安装、恢复和立即运行同样进入该逐轮策略,防止可信 MCP 绕过群轮次权限;Auto 的风险判定交 AI,只有 ask 或服务不可用才转 owner 确认。官方侧继续完全按用户配置,不改服务端行为。见 `hook-control/session-runner.ts`、`im/telegram/adapter.ts`、`im/shared/channelToolPolicy.ts` 与 `im/shared/turnRunner.ts` || 私聊过程态的载体 | 默认真实进度消息;开启 `TELEGRAM_DM_DRAFT_ENABLED` 时使用 Telegram **草稿**(`sendDraft`),终稿一发草稿自然消失 | 真实消息,原地 `editMessageText` 覆盖 | 草稿只有官方路径拿得到。个人栈**不是零推送**:惰性占位让「没有真实内容就不建消息」,但**第一帧真实内容那次 `sendMessage` 会推送**,之后的编辑才不推送。`presentationCapabilities.ts` 的 `progressSilent: true` 说的是「过程帧不额外推送」,不是「整轮零推送」 || `/status` | 有 | 无 | 官方 bot 经服务端中继,链路可断,所以有「关联状态」可看;个人 bot 由桌面直连 Bot API,没有等价概念。见注册表 `parityNote` |