Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(plugins): reject first write grants after ordinary task execution

Dash5e20be997693
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
index 50144211f4..213668ce19 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
@@ -9,16 +9,20 @@ const branch = source.slice(source.indexOf(" case 'requestWriteAccess': {")
const js = ts.transpileModule(`return async function(pluginId, request) { switch(request.kind) { ${branch} } }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
function fixture() {
let cfg: Record<string, unknown> = { permissionMode: 'plan', model: 'old' };
- const epoch = { client: { tx: vi.fn(async () => ({ updated: true })) } };
+ 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'};
+ const select = vi.fn(() => ({from:(table:unknown)=>({where:()=>({limit:async()=>table===messages ? (history.input ? [{id:'manual-input'}] : []) : [{startedAt:history.startedAt,endedAt:history.endedAt}]})})}));
+ const drain = vi.fn(async()=>{});
+ const epoch = { client: { tx: vi.fn(async () => ({ updated: true })), drizzle: {select} } };
const task = { taskId: 'task', revision: 1, permissionMode: 'plan' };
const service = { get: vi.fn(async () => task), listRuns: vi.fn(async () => ({ items: [] })) };
const live = { isTurnRunning: () => false, getTurnControlSnapshot: () => ({ pendingInteractionCount: 0 }), setPermissionMode: vi.fn(async () => {}) };
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 = { 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 deps = { 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, config: () => cfg, change: (next: Record<string, unknown>) => { cfg = next; } };
+ 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; } };
}
describe('plugin write confirmation interleavings', () => {
it('owns the existing slot across idle checks and releases it on failure', async () => {
@@ -44,3 +48,23 @@ describe('plugin write confirmation interleavings', () => {
expect(f.write).not.toHaveBeenCalled(); expect(f.slots.size).toBe(0);
});
});
+
+describe('first plugin write approval checks actual task history', () => {
+ it.each(['input','startedAt','endedAt'] as const)('rejects a manual UI turn with %s evidence without a plugin receipt', async key=>{
+ const f=fixture();
+ if(key==='input') f.history.input=true; else f.history[key]=1;
+ await expect(f.run()).rejects.toMatchObject({code:'TASK_BUSY'});
+ expect(f.dialog.showMessageBox).not.toHaveBeenCalled();expect(f.live.setPermissionMode).not.toHaveBeenCalled();expect(f.slots.size).toBe(0);
+ });
+ it('rechecks after confirmation if a manual turn completed while the dialog was open',async()=>{
+ const f=fixture();f.dialog.showMessageBox.mockImplementationOnce(async()=>{f.history.input=true;return {response:0};});
+ await expect(f.run()).rejects.toMatchObject({code:'TASK_BUSY'});
+ expect(f.live.setPermissionMode).not.toHaveBeenCalled();expect(f.epoch.client.tx).not.toHaveBeenCalled();
+ });
+ it('drains pending message writes before checking and fails closed on storage failure',async()=>{
+ const f=fixture();f.drain.mockImplementationOnce(async()=>{f.history.input=true;});
+ await expect(f.run()).rejects.toMatchObject({code:'TASK_BUSY'});
+ const g=fixture();g.drain.mockRejectedValueOnce(new Error('storage unavailable'));
+ await expect(g.run()).rejects.toThrow('storage unavailable');expect(g.dialog.showMessageBox).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 00d91dc37a..fdc223ec51 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10279,7 +10279,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (pluginPermissionRequests.size) throw new PluginTaskError('TASK_BUSY', 'A permission request is already open');
const before = JSON.stringify(cfg);
const assertIdle = async () => {
- if (mode === 'acceptEdits' && (await service.listRuns(pluginId, task.taskId)).items.length) throw new PluginTaskError('TASK_BUSY', 'Only an unstarted task can request write access');
+ if (mode === 'acceptEdits') {
+ if ((await service.listRuns(pluginId, task.taskId)).items.length) throw new PluginTaskError('TASK_BUSY', 'Only an unstarted task can request write access');
+ await drainPersistQueue();
+ if (!snapshot || snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ // Ordinary UI turns have no plugin send receipt. Clearing or rewinding
+ // their messages must not make an already-started task new again.
+ const [input] = await snapshot.client.drizzle.select({id: messages.id}).from(messages)
+ .where(and(eq(messages.sessionId, task.taskId), eq(messages.role, 'user'))).limit(1);
+ const [row] = await snapshot.client.drizzle.select({startedAt: sessions.activeTurnStartedAt, endedAt: sessions.lastTurnEndedAt}).from(sessions)
+ .where(eq(sessions.id, task.taskId)).limit(1);
+ if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ if (input || row?.startedAt != null || row?.endedAt != null) throw new PluginTaskError('TASK_BUSY', 'Only an unstarted task can request write access');
+ }
const live = maker.getSession(task.taskId);
if (live?.isTurnRunning() || live?.getTurnControlSnapshot().pendingInteractionCount || inputCoordinator.getQueueControlSnapshot(task.taskId).pendingQueue.length) throw new PluginTaskError('TASK_BUSY', 'Wait for the current turn before changing permission');
};