Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): guard memory access and Plan permission commits
Dash63319e8337ae
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.tsindex 30b60b44bd..b8f7e47304 100644--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts@@ -2865,14 +2865,14 @@ describe('远程 set-* 持久化回流', () => {expect(persist).not.toHaveBeenCalled();});- it('set-permission-mode commits inside the handler without a later duplicate write', async () => {+ it.each([['maker:set-permission-mode','ask'],['maker:set-plan-mode',true]])('%s commits inside the handler without a later duplicate write', async (channel,value) => {const persist = vi.fn();setRemoteSettingsPersist(persist);const response = {};markRemoteSettingPersistedInsideHandler(response);- registry.register('maker:set-permission-mode', () => response);+ registry.register(channel as string, () => response);const result = await runInvoke('ctrl-a', {- channel: 'maker:set-permission-mode', args: ['sess-1', 'ask'],+ channel: channel as string, args: ['sess-1', value],});expect(result).toEqual({ ok: true, result: response });expect(persist).not.toHaveBeenCalled();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.tsindex 400f0b4950..b5f532bf03 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts@@ -16,20 +16,23 @@ 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 planSource = source.slice(source.indexOf(' ipcMain.handle(\n MAKER_INVOKE.SET_PLAN_MODE,'), source.indexOf(' ipcMain.handle(MAKER_INVOKE.EXPORT_SESSION_HTML,'));+const planJs = ts.transpileModule(planSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;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, permissionMode: 'plan' };+ const history = { input: false, startedAt: null as number | null, endedAt: null as number | null, permissionMode: 'plan', planModeEnabled: false };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,permissionMode:history.permissionMode}]})})}));+ 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,planModeEnabled:history.planModeEnabled}]})})}));const drain = vi.fn(async()=>{});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 (mode: string) => {runtimeMode=mode;}) };+ let runtimePlan: boolean | null = false;+ const live = { get stablePlanModeState() { return runtimePlan === null ? null : {enabled:runtimePlan,generation:0}; }, getPlanMode:()=>runtimePlan, setPlanMode:vi.fn(async(enabled:boolean)=>{runtimePlan=enabled;}), 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 })) };@@ -38,17 +41,21 @@ function fixture() {const allDeps = {...deps, pluginWriteAccessGate:gate, pluginWriteAccessIdentity:()=>identity};const run = new Function(...Object.keys(allDeps), js)(...Object.values(allDeps));let setMode!: (event: unknown, sessionId: string, mode: string) => Promise<unknown>;+ let setPlan!: (event:unknown, sessionId:string, enabled:boolean)=>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 planPersist=vi.fn(async(_id:string,patch:{planModeEnabled:boolean})=>{history.planModeEnabled=patch.planModeEnabled;});+ const planDeps={...settingDeps,persistSessionFields:planPersist,ipcMain:{handle:(_name:unknown,fn:typeof setPlan)=>{setPlan=fn;}},MAKER_INVOKE:{SET_PLAN_MODE:'plan'}};+ new Function(...Object.keys(planDeps), planJs)(...Object.values(planDeps));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; } };+ return {setPlan:(enabled:boolean)=>setPlan({},'task',enabled),planPersist,runtimePlan:()=>runtimePlan,nativePlan:(enabled:boolean|null)=>{runtimePlan=enabled;},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})=>{@@ -352,3 +359,91 @@ it('lets a real Session policy lease restore through the send fence while a permexpect(transport.mock.calls).toEqual([['ask'],['bypassPermissions']]);expect(f.history.permissionMode).toBe('bypassPermissions');});+++describe('Plan changes share the complete permission commit',()=>{+ it.each(['local','remote','cold'])('persists Plan through Host for %s and recovers before a successor',async entry=>{+ const f=fixture();if(entry==='remote')f.remote();if(entry==='cold')f.cold();+ f.planPersist.mockRejectedValueOnce(Error('plan db failed'));+ const first=f.setPlan(true).catch(e=>e.message);const next=f.setPlan(false);+ expect(await first).toBe('plan db failed');const result=await next;+ expect(f.history.planModeEnabled).toBe(false);expect(f.planPersist).toHaveBeenCalledTimes(2);+ if(entry!=='cold')expect(f.live.setPlanMode.mock.calls).toEqual([[true],[false],[false]]);+ if(entry==='remote')expect(f.persistedResults.has(result as object)).toBe(true);+ });+ it('restores a partially changed runtime even when its setter rejects',async()=>{+ const f=fixture();f.live.setPlanMode.mockImplementationOnce(async()=>{f.nativePlan(true);throw Error('partial runtime');});+ await expect(f.setPlan(true)).rejects.toThrow('partial runtime');+ expect(f.runtimePlan()).toBe(false);expect(f.planPersist).not.toHaveBeenCalled();+ });+ it('rejects a queued Plan change when its captured account is gone',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 pending=f.setPlan(true).then(value=>value,error=>error);+ f.changeOwner();release();await prior;expect(await pending).toMatchObject({code:'PRECONDITION_FAILED'});expect(f.planPersist).not.toHaveBeenCalled();expect(f.live.setPlanMode).not.toHaveBeenCalled();+ });+ it.each([true,null])('rejects runtime Plan %s even with a stale already-granted DB snapshot',async enabled=>{+ const f=fixture();f.change({permissionMode:'auto'});f.service.get.mockResolvedValue({taskId:'task',revision:1,status:'active',permissionMode:'auto'});f.nativePlan(enabled);+ await expect(f.run('auto')).rejects.toMatchObject({code:'PERMISSION_DENIED'});expect(f.dialog.showMessageBox).not.toHaveBeenCalled();+ });+ it.each(['dialog','lastRead'])('rejects native Plan enabled at %s before its DB mirror',async point=>{+ const f=fixture();if(point==='dialog')f.dialog.showMessageBox.mockImplementationOnce(async()=>{f.nativePlan(true);return {response:0};});+ else f.epoch.client.tx.mockImplementationOnce(async()=>{f.nativePlan(true);return {updated:true};});+ await expect(f.run('auto')).rejects.toMatchObject({code:'PERMISSION_DENIED'});expect(f.write).not.toHaveBeenCalled();+ });+ it('keeps the later manual Plan after a plugin grant and DB commit',async()=>{+ const f=fixture();let release!:()=>void;f.epoch.client.tx.mockImplementationOnce(()=>new Promise(r=>{release=()=>r({updated:true});}));+ const grant=f.run('auto');await vi.waitFor(()=>expect(release).toBeTypeOf('function'));+ const plan=f.setPlan(true);await Promise.resolve();expect(f.live.setPlanMode).not.toHaveBeenCalled();release();await grant;await plan;+ expect(f.history.planModeEnabled).toBe(true);expect(f.runtimePlan()).toBe(true);+ });+});+++describe('native Plan mirrors preserve the current binding and armed value',()=>{+ const emitter=source.slice(source.indexOf(' const emitWiredSessionEvent ='),source.indexOf(' const ownerDb =',source.indexOf(' const emitWiredSessionEvent =')));+ const code=ts.transpileModule(`${emitter}\nreturn emitWiredSessionEvent;`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;+ it.each(['current','stale-value','unknown','account','replacement'])('handles queued native Plan mirror: %s',async scenario=>{+ const f=fixture();let release!:()=>void;+ const before=withSessionPermissionChange('task',()=>new Promise<void>(r=>{release=r;}));+ await vi.waitFor(()=>expect(release).toBeTypeOf('function'));+ const session={...f.live,id:'task'};let bound:unknown=session;+ const deps={session,ownerDb:f.epoch,getCurrentDbClientSnapshot:()=>ownership.current,sessionBindings:{getSession:()=>bound},withSessionPermissionChange,persistSessionFields:f.planPersist,handleSessionEvent:vi.fn(),ownerEventDependencies:{},log:{warn:vi.fn()}};+ const emit=new Function(...Object.keys(deps),code)(...Object.values(deps));+ f.nativePlan(false);expect(emit({type:'plan_mode_changed',data:{enabled:false}})).toBeUndefined();+ // The event callback is synchronous even while a permission change is held.+ expect(f.planPersist).not.toHaveBeenCalled();+ if(scenario==='stale-value')f.nativePlan(true);+ if(scenario==='unknown')f.nativePlan(null);+ if(scenario==='account')f.changeOwner();+ if(scenario==='replacement')bound={};+ release();await before;await withSessionPermissionChange('task',async()=>{});+ if(scenario==='current')expect(f.planPersist).toHaveBeenCalledExactlyOnceWith('task',{planModeEnabled:false});+ else expect(f.planPersist).not.toHaveBeenCalled();+ });+});+++describe('new user input waits outside execution fences',()=>{+ const sendStart=source.indexOf(' sendToAgentAccepted: async (sessionId, message, createOpts, sendOpts) => {');+ const sendText=source.slice(sendStart,source.indexOf(' assertRemoteInputControlBoundary:',sendStart));+ const sendJs=ts.transpileModule(`return {${sendText}}.sendToAgentAccepted;`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;+ const enqueueStart=source.indexOf(' MAKER_INVOKE.INPUT_ENQUEUE,');+ const enqueueText=source.slice(source.indexOf(' const sid = requireSessionId(sessionId);',enqueueStart),source.indexOf(' if (parsed.durableDelivery)',enqueueStart));+ const enqueueJs=ts.transpileModule(`return async function(event,sessionId,item){${enqueueText}};`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;+ it.each(['send','enqueue'].flatMap(entry=>[false,true].map(switchOwner=>({entry,switchOwner}))))('$entry waits for permission and rejects changed owner=$switchOwner',async({entry,switchOwner})=>{+ const f=fixture();let release!:()=>void;+ const prior=withSessionPermissionChange('task',()=>new Promise<void>(r=>{release=r;}));+ await vi.waitFor(()=>expect(release).toBeTypeOf('function'));+ const dispatch=vi.fn(async()=>({}));+ const deps={withSessionPermissionChange,getCurrentDbClientSnapshot:()=>ownership.current,throwIpcError:(code:string,message:string)=>{throw Object.assign(Error(message),{code});},sendToAgentAccepted:dispatch,isDeviceLinkInvoke:()=>false,attachTrustedDesktopSendContext:(_m:unknown,o:unknown)=>o,requireSessionId:(id:string)=>id,assertReviewExternalInputAllowed:async()=>{},assertTrustedAppRendererEvent:()=>{},prepareSharedTaskInput:dispatch,requireQueuedMessage:(x:unknown)=>x};+ const run=new Function(...Object.keys(deps),entry==='send'?sendJs:enqueueJs)(...Object.values(deps));+ const result=(entry==='send'?run('task','hello',{},{}):run({},'task',{})).then((v:unknown)=>v,(e:Error)=>e);+ await Promise.resolve();await Promise.resolve();expect(dispatch).not.toHaveBeenCalled();+ // Completion/continuation can use the normal send fence while input waits.+ await withSendToSessionLock('task',async()=>{});+ if(switchOwner)f.changeOwner();release();await prior;const value=await result;+ if(switchOwner){expect(value).toMatchObject({code:'PRECONDITION_FAILED'});expect(dispatch).not.toHaveBeenCalled();}+ else expect(dispatch).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex a839c2aaf6..2047ac5105 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -4976,6 +4976,19 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// listeners never treat it as turn text; Desktop persist/broadcast still// consumes the localized notice.const emitWiredSessionEvent = (event: AgentEvent) => {+ if (event.type === 'plan_mode_changed') {+ const enabled = (event.data as { enabled?: unknown })?.enabled;+ if (typeof enabled === 'boolean') {+ // Do not block event consumption/turn lease release on this queue.+ void withSessionPermissionChange(session.id, async () => {+ if (!ownerDb || ownerDb !== getCurrentDbClientSnapshot()+ || sessionBindings.getSession(session.id) !== session+ || session.getPlanMode() !== enabled) return;+ await persistSessionFields(session.id, {planModeEnabled: enabled});+ }).catch((error) => log.warn('persist plan_mode_changed failed', {sessionId: session.id, error: String(error)}));+ }+ return;+ }handleSessionEvent(ownerEventDependencies, session, event);};const ownerDb = getCurrentDbClientSnapshot();@@ -10747,6 +10760,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const snapshot = getCurrentDbClientSnapshot();const task = await service.get(pluginId, request.taskId);if (task.status !== 'active') throw new PluginTaskError('TASK_BUSY', 'Archived tasks cannot request write access');+ const assertPlanInactive = () => {+ const live = maker.getSession(task.taskId);+ const plan = live?.stablePlanModeState;+ if (live && (!plan || plan.enabled)) throw new PluginTaskError('PERMISSION_DENIED', 'Plan Mode is active or changing');+ };+ assertPlanInactive();if (task.planModeEnabled) throw new PluginTaskError('PERMISSION_DENIED', 'Exit Plan Mode before requesting write access');const mode = request.mode ?? 'acceptEdits';const cfg = readGhostErrandConfig(pluginId);@@ -10803,6 +10822,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (fresh.revision !== task.revision) throw new PluginTaskError('TASK_BUSY', 'Task changed while awaiting permission');await assertIdle();assertRequestCurrent();+ assertPlanInactive();const live = maker.getSession(task.taskId);let persisted = false;try {@@ -10817,6 +10837,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (updatedTask.planModeEnabled) throw new PluginTaskError('PERMISSION_DENIED', 'Plan Mode changed during permission confirmation');assertRequestCurrent();if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');+ assertPlanInactive();const currentConfig = readGhostErrandConfig(pluginId);if (currentConfig.permissionMode !== cfg.permissionMode) throw new PluginTaskError('PERMISSION_DENIED', 'Permission settings changed');if (mode === 'auto' || clampErrandPermissionMode(currentConfig.permissionMode) === 'plan') writeGhostErrandConfig(pluginId, {...currentConfig, permissionMode: mode});@@ -14367,15 +14388,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},},{- sendToAgentAccepted: (sessionId, message, createOpts, sendOpts) =>- sendToAgentAccepted(+ sendToAgentAccepted: async (sessionId, message, createOpts, sendOpts) => {+ // Only fresh user IPC waits, before taking any send/restart fence.+ // Internal continuations and turn cleanup must remain able to finish.+ const owner = getCurrentDbClientSnapshot();+ await withSessionPermissionChange(sessionId, async () => undefined);+ if (!owner || owner !== getCurrentDbClientSnapshot()) throwIpcError('PRECONDITION_FAILED', 'Account changed before input');+ return sendToAgentAccepted(sessionId,message,createOpts,isDeviceLinkInvoke()? sendOpts: attachTrustedDesktopSendContext(message, sendOpts),- ),+ );+ },assertRemoteInputControlBoundary: (sessionId, opts) =>assertRemoteInputControlBoundary(sessionId, isDeviceLinkInvoke(), opts),},@@ -16346,6 +16373,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await assertReviewExternalInputAllowed(sid);const deviceLinkInvoke = isDeviceLinkInvoke();if (!deviceLinkInvoke) assertTrustedAppRendererEvent(event);+ const inputOwner = getCurrentDbClientSnapshot();+ await withSessionPermissionChange(sid, async () => undefined);+ if (!inputOwner || inputOwner !== getCurrentDbClientSnapshot()) throwIpcError('PRECONDITION_FAILED', 'Account changed before input');const parsed = await prepareSharedTaskInput(sid, requireQueuedMessage(item));if (parsed.durableDelivery) await awaitAgentInputQueueSnapshotPersistence(sid);assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);@@ -19038,13 +19068,43 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (typeof sessionId !== 'string' || typeof enabled !== 'boolean') {throwIpcError('INVALID_PARAMS', 'sessionId + enabled required');}- await assertReviewSettingsUnlocked(sessionId);- const sess = maker.getSession(sessionId);- if (!sess) {- log.debug('set-plan-mode: session not found, no-op', { sessionId });- return;- }- await sess.setPlanMode(enabled);+ const snapshot = getCurrentDbClientSnapshot();+ const remote = isDeviceLinkInvoke();+ const assertOwnerCurrent = () => {+ if (!snapshot || snapshot !== getCurrentDbClientSnapshot())+ throwIpcError('PRECONDITION_FAILED', 'Account changed during Plan update');+ };+ return withSessionPermissionChange(sessionId, async () => {+ assertOwnerCurrent();+ await assertReviewSettingsUnlocked(sessionId);+ assertOwnerCurrent();+ const [row] = await snapshot!.client.drizzle.select({planModeEnabled: sessions.planModeEnabled})+ .from(sessions).where(eq(sessions.id, sessionId)).limit(1);+ assertOwnerCurrent();+ if (!row) throwIpcError('NOT_FOUND', 'session not found');+ const sess = maker.getSession(sessionId);+ try {+ if (sess) await sess.setPlanMode(enabled);+ assertOwnerCurrent();+ if (maker.getSession(sessionId) !== sess) throwIpcError('PRECONDITION_FAILED', 'Session changed during Plan update');+ await persistSessionFields(sessionId, {planModeEnabled: enabled});+ assertOwnerCurrent();+ } catch (error) {+ // A provider may change its runtime before rejecting. Preserve the+ // existing best-effort recovery, inside this same complete commit.+ if (sess && snapshot === getCurrentDbClientSnapshot() && maker.getSession(sessionId) === sess) {+ await sess.setPlanMode(!!row.planModeEnabled).catch((rollbackError) => {+ log.warn('Plan runtime rollback failed', {sessionId, error: String(rollbackError)});+ });+ }+ throw error;+ }+ if (remote) {+ const result = {};+ markRemoteSettingPersistedInsideHandler(result);+ return result;+ }+ });},);diff --git a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.tsindex 825b47f387..a39e9ac181 100644--- a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts+++ b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts@@ -15,7 +15,6 @@ import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-continimport type { AgentMeta } from '../../renderer/lib/ccAgent.types';import { parseAgentInputToolLoopDetails } from '../../shared/agentInputQueue.js';import { noteSubagentObservationTurnStarted } from '../subagentObservationRewindFence.js';-import { persistSessionFields } from '../localDb/ipc/sessions.js';import { createLogger } from '../logger.js';import { t } from '../i18n.js';@@ -258,21 +257,6 @@ export function prepareSessionEvent(if (!isQuietScheduledOutput(event)) void deps.broadcastCodexImageAsToolResult(session.id, event);return;}- if (event.type === 'plan_mode_changed') {- // agent 自行切换计划模式(典型: 计划批准后自动退出)。main 是持久化收口点:- // 复用 persistSessionFields 回写 sessions.plan_mode_enabled 并广播- // sessions:patched, 本机窗口与 device-link 控制端镜像同步收敛。- const data = event.data as { enabled?: unknown };- if (typeof data?.enabled === 'boolean') {- void persistSessionFields(session.id, { planModeEnabled: data.enabled }).catch((err) => {- deps.log.warn('persist plan_mode_changed failed', {- sessionId: session.id,- error: err instanceof Error ? err.message : String(err),- });- });- }- return;- }// turn 结束的 status event (isRunning=false + status='Done') 携带 endSnapshot。// contextTokens / contextWindow 的持久化统一在 main 端做,避免多 window 竞写;// 但不能挡在 EVENT broadcast 前面,否则 final/done 已到 main 后还会被同步 SQLitediff --git a/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.tsindex 9de3dbd640..e048b3740f 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts@@ -237,25 +237,26 @@ it.each(['codex', 'claude-code', 'pi'] as const)('blocks helper discovery and gu});it.each(['lead', 'worker'].flatMap(sessionId => (['codex', 'claude-code', 'pi'] as const).flatMap(agentKind =>- (['cindy_contacts', 'cindy_scheduler', 'cindy_slack'] as const).map(name => ({ sessionId, agentKind, name })))))(+ (['cindy_contacts', 'cindy_scheduler', 'cindy_slack', 'cindy_memory'] as const).map(name => ({ sessionId, agentKind, name })))))('protects account data from $sessionId through $agentKind $name', async ({ sessionId, agentKind, name }) => {const f = fixture();const privateData = [{ id: 'private', displayName: 'Synthetic private contact', prompt: 'Synthetic private schedule' }];const read = vi.fn(async () => privateData);- const manager = vi.fn(() => ({ getStore: () => ({ listContacts: read }) }));+ const manager = vi.fn(() => ({ isEnabled: () => true, getStore: () => ({ listContacts: read, list: async () => (await read()).map(item => ({ filename: 'private.md', frontmatter: { title: item.displayName } })) }) }));const scheduler = vi.fn(() => ({ list: read }));const getBridge = vi.fn(() => ({ availability: () => ({ bound: true, connected: true, serverSupportsTools: true }),callTool: async () => ({ ok: true, result: await read() }) }));const { withAccountDataAccess } = f;const providers = createLiziMcpProviders({ enabled: [name],contacts: { getManager: manager, withAccountDataAccess },+ memory: { getManager: manager, withAccountDataAccess, searchSessions: read },scheduler: { getScheduler: scheduler, withAccountDataAccess },slackHook: { getBridge, withAccountDataAccess },} as unknown as Parameters<typeof createLiziMcpProviders>[0]);const workingDir = mkdtempSync(join(tmpdir(), 'plugin-account-scope-'));let liveId = sessionId;- const ctx: LiziMcpSessionContext = { agentKind, workingDir, sessionId,- ...(agentKind !== 'claude-code' ? { sessionId: undefined, getSessionContext: () => ({ agentKind, workingDir, sessionId: liveId }) } : {}) };+ const ctx: LiziMcpSessionContext = { agentKind, workingDir, memoryScopeKey: 'fixture', sessionId,+ ...(agentKind !== 'claude-code' ? { sessionId: undefined, getSessionContext: () => ({ agentKind, workingDir, memoryScopeKey: 'fixture', sessionId: liveId }) } : {}) };const config = await providers[0]!.toClaudeSdkConfig(ctx);const server = (config as { instance: ReturnType<typeof createXdtHelperMcpServer> }).instance;const client = new Client({ name: 'plugin-account-scope', version: '1' });@@ -263,9 +264,10 @@ it.each(['lead', 'worker'].flatMap(sessionId => (['codex', 'claude-code', 'pi']await Promise.all([client.connect(ct), server.connect(st)]);const call = (spill = false) => client.callTool(name === 'cindy_slack'? { name: 'slack_call_tool', arguments: { name: 'search', ...(spill ? { out_file: 'private.json' } : {}) } }- : { name: 'call_tool', arguments: { name: name === 'cindy_contacts' ? 'contacts_list' : 'schedule_list', args: {} } });+ : { name: 'call_tool', arguments: { name: name === 'cindy_contacts' ? 'contacts_list' : name === 'cindy_memory' ? 'memory_list' : 'schedule_list', args: {} } });const denied = (result: unknown) => {expect(result).toMatchObject({ isError: true });+ expect(JSON.parse((result as {content:Array<{text:string}>}).content[0]!.text)).toMatchObject({ok:false,errorCode:'CAPABILITY_NOT_AVAILABLE'});expect(JSON.stringify(result)).not.toContain('Synthetic private');};try {@@ -274,6 +276,7 @@ it.each(['lead', 'worker'].flatMap(sessionId => (['codex', 'claude-code', 'pi']if (name === 'cindy_slack') denied(await client.callTool({ name: 'slack_status', arguments: {} }));else for (const tool of name === 'cindy_contacts'? ['contacts_get', 'contacts_resolve', 'contacts_search', 'contacts_export_vcf', 'contacts_import_system', 'contacts_export_system', 'contacts_delete', 'contacts_create']+ : name === 'cindy_memory' ? ['memory_read', 'memory_search', 'memory_write', 'memory_delete', 'memory_consolidate', 'memory_review', 'session_search']: ['schedule_get', 'schedule_list_runs', 'schedule_create', 'schedule_update', 'schedule_delete', 'schedule_run_now']) {denied(await client.callTool({ name: 'call_tool', arguments: { name: tool, args: { id: 'private' } } }));}diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex a335d873d0..c7451d2e28 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -368,6 +368,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMclogger: createLogger('mcp/cindy_ssh'),},memory: {+ withAccountDataAccess,getManager: deps.getMakerMemoryManager,beginWrite: (context) => {const saved = botLearningTracker.capture(context?.memoryScopeKey?.startsWith('bot:') ? context.sessionId ?? '' : '');diff --git a/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.ts b/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.tsindex cb4b8483c3..08bd8bb371 100644--- a/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.ts@@ -457,19 +457,17 @@ describe('setPlanMode 乐观时序(勾选后立即发送不丢武装态)', () =>expect(makerChatStore.getSnapshot(SESSION_ID).planModeEnabled).toBe(true);});- it('持久化失败 → 回滚乐观值并通知 runtime 还原', async () => {+ it('Host 提交失败只回滚乐观值,不另写 DB 或发第二次 runtime 回滚', async () => {const sessionService = await import('@/lib/sessionService');- (sessionService.update as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('db down'));const w = globalThis as unknown as {window: { electronAPI: { maker: { setPlanMode: ReturnType<typeof vi.fn> } } };};- w.window.electronAPI.maker.setPlanMode = vi.fn(async () => {});+ w.window.electronAPI.maker.setPlanMode = vi.fn(async () => { throw new Error('db down'); });await expect(makerChatStore.setPlanMode(SESSION_ID, true)).rejects.toThrow('db down');expect(makerChatStore.getSnapshot(SESSION_ID).planModeEnabled).toBe(false);- // 先乐观 true、失败后还原 false 各推送一次。- expect(w.window.electronAPI.maker.setPlanMode).toHaveBeenCalledWith(SESSION_ID, true);- expect(w.window.electronAPI.maker.setPlanMode).toHaveBeenCalledWith(SESSION_ID, false);+ expect(w.window.electronAPI.maker.setPlanMode).toHaveBeenCalledExactlyOnceWith(SESSION_ID, true);+ expect(sessionService.update).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex b283905f2c..ecee3b95d2 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -16623,9 +16623,8 @@ async function setFastMode(* 与 setFastMode 同款双路径:* - 远程会话:控制端纯镜像, 只发运行时隧道 setPlanMode, 被控端持久化后经* sessions:patched 回流收敛; 失败回滚乐观值并 reject。- * - 本机会话:server-first —— sessionService.update({ planModeEnabled }) 落库,- * 再推 maker runtime(session 未 spawn / 已 close 时 no-op, 下次 lazy-create- * 由 createOpts.planMode 兜底)。+ * - 本机会话:同步更新乐观 UI 并发送 IPC;Host 完成 runtime、落库和失败恢复。+ * UI 不再另写数据库或发第二次回滚,以免覆盖后来的用户选择。*/async function setPlanMode(sessionId: string, enabled: boolean): Promise<void> {if (!sessionId) return;@@ -16651,45 +16650,26 @@ async function setPlanMode(sessionId: string, enabled: boolean): Promise<void> {return;}// 乐观先行(bot review P2):store(下一次 createOpts / lazy-create 读)与 maker- // runtime(已 spawn 会话的 send 读 agent 武装态)都必须在任何 await 之前可见,- // 否则「勾选后立即回车」会以未武装状态发出(maker:send 对已存在会话忽略- // createOpts)。setPlanMode IPC 同步 invoke 也保证其先于后续 send IPC 到达 main。+ // 输入快照必须在任何 await 之前可见。同步 invoke 保持与后续发送 IPC 的顺序,+ // Host 的新输入入口在 send fence 外等待已有权限提交,内部续跑不等待。const previous = getOrCreateState(sessionId).planModeEnabled;setState(sessionId, (s) =>s.planModeEnabled === enabled? s: { ...s, planModeEnabled: enabled, planModeRev: s.planModeRev + 1 },);- // 轮 40-w4-t17 HIGH-1:runtime setPlanMode 失败必须 fail-closed —— 旧实现只- // catch 记日志, 继续持久化 DB, UI/DB 显示已开启但 PI runtime 实际未进入- // plan mode(状态分叉, 下一条消息以普通模式执行)。- const runtimePush = window.electronAPI.maker- .setPlanMode(sessionId, enabled)- .catch((err: unknown) => {- // 回滚乐观值, 不持久化, UI 不谎报。- setState(sessionId, (s) =>- s.planModeEnabled === enabled- ? { ...s, planModeEnabled: previous, planModeRev: s.planModeRev + 1 }- : s,- );- log.warn('setPlanMode runtime push failed — plan mode not applied', err);- throw err;- });try {- await runtimePush;- await sessionService.update(sessionId, { planModeEnabled: enabled });+ // Host owns runtime, persistence and recovery as one permission commit.+ await window.electronAPI.maker.setPlanMode(sessionId, enabled);} catch (err) {- // 持久化失败 → 回滚乐观值(store + runtime 尽力), UI 不谎报已开启。setState(sessionId, (s) =>s.planModeEnabled === enabled? { ...s, planModeEnabled: previous, planModeRev: s.planModeRev + 1 }: s,);- void window.electronAPI.maker.setPlanMode(sessionId, previous).catch(() => {});- log.warn('setPlanMode persist failed:', err);+ log.warn('setPlanMode commit failed:', err);throw err;}- await runtimePush;}/**diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex d82a46d3e8..2189b8ca7f 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -15,7 +15,7 @@- 回执独立落库,区分任务、输入执行及原生执行代次;原生终态按 instanceId + generation 结算,不以 idle 或最后一条 assistant 消息猜测完成。- send 回执写入后,进入宿主派发前的检查拒绝可确定未发送,结算为 failed;进入派发后的异常仍为 reconciling,明确拒绝仍为 failed,已有原生进展优先。同 requestKey 只读取旧回执,权限恢复后需新 key 显式提交。若账号、归属或存储条件不再允许结算,调用仍拒绝并保留回执,不绕过权限门补写终态。- 读取限定于本插件创建的任务;返回消息 clientId。list/listRuns 按 (createdAt, id) 排序,现有回执 ID 游标在同插件与目标内解析,不再只按随机 UUID 排序。列表是分页查询,不是增量订阅;刷新应从首页重扫,不能把游标当永久同步水位(同毫秒追加、系统时钟回退或既有回执终态更新均需刷新)。-- 插件持有 create 归属的任务及其 Orca Worker 使用既有 restricted `cindy_helper` 能力面,不提供账号级历史、待发消息或跨任务控制;发现与实际调用共用实时 Host 判据,猜工具名也不放行。另一个原始历史入口 `cindy_memory.session_search` 复用同一判据,在查询前拒绝,不伪装为空结果;读取期间账号变化也不返回结果。按创建回执和 Worker→Team→Lead 关系判断,不按 `source=plugin` 一刀切,也不因团队结束而放开。旧 errand/workspace 无回执时保持原行为;明确 `ownershipRevoked=true` 后,调用方已无正在执行的输入或已接受新的 Host 真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限。发现、调用和 memory 检索复用 Orca 的只读来源判据,首个异步查询前固定当前来源、返回前复核;真人重试保留 Host 文本及稳定来源,插件重试不变真人。Lead 自动回报可沿当前可见输入追溯,但 Worker 的新 Lead 指令阻断对更早真人的回溯。损坏回执、未知来源或查询失败保持拒绝;这不恢复插件归属、旧 requestKey 或插件控制权,也不承诺停止已接受执行。独立 Orca 工具不受影响。这不是通用执行或文件系统隔离。+- 插件持有 create 归属的任务及其 Orca Worker 使用既有 restricted `cindy_helper` 能力面,不提供账号级历史、待发消息或跨任务控制;发现与实际调用共用实时 Host 判据,猜工具名也不放行。整个 `cindy_memory` registry(发现、读取、搜索、写入、删除、合并、复核及 `session_search`)复用账号数据守门,在访问前拒绝,返回前复核账号及输入来源;不伪装为空结果,也不回滚已经接受的写操作。按创建回执和 Worker→Team→Lead 关系判断,不按 `source=plugin` 一刀切,也不因团队结束而放开。旧 errand/workspace 无回执时保持原行为;明确 `ownershipRevoked=true` 后,调用方已无正在执行的输入或已接受新的 Host 真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限。发现、调用和 memory 检索复用 Orca 的只读来源判据,首个异步查询前固定当前来源、返回前复核;真人重试保留 Host 文本及稳定来源,插件重试不变真人。Lead 自动回报可沿当前可见输入追溯,但 Worker 的新 Lead 指令阻断对更早真人的回溯。损坏回执、未知来源或查询失败保持拒绝;这不恢复插件归属、旧 requestKey 或插件控制权,也不承诺停止已接受执行。独立 Orca 工具不受影响。这不是通用执行或文件系统隔离。- 账号级 `cindy_contacts`、`cindy_scheduler`、`cindy_slack` 的发现与实际调用也复用上述实时来源判据。插件持有的任务及 Worker 在读取管理器、调度器或 Slack 绑定前拒绝,猜工具名不能绕过;Codex/Pi 共用服务按每次调用的实际任务判定,Claude 使用当前服务上下文。读取后再核验账号及来源,不返回过期结果;Slack 的既有结果文件路径解析与目录准备后、写入前再核验。普通任务与明确撤权后的真人接管保持原能力;缺少上下文或核验失败拒绝。这不回滚已经接受的外部写操作,不保证中断已派发原生执行或跨工具授权事务,也不改变独立 UI 的调度与通讯录管理。- 取消只撤回自己的排队输入或其原生重试别名;停止前在 Session 锁内再次核对执行身份与插件权限。- 请求跨账号切换后不能继续操作新账号数据库。禁用插件后不能继续发送或停止。@@ -86,3 +86,5 @@ getTeam 的 completedAt 可由宿主落盘的 turnCompleted 终态恢复:仅`getTeam` 增加包含创建预留的 capacity 快照(advisory;准入仍由创建事务裁决)、逐 Worker 的等待确认状态、首条输入/首条执行消息时间、最近轮结束时间,以及 Worker/Lead 分列的 session-total 用量。`host-message-window` 是可观测作答窗口,不是精确模型计算时长。无确切 USD 金额时返回 null,不把订阅估值或其他币种直接当美元。写权限确认前及最终提交前,在原 session/send 锁下恢复持久输入队列;恢复未确认或仍有排队输入时拒绝提权,不把冷任务的空内存队列当作空闲。任务能力批准在收据临时文件准备完成后紧邻原子发布复核账号时效,该受保护替换不跨事件循环;普通收据写入保持原路径。++Plan Mode 的本地及 device-link 切换与插件确认复用同一内存权限提交队列,由 Host 完成 runtime、落库与失败恢复;renderer 不再另写 DB 或发第二次回滚。原生 Plan 事件只异步登记镜像,不阻塞事件消费和 turn 收尾;落库前核对原账号、绑定 Session 及当前 armed 值,忽略迟到的旧事件。插件授权另同步核对现有稳定 Plan 状态(含未知/切换中),不等同于仅看数据库镜像。普通新输入 IPC 在 send/restart fence 外等已有权限提交完成后才进入发送;内部续跑、steering 与独立停止不等待该队列。上述复用不新增 Plan 代次、持久字段或后台重试,也不承诺跨工具事务。diff --git a/packages/lizi-mcps/src/cindy_memoryMcpServer.ts b/packages/lizi-mcps/src/cindy_memoryMcpServer.tsindex 662c46766b..585516006a 100644--- a/packages/lizi-mcps/src/cindy_memoryMcpServer.ts+++ b/packages/lizi-mcps/src/cindy_memoryMcpServer.ts@@ -22,6 +22,7 @@import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';+import { withAccountDataAccess } from './account-data-access.js';import { jsonObjectArg } from './json-object-arg.js';import { MemoryToolRegistry } from './cindy_memoryToolRegistry.js';@@ -56,14 +57,14 @@ const D_CALL_TOOL =const CATEGORY_ENUM = ['read', 'write', 'maintain', 'search'] as const;-function registerListToolsEntry(server: McpServer, registry: MemoryToolRegistry): void {+function registerListToolsEntry(server: McpServer, registry: MemoryToolRegistry, deps: MemoryMcpDeps): void {server.tool('list_tools',D_LIST_TOOLS,{category: z.enum(CATEGORY_ENUM).optional().describe('工具类目, 不传时返回所有类目概览'),},- async ({ category }) => {+ async ({ category }) => withAccountDataAccess(deps.withAccountDataAccess, deps.getSessionContext?.().sessionId, async () => {if (category) {const tools = registry.list(category);return {@@ -99,11 +100,11 @@ function registerListToolsEntry(server: McpServer, registry: MemoryToolRegistry)},],};- },+ }),);}-function registerCallToolEntry(server: McpServer, registry: MemoryToolRegistry): void {+function registerCallToolEntry(server: McpServer, registry: MemoryToolRegistry, deps: MemoryMcpDeps): void {server.tool('call_tool',D_CALL_TOOL,@@ -111,7 +112,7 @@ function registerCallToolEntry(server: McpServer, registry: MemoryToolRegistry):name: z.string().describe('工具名, 从 list_tools 获取 (e.g. memory_write / memory_search)'),args: jsonObjectArg('工具参数 JSON; 不确定 schema 可先传 {} 触发反馈'),},- async ({ name, args }) => registry.call(name, args),+ async ({ name, args }) => withAccountDataAccess(deps.withAccountDataAccess, deps.getSessionContext?.().sessionId, async () => registry.call(name, args)),);}@@ -136,8 +137,8 @@ export function createCindyMemoryMcpServer(deps: MemoryMcpDeps): McpServer {registerMemoryConsolidateTool(registry, deps);registerMemoryReviewTool(registry, deps);- registerListToolsEntry(server, registry);- registerCallToolEntry(server, registry);+ registerListToolsEntry(server, registry, deps);+ registerCallToolEntry(server, registry, deps);return server;}diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.tsindex 90b21cc2e2..abdec686fc 100644--- a/packages/lizi-mcps/src/providers.ts+++ b/packages/lizi-mcps/src/providers.ts@@ -467,6 +467,7 @@ export function createLiziMcpProviders(name: 'cindy_memory',instance: createCindyMemoryMcpServer({getManager: opts.memory!.getManager,+ withAccountDataAccess: opts.memory!.withAccountDataAccess,workdir: ctx.workingDir,getSessionContext: () => resolveLiziMcpSessionContext(ctx),beginWrite: opts.memory!.beginWrite,diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.tsindex 4282c88633..90185421d2 100644--- a/packages/lizi-mcps/src/types.ts+++ b/packages/lizi-mcps/src/types.ts@@ -301,6 +301,7 @@ export interface SchedulerHookScriptService {* vCard 序列化, workspace dep 已声明), 依赖方向仍单向 @cindy/mcps → maker-core。*/export interface MemoryMcpDeps {+ withAccountDataAccess?: import('./account-data-access.js').AccountDataAccess;/** Host captures the source turn before storage; invoked only for a successful write. */beginWrite?: (context: LiziMcpSessionContext | undefined) => ((receipt: { key: string; title: string; action: 'created' | 'updated' }) => void);