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(plugin): 补齐项目投递权限复核与测试契约

liugaoweia6dc4bb2f6b4
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-agent-tasks.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-agent-tasks.md
index b4684d7940..c98294f5ae 100644
--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-agent-tasks.md
+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-agent-tasks.md
@@ -260,15 +260,8 @@ text 与 context 合计不超过 64000;tasks.send 的 text 上限仍为 32768
先检查 `tasks.capabilities().createPermissionMode === true`。`tasks.create` 和 project 的
`targets.send` 可传 `permissionMode: 'ask' | 'auto' | 'bypassPermissions'`,分别对应默认权限、自动审批、完全访问,仅决定这一个新任务的权限,
不修改插件默认设置。省略时仍使用用户的插件任务设置,未设置则为 ask。
-例如,用户已将插件权限设为 auto,插件可为某次任务选择 ask:
-```js
-const task = await cindy.tasks.create({
- requestKey: 'inspect-42', title: 'Inspect the selected item', permissionMode: 'ask',
-});
-```
-
-参数不是授权凭证。Host 在创建前及异步准备后按当前用户设置复核:ask 只允许 ask,
+参数不是授权凭证。Host 在创建前、异步准备后、投递及排队受理前按当前用户设置复核:ask 只允许 ask,
auto 允许 ask/auto,bypassPermissions 允许上述三档;超出范围返回 PERMISSION_DENIED,
不会静默降档或自动更改用户设置。完全访问须由用户在插件任务设置中选择;
既有 `requestWriteAccess` 仍只支持 acceptEdits/auto,不能请求完全访问或降低用户已授权的上限。
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts
index fd0f7ae61c..ad291b679a 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts
@@ -54,12 +54,13 @@ describe('plugin target queries and delivery', () => {
]);
const approvalRevision = vi.fn<PluginTargetAdapter['approvalRevision']>(() => 'approved-install');
const assertCreatePermission = vi.fn();
- slot.adapter = { store: () => store, approvalRevision, candidates, session: async () => 'chosen', send, create, withdraw, assertCreatePermission };
+ const assertProjectDispatch = vi.fn(async (_pluginId: string, _taskId: string) => {});
+ slot.adapter = { store: () => store, approvalRevision, candidates, session: async () => 'chosen', send, create, withdraw, assertCreatePermission, assertProjectDispatch };
const guard = vi.fn();
const call = (payload: unknown, plugin = 'plugin') => slot.handle(plugin, payload, guard);
const request = { kind: 'send', target: { kind: 'task', id: 'chosen' },
requestKey: 'send', text: 'context' };
- return { slot, call, request, send, create, withdraw, candidates, guard, approvalRevision, assertCreatePermission };
+ return { slot, call, request, send, create, withdraw, candidates, guard, approvalRevision, assertCreatePermission, assertProjectDispatch };
}
// unit: a project is a new task, but task/bot sends must never change recipient
// permissions. Prior tests did not cover a permission choice or its receipt.
@@ -97,6 +98,50 @@ describe('plugin target queries and delivery', () => {
expect(f.create).not.toHaveBeenCalled();
await expect(f.call(request)).resolves.toMatchObject({ accepted: true });
});
+ // Unit regression for #7615: project inputs have target receipts, not tasks.send
+ // receipts. Both delivery and restored queue acceptance must use the current
+ // plugin dispatch policy; existing task/bot recipients keep their own policy.
+ it('rejects a project input when its permission is lowered after task creation', async () => {
+ const f = fixture();
+ f.assertProjectDispatch.mockImplementation(async () => {
+ const code = f.create.mock.calls.length ? 'PERMISSION_DENIED' : 'TASK_NOT_FOUND';
+ throw Object.assign(new Error(code), { code });
+ });
+ await expect(f.call({ ...f.request, target: { kind: 'project', id: 'chosen' }, permissionMode: 'bypassPermissions' }))
+ .rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(f.create).toHaveBeenCalledOnce();
+ expect(f.send).not.toHaveBeenCalled();
+ expect([...receipts.values()][0]?.status).toBe('pending');
+ });
+ it.each(['live', 'restored'] as const)('rechecks project permission before accepting a %s queued input', async phase => {
+ const f = fixture();
+ await f.call({ ...f.request, target: { kind: 'project', id: 'chosen' }, permissionMode: 'bypassPermissions' });
+ f.assertProjectDispatch.mockRejectedValue(Object.assign(new Error('Permission lowered'), { code: 'PERMISSION_DENIED' }));
+ const [, taskId, clientId, , , validateTarget] = f.send.mock.calls[0]!;
+ const restarted = new PluginTargetSlot();
+ restarted.adapter = f.slot.adapter;
+ await expect(phase === 'live' ? validateTarget() : restarted.assertQueuedDelivery(taskId, clientId))
+ .rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(f.send).toHaveBeenCalledOnce();
+ });
+ it.each(['task', 'bot'] as const)('keeps the recipient permission policy for an existing %s', async kind => {
+ const f = fixture();
+ f.assertProjectDispatch.mockRejectedValue(Object.assign(new Error('Plugin permission denied'), { code: 'PERMISSION_DENIED' }));
+ await expect(f.call({ ...f.request, target: { kind, id: 'chosen' } })).resolves.toMatchObject({ accepted: true });
+ const [, taskId, clientId] = f.send.mock.calls[0]!;
+ await expect(f.slot.assertQueuedDelivery(taskId, clientId)).resolves.toBeUndefined();
+ expect(f.assertProjectDispatch).not.toHaveBeenCalled();
+ });
+ it.each(['approval', 'cancelled'] as const)('rechecks the receipt when %s changes during project policy validation', async change => {
+ const f = fixture();
+ await f.call({ ...f.request, target: { kind: 'project', id: 'chosen' }, permissionMode: 'bypassPermissions' });
+ f.assertProjectDispatch.mockImplementationOnce(async () => {
+ if (change === 'approval') f.approvalRevision.mockReturnValue('replacement-install');
+ else await f.call({ kind: 'cancel', requestKey: f.request.requestKey });
+ });
+ const [, taskId, clientId] = f.send.mock.calls[0]!;
+ await expect(f.slot.assertQueuedDelivery(taskId, clientId)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ });
// unit: actual target delivery must bind context to its receipt. Omitting the
// new parameter previously made changed context replay as the same message.
it('delivers independent context once and rejects changed context on receipt replay', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts b/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts
index aaad208e6c..d80d322d72 100644
--- a/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts
@@ -37,6 +37,7 @@ export interface PluginTargetAdapter {
approvalRevision(pluginId: string): string | null;
candidates(kind: PluginTargetKind): Promise<PluginTargetCandidate[]>;
assertCreatePermission(pluginId: string, permissionMode: PluginTaskPermissionMode): void;
+ assertProjectDispatch(pluginId: string, taskId: string): Promise<void>;
create(
pluginId: string,
project: string,
@@ -81,6 +82,9 @@ export class PluginTargetSlot {
private inFlight = new Map<string, { hash: string; cancelled: boolean; result?: Promise<unknown> }>();
/** Used by the existing queue acceptance boundary, including restored snapshots. */
async assertQueuedDelivery(taskId: string, clientId: string): Promise<void> {
+ await this.assertTargetReceipt(taskId, clientId, 'dispatch');
+ }
+ private async assertTargetReceipt(taskId: string, clientId: string, phase: 'create' | 'dispatch'): Promise<void> {
if (!this.adapter) fail('HOST_NOT_READY');
const adapter = this.adapter!;
const store = adapter.store();
@@ -94,6 +98,8 @@ export class PluginTargetSlot {
const target = receipt!.target!;
if (!(await adapter.candidates(target.kind)).some(item => item.id === target.id)) fail('TARGET_UNAVAILABLE');
if (target.kind !== 'project' && await adapter.session(target.kind, target.id) !== taskId) fail('TARGET_UNAVAILABLE');
+ if (target.kind === 'project' && phase === 'dispatch')
+ await adapter.assertProjectDispatch(receipt!.pluginId, taskId);
assertReceipt(await store.getById(clientId));
}
async handle(pluginId: string, raw: unknown, authorized: () => void): Promise<unknown> {
@@ -219,15 +225,18 @@ export class PluginTargetSlot {
await this.assertQueuedDelivery(taskId, receipt.id);
guard();
};
- await validateTarget();
if (target.kind === 'project') {
+ // Validate the target before creation; task dispatch policy requires the
+ // created task and is rechecked below and at queue acceptance.
+ await this.assertTargetReceipt(taskId, receipt.id, 'create');
+ guard();
const title = request.autoTitle ? DEFAULT_DRAFT_SESSION_TITLE : request.title || candidate.label;
if (request.permissionMode !== undefined)
await adapter.create(pluginId, target.id, taskId, title, route, guard, request.autoTitle || undefined, request.permissionMode);
else if (request.autoTitle) await adapter.create(pluginId, target.id, taskId, title, route, guard, true);
else await adapter.create(pluginId, target.id, taskId, title, route, guard);
}
- guard();
+ await validateTarget();
const actualDelivery = await adapter.send(
pluginId, taskId, receipt.id, request.text, guard, validateTarget, delivery, images,
request.context ? { context: request.context } : undefined,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts
index bd1da52687..9c0fc8456e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts
@@ -96,7 +96,11 @@ it('marks plugin dispatch and every queue fallback with the host-only receipt',
const start = source.indexOf('async function sendToSessionInternal(params: {');
const end = source.indexOf('const startOrcaTeamForCaller', start);
const dispatch = source.slice(start, end);
- expect(dispatch).toContain("message: text, autoReviewUserText: { kind: 'delegated-continuation' }, forceQueue: true");
+ const pluginStart = source.indexOf(' dispatch: async (pluginId, taskId, clientId, text');
+ expect(pluginStart).toBeGreaterThan(0);
+ const pluginDispatch = source.slice(pluginStart, source.indexOf(' inspect:', pluginStart));
+ // Independent context changes the message expression, not its Host authorship.
+ expect(pluginDispatch).toContain("autoReviewUserText: { kind: 'delegated-continuation' }, forceQueue: true");
const queues = [...dispatch.matchAll(/await enqueueSendToSessionMessage\(\{([\s\S]*?)\}\);/g)];
// Verified create handoffs add a fifth durable entry; all must retain provenance.
expect(queues).toHaveLength(5);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts
index 6f7fe6805c..68dc266c7f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts
@@ -81,7 +81,7 @@ it.each(['codex', 'cc'])('rechecks preferences after runtime admission waits for
it.each(['auto', 'acceptEdits'])('exposes independent Plan Mode alongside stored %s permission', async permissionMode => {
const start = source.indexOf(' readSession: async taskId =>');
- const property = source.slice(start, source.indexOf(' dispatch:', start)).trim().replace(/,$/, '');
+ const property = source.slice(start, source.indexOf(' scheduleAutoTitle:', start)).trim().replace(/,$/, '');
const row = {id:'task',source:'plugin',agentKind:'codex',status:'active',permissionMode,planModeEnabled:true};
const query = {from:()=>query,where:()=>query,limit:async()=>[row]};
const read = compile(`return ({${property}}).readSession;`, {assertCurrent:()=>{},snapshot:{client:{drizzle:{select:()=>query}}},sessions:{},eq:()=>true,pluginTaskConfigHash:createHash,readSessionRuntimeProfiles:async()=>null});
@@ -95,7 +95,7 @@ it.each(['auto', 'acceptEdits'])('exposes independent Plan Mode alongside stored
it.each(['codex', 'claude-code'] as const)('keeps the accepted next-input route stable when a deferred %s switch settles', async agentKind => {
const start = source.indexOf(' readSession: async taskId =>');
- const property = source.slice(start, source.indexOf(' dispatch:', start)).trim().replace(/,$/, '');
+ const property = source.slice(start, source.indexOf(' scheduleAutoTitle:', start)).trim().replace(/,$/, '');
const old = {agentKind:'codex',providerId:'old-provider',model:'old',effort:'medium',fastMode:false};
const next = {agentKind,providerId:'selected-provider',model:'selected',effort:'high',fastMode:false};
const row = {id:'task',source:'plugin',status:'active',permissionMode:'ask',planModeEnabled:false,...old};
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 7ccf2a2ebb..8e17e4f4e8 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -14505,6 +14505,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!isPluginTaskPermissionAllowed(permissionMode, clampPluginTaskPermissionMode(readPluginTaskConfig(pluginId).permissionMode)))
throw new PluginTaskError('PERMISSION_DENIED', 'Requested permission exceeds plugin dispatch policy');
},
+ assertProjectDispatch: async (pluginId, taskId) => {
+ await pluginTaskServiceForCurrentOwner!().assertDispatch(pluginId, taskId);
+ },
create: async (pluginId, project, taskId, title, route, guard, autoTitle, permissionMode) => {
guard();
await pluginTaskServiceForCurrentOwner!().create(pluginId, {