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。

修复插件任务完整排空及权限提交互斥

Dasha8fb1c001bf8
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
index 0745f25fe0..f598bf2fa5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
@@ -345,3 +345,35 @@ it('drains terminal receipt writes before the owner database closes', async () =
f.switchOwner();
expect(JSON.parse(f.rows.get(run.runId)!.payload)).toMatchObject({status: 'completed', outputMessageId: 'answer'});
});
+
+it.each(['send', 'cancel'] as const)('drain waits for the full %s operation including native callbacks', async kind => {
+ const f = fixture(); const task = await f.create();
+ const old = kind === 'cancel' ? await f.send() : null;
+ let release!: () => void;
+ const barrier = new Promise<void>(resolve => { release = resolve; });
+ let entered!: () => void; const started = new Promise<void>(resolve => { entered = resolve; });
+ f.deps.dispatch = async (_p, taskId, inputMessageId) => {
+ entered(); await barrier;
+ await f.service.accept(taskId, {clientId: inputMessageId}, f.execution);
+ return {ok: false};
+ };
+ f.deps.cancel = async () => { entered(); await barrier; return 'cancelled'; };
+ const operation = kind === 'send'
+ ? f.service.send('p', {taskId:task.taskId, requestKey:'new', expectedRevision:task.revision, text:'hello'})
+ : f.service.cancel('p', old!.runId);
+ await started;
+ let drained = false; const drain = f.service.drain().then(() => { drained = true; });
+ await new Promise(resolve => setTimeout(resolve, 0)); expect(drained).toBe(false);
+ release(); const [run] = await Promise.all([operation, drain]);
+ f.switchOwner();
+ expect(JSON.parse(f.rows.get(run.runId)!.payload).status).toBe(kind === 'send' ? 'running' : 'cancelled');
+});
+it('a rejected operation does not poison subsequent drain', async () => {
+ const f = fixture(), run = await f.send();
+ f.deps.cancel = async () => { throw new Error('native stop failed'); };
+ await expect(f.service.cancel('p', run.runId)).rejects.toThrow('native stop failed');
+ await f.service.drain();
+ f.deps.cancel = async () => 'cancelled';
+ await expect(f.service.cancel('p', run.runId)).resolves.toMatchObject({status:'cancelled'});
+ await f.service.drain();
+});
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 213668ce19..debdff699c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts
@@ -1,6 +1,7 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it, vi } from 'vitest';
import ts from 'typescript';
+import { withSessionRestartLock, withSendToSessionLock, sendToSessionLocks } from '../sendToSessionLock.js';
import { PluginTaskError } from '../pluginTaskService.js';
// Execute the real switch branch with controlled Host boundaries.
@@ -20,7 +21,7 @@ function fixture() {
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 = { 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 deps = { 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; } };
}
@@ -68,3 +69,31 @@ describe('first plugin write approval checks actual task history', () => {
await expect(g.run()).rejects.toThrow('storage unavailable');expect(g.dialog.showMessageBox).not.toHaveBeenCalled();
});
});
+
+ it('rechecks under the shared lock after an earlier sender completes', async () => {
+ const f = fixture(); let release!: () => void;
+ const barrier = new Promise<void>(resolve => { release = resolve; });
+ let entered!: () => void; const started = new Promise<void>(resolve => { entered = resolve; });
+ let sender: Promise<void>;
+ f.dialog.showMessageBox.mockImplementationOnce(async () => {
+ sender = withSendToSessionLock('task', async () => { entered(); await barrier; f.history.endedAt = 1; });
+ await started;
+ return { response: 0 };
+ });
+ const result = expect(f.run()).rejects.toMatchObject({ code: 'TASK_BUSY' });
+ await vi.waitFor(() => expect(sendToSessionLocks.has('task')).toBe(true));
+ expect(f.live.setPermissionMode).not.toHaveBeenCalled();
+ release(); await result; await sender!;
+ });
+ it('keeps send fenced through runtime permission persistence and releases after rejection', async () => {
+ const f = fixture(); let release!: () => void;
+ const barrier = new Promise<void>(resolve => { release = resolve; });
+ f.epoch.client.tx.mockImplementationOnce(async () => { await barrier; throw new Error('persist failed'); });
+ const result = expect(f.run()).rejects.toThrow('persist failed');
+ await vi.waitFor(() => expect(f.epoch.client.tx).toHaveBeenCalled());
+ const send = vi.fn(async () => {});
+ await expect(withSendToSessionLock('task', send)).rejects.toThrow('restart');
+ expect(send).not.toHaveBeenCalled();
+ release(); await result;
+ await withSendToSessionLock('task', send); expect(send).toHaveBeenCalledOnce();
+ });
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
index a61d806930..b79dd1a2ce 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
@@ -107,6 +107,14 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
tail = result.catch(() => undefined);
return result;
};
+ // Drain spans the entire dispatch/control operation, without holding the receipt
+ // mutex while native dispatch calls accept()/settle() back into this service.
+ let operations: Promise<unknown> = Promise.resolve();
+ const completeOperation = <T>(fn: () => Promise<T>): Promise<T> => {
+ const result = fn();
+ operations = Promise.all([operations, result.catch(() => undefined)]).then(() => undefined);
+ return result;
+ };
const save = async (row: PluginTaskReceipt, payload: unknown) => {
deps.assertCurrent();
row.payload = JSON.stringify(payload);
@@ -171,8 +179,11 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
return {
/** Account teardown awaits already accepted writes before closing this DB. */
drain: async () => {
- let pending: Promise<unknown>;
- do { pending = tail; await pending; } while (pending !== tail);
+ let pending: Promise<unknown>, active: Promise<unknown>;
+ do {
+ pending = tail; active = operations;
+ await Promise.all([pending, active]);
+ } while (pending !== tail || active !== operations);
},
create: (
pluginId: string,
@@ -242,7 +253,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
send: async (
pluginId: string,
request: { taskId: string; requestKey: string; expectedRevision: number; text: string },
- ): Promise<PluginTaskRun> => {
+ ): Promise<PluginTaskRun> => completeOperation(async () => {
const prepared = await exclusive(async () => {
const view = await ownTask(pluginId, request.taskId);
const fingerprint = hash([request.text, request.expectedRevision]);
@@ -304,7 +315,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
}
return run;
});
- },
+ }),
getRun: async (pluginId: string, runId: string) =>
reconcile(await exclusive(() => ownRun(pluginId, runId))),
listRuns: async (pluginId: string, taskId: string, after = '', limit = 50) => {
@@ -317,7 +328,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
deps.assertAuthorized(pluginId);
return { items, nextCursor: rows.length === limit ? rows.at(-1)!.id : null };
},
- cancel: async (pluginId: string, runId: string): Promise<PluginTaskRun> => {
+ cancel: (pluginId: string, runId: string): Promise<PluginTaskRun> => completeOperation(async () => {
const prepared = await exclusive(async () => {
const row = await ownRun(pluginId, runId);
const run = JSON.parse(row.payload) as PluginTaskRun;
@@ -344,7 +355,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
await save(row, run);
return run;
});
- },
+ }),
/** Awaited before vendor dispatch. Aliases are native recovery provenance, never caller input. */
accept: (taskId: string, item: OwnedQueuedInput, execution: SessionExecutionIdentity) =>
exclusive(async () => {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index fdc223ec51..77e9d3d753 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10305,28 +10305,31 @@ 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 };
- 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();
- const live = maker.getSession(task.taskId);
- if (live) await live.setPermissionMode(mode);
- try {
+ // Reuse the existing non-bailing runtime mutation fence; do not hold it over the dialog.
+ return await withSessionRestartLock(task.taskId, async () => {
+ 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();
+ const live = maker.getSession(task.taskId);
+ if (live) await live.setPermissionMode(mode);
+ try {
+ if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ const saved = await snapshot!.client.tx('bots.persistSessionPermission', {sessionId: task.taskId, mode});
+ if (!saved.updated) throw new PluginTaskError('TASK_NOT_FOUND', 'Task not found');
+ } catch (error) {
+ if (live) await live.setPermissionMode(task.permissionMode as Parameters<typeof live.setPermissionMode>[0]).catch(() => undefined);
+ throw error;
+ }
if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
- const saved = await snapshot!.client.tx('bots.persistSessionPermission', {sessionId: task.taskId, mode});
- if (!saved.updated) throw new PluginTaskError('TASK_NOT_FOUND', 'Task not found');
- } catch (error) {
- if (live) await live.setPermissionMode(task.permissionMode as Parameters<typeof live.setPermissionMode>[0]).catch(() => undefined);
- throw error;
- }
- if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
- await service.get(pluginId, task.taskId);
- 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');
- if (mode === 'auto' || clampErrandPermissionMode(currentConfig.permissionMode) === 'plan') writeGhostErrandConfig(pluginId, {...currentConfig, permissionMode: mode});
- broadcastSessionPatched(task.taskId, {permissionMode: mode});
- return { granted: true, task: await service.get(pluginId, task.taskId) };
+ await service.get(pluginId, task.taskId);
+ 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');
+ if (mode === 'auto' || clampErrandPermissionMode(currentConfig.permissionMode) === 'plan') writeGhostErrandConfig(pluginId, {...currentConfig, permissionMode: mode});
+ broadcastSessionPatched(task.taskId, {permissionMode: mode});
+ return { granted: true, task: await service.get(pluginId, task.taskId) };
+ });
} finally { pluginPermissionRequests.delete(pluginId); }
}
case 'startTeam': {