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): recheck Worker Auto authorization after reservation

Dasha137ec9a3665
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index 7d53c8d8f4..1c0d0ce082 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@ -1,4 +1,7 @@
import path from 'node:path';
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
+import { PluginTaskError } from '../pluginTaskService.js';
import { resolveAgentCredentialMode, type AgentKind } from '@cindy/maker-core';
import { describe, expect, it, vi } from 'vitest';
@@ -2751,3 +2754,57 @@ it('checks the resolved creation directory before bootstrap and releases a rejec
expect(deps.bootstrapSession).not.toHaveBeenCalled();
expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledTimes(1);
});
+
+describe('production plugin Auto admission after reservation', () => {
+ const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
+ const helper = source.slice(source.indexOf(' const assertPluginWorkerAutoAuthorized ='), source.indexOf(' const orcaWorkerCreationService ='));
+ const callback = source.slice(source.indexOf(' validateCreationPlan: async (params, resolvedWorkingDir) => {'), source.indexOf(' getLeadSessionRow: async (leadSessionId) => {'));
+ const js = ts.transpileModule(`${helper}\nreturn ({${callback}}).validateCreationPlan;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+
+ it.each([false, true].flatMap(planned => ['reservation', 'directory', 'receipt', 'final-task', 'task-mode', 'disabled', 'healthy'].map(point => ({ planned, point }))))('checks $point with planned=$planned before bootstrap', async ({ planned, point }) => {
+ let reserved = false;
+ let mode = 'auto';
+ let taskMode = 'auto';
+ let enabled = true;
+ let receiptReads = 0;
+ let taskReads = 0;
+ const epoch = { client: {} };
+ const revoke = () => { mode = 'acceptEdits'; };
+ const task = () => ({ revision: 1, permissionMode: taskMode, workingDir: path.resolve('repo') });
+ const receipt = { pluginId: 'plugin', operation: 'create', payload: JSON.stringify(planned ? { teamPlan: { concurrency: 2, items: [{ label: 'sample', route: { agentKind: 'codex' } }] } } : {}) };
+ const depsForCallback = {
+ getCurrentDbClientSnapshot: () => epoch,
+ createPluginTaskStore: () => ({ get: async () => { if (++receiptReads === 4 && point === 'receipt') revoke(); return receipt; } }),
+ pluginTaskServiceForCurrentOwner: () => ({ get: async () => {
+ ++taskReads;
+ if (taskReads === 4 && point === 'final-task') revoke();
+ if (taskReads === 4 && point === 'task-mode') taskMode = 'plan';
+ return task();
+ } }),
+ readGhostErrandConfig: () => ({ permissionMode: mode, workingDir: path.resolve('repo') }),
+ isPluginTaskAuthorized: () => enabled,
+ resolvePluginWorkerDirectory: async () => { if (reserved && point === 'directory') revoke(); return path.resolve('repo'); },
+ realpathWorkingDirectory: async () => path.resolve('repo'),
+ isGhostPickedDir: () => false,
+ PluginTaskError,
+ };
+ const validateCreationPlan = new Function(...Object.keys(depsForCallback), js)(...Object.values(depsForCallback));
+ const { deps, service } = createDeps({ validateCreationPlan });
+ const reserve = deps.reserveWorkerCreation;
+ deps.reserveWorkerCreation = vi.fn(async input => {
+ const result = await reserve(input); reserved = true;
+ if (point === 'reservation') revoke();
+ if (point === 'disabled') enabled = false;
+ return result;
+ });
+ const result = service.createWorker({ leadSessionId: 'lead-1', role: 'eval', agent: 'codex', label: 'sample', workerPermissionMode: 'auto' });
+ if (point === 'healthy') {
+ await expect(result).resolves.toMatchObject({ ok: true });
+ expect(deps.bootstrapSession).toHaveBeenCalledOnce();
+ } else {
+ await expect(result).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(deps.bootstrapSession).not.toHaveBeenCalled();
+ }
+ expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index cae837838b..1a15ea685a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -11415,6 +11415,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
getCatalog: getActiveCatalog,
});
+ const assertPluginWorkerAutoAuthorized = (pluginId: string, task: { permissionMode?: string }) => {
+ if (!isPluginTaskAuthorized(pluginId) || task.permissionMode !== 'auto' || readGhostErrandConfig(pluginId).permissionMode !== 'auto') {
+ throw new PluginTaskError('PERMISSION_DENIED', 'Authorize Auto for the plugin coordinator before creating Workers');
+ }
+ };
+
const orcaWorkerCreationService = createOrcaWorkerCreationService({
getActiveTeamByLead,
listWorkersByLead,
@@ -11427,6 +11433,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!receipt || receipt.operation !== 'create') return undefined;
const task = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ assertPluginWorkerAutoAuthorized(receipt.pluginId, task);
const cfg = readGhostErrandConfig(receipt.pluginId);
const directory = await resolvePluginWorkerDirectory({
requested: params.workingDir ?? task.workingDir ?? '', leadDirectory: task.workingDir,
@@ -11436,11 +11443,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
});
if (resolvedWorkingDir !== undefined && directory !== await realpathWorkingDirectory(resolvedWorkingDir)) throw new PluginTaskError('PERMISSION_DENIED','Worker directory changed during creation');
- const currentTask = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
- if (epoch !== getCurrentDbClientSnapshot() || currentTask.revision !== task.revision) throw new PluginTaskError('STALE_REVISION','Task changed during directory validation');
// get() waits behind plan registration in the existing receipt queue.
const currentReceipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
if (!currentReceipt) throw new PluginTaskError('TASK_NOT_FOUND', 'Task not found');
+ const currentTask = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot() || currentTask.revision !== task.revision) throw new PluginTaskError('STALE_REVISION','Task changed during directory validation');
+ // Last admission check also covers no-plan plugin tasks and revocation
+ // while directory/receipt reads or the existing reservation were pending.
+ assertPluginWorkerAutoAuthorized(receipt.pluginId, currentTask);
+ if (cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');
const data = JSON.parse(currentReceipt.payload);
if (!data.teamPlan) return undefined; // Existing plugins retain their original behavior.
const item = data.teamPlan.items.find((x: {label:string})=>x.label===params.label);
@@ -11556,9 +11567,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const task = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId, leadSessionId);
if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
// Plugin tasks never inherit an unrelated global Full access preference.
- if (task.permissionMode !== 'auto' || readGhostErrandConfig(receipt.pluginId).permissionMode !== 'auto') {
- throw new PluginTaskError('PERMISSION_DENIED', 'Authorize Auto for the plugin coordinator before creating Workers');
- }
+ assertPluginWorkerAutoAuthorized(receipt.pluginId, task);
return 'auto';
},
setWorkerPermissionMode: applyWorkerPermissionModePreference,