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): validate worker plans against resolved configuration

Dash7adea4c41340
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 1c0d0ce082..e38c88c6e4 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@ -2750,7 +2750,7 @@ it('checks the resolved creation directory before bootstrap and releases a rejec
const {deps, service} = createDeps({validateCreationPlan, resolveWorkerWorkingDir: vi.fn(async () => resolved)});
const params = {leadSessionId:'lead-1',role:'eval',agent:'codex' as const,label:'sample',workingDir:path.resolve('candidate')};
await expect(service.createWorker(params)).rejects.toThrow('Directory authorization revoked');
- expect(validateCreationPlan).toHaveBeenLastCalledWith(expect.objectContaining(params), resolved);
+ expect(validateCreationPlan).toHaveBeenLastCalledWith(expect.objectContaining(params), resolved, expect.objectContaining({ model: 'gpt-5.5', providerId: 'xd' }));
expect(deps.bootstrapSession).not.toHaveBeenCalled();
expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledTimes(1);
});
@@ -2758,10 +2758,13 @@ it('checks the resolved creation directory before bootstrap and releases a rejec
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 callback = source.slice(source.indexOf(' validateCreationPlan: async (params, resolvedWorkingDir, resolvedRoute) => {'), 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 }) => {
+ it.each([
+ ...[false, true].flatMap(planned => ['reservation', 'directory', 'receipt', 'final-task', 'task-mode', 'disabled', 'healthy'].map(point => ({ planned, point }))),
+ ...['explicit-match', 'canonical-directory', 'different-model', 'different-directory', 'normalized-fast', 'changed-plan'].map(point => ({ planned: true, point })),
+ ])('checks $point with planned=$planned before bootstrap', async ({ planned, point }) => {
let reserved = false;
let mode = 'auto';
let taskMode = 'auto';
@@ -2771,7 +2774,9 @@ describe('production plugin Auto admission after reservation', () => {
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 planItem = { label: 'sample', workingDir: path.resolve(point === 'canonical-directory' ? 'alias' : point === 'different-directory' ? 'other' : 'repo'), route: { agentKind: 'codex', model: 'gpt-5.5', providerId: 'xd', effort: 'medium', fastMode: point === 'normalized-fast' } };
+ const payload = () => JSON.stringify(planned ? { teamPlan: { concurrency: 2, items: [planItem] } } : {});
+ const receipt = { pluginId: 'plugin', operation: 'create', payload: payload() };
const depsForCallback = {
getCurrentDbClientSnapshot: () => epoch,
createPluginTaskStore: () => ({ get: async () => { if (++receiptReads === 4 && point === 'receipt') revoke(); return receipt; } }),
@@ -2784,25 +2789,37 @@ describe('production plugin Auto admission after reservation', () => {
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'),
+ realpathWorkingDirectory: async (dir: string) => dir === path.resolve('other') ? dir : path.resolve('repo'),
isGhostPickedDir: () => false,
PluginTaskError,
};
const validateCreationPlan = new Function(...Object.keys(depsForCallback), js)(...Object.values(depsForCallback));
const { deps, service } = createDeps({ validateCreationPlan });
+ if (point === 'normalized-fast') {
+ const models = deps.getAvailableModels;
+ deps.getAvailableModels = agent => models(agent).map(model => ({ ...model, supportsFastMode: false }));
+ }
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;
+ if (point === 'changed-plan') {
+ planItem.route.model = 'gpt-5.4';
+ receipt.payload = payload();
+ }
return result;
});
- const result = service.createWorker({ leadSessionId: 'lead-1', role: 'eval', agent: 'codex', label: 'sample', workerPermissionMode: 'auto' });
- if (point === 'healthy') {
+ const result = service.createWorker({ leadSessionId: 'lead-1', role: 'eval', agent: 'codex', label: 'sample', workerPermissionMode: 'auto',
+ ...(point === 'explicit-match' ? { model: 'gpt-5.5', providerId: 'xd', effort: 'medium', fast: false, workingDir: path.resolve('repo') } : {}),
+ ...(point === 'different-model' ? { model: 'gpt-5.4' } : {}),
+ ...(point === 'normalized-fast' ? { fast: true } : {}),
+ });
+ if (['healthy', 'explicit-match', 'canonical-directory'].includes(point)) {
await expect(result).resolves.toMatchObject({ ok: true });
expect(deps.bootstrapSession).toHaveBeenCalledOnce();
} else {
- await expect(result).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ await expect(result).rejects.toMatchObject({ code: ['different-model', 'different-directory', 'normalized-fast', 'changed-plan'].includes(point) ? 'INVALID_REQUEST' : 'PERMISSION_DENIED' });
expect(deps.bootstrapSession).not.toHaveBeenCalled();
}
expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledTimes(1);
diff --git a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
index c21ceb3b4a..9549f2e5a6 100644
--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
@@ -208,7 +208,8 @@ export interface OrcaWorkerCreationDeps {
getActiveTeamByLead(leadSessionId: string): Promise<OrcaTeamSnapshot | null>;
listWorkersByLead(leadSessionId: string): Promise<OrcaWorkerListSnapshot[]>;
isActiveWorkerStatus(status: OrcaWorkerStatus): boolean;
- validateCreationPlan?(params: OrcaWorkerCreateInTeamParams, resolvedWorkingDir?: string): Promise<number | null | undefined>;
+ validateCreationPlan?(params: OrcaWorkerCreateInTeamParams, resolvedWorkingDir?: string,
+ resolvedRoute?: { model: string; providerId: string | null; effort: string | null; fastMode: boolean }): Promise<number | null | undefined>;
readCollaborationSettings(): { workerSoftLimit: number; workerHardLimit: number };
getLeadSessionRow(leadSessionId: string): Promise<OrcaLeadSessionSnapshot | null>;
getWorkerDefaults(agent: AgentKind): OrcaWorkerDefaultsSnapshot;
@@ -1026,7 +1027,7 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
try {
// Registration may race the preflight. Once a reservation exists, a new
// plan cannot be registered; reread any plan that won before reservation.
- const reservedPlanLimit = await deps.validateCreationPlan?.(params, workingDir);
+ const reservedPlanLimit = await deps.validateCreationPlan?.(params, workingDir, resolved);
if (reservedPlanLimit != null && reservation.occupiedSlotsBefore >= reservedPlanLimit) {
return { ok: false, errorCode: 'WORKER_LIMIT_HARD_EXCEEDED', message: 'Registered plan concurrency reached' };
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 2350d70946..d8f04f85e6 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -11691,7 +11691,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
listWorkersByLead,
isActiveWorkerStatus,
readCollaborationSettings,
- validateCreationPlan: async (params, resolvedWorkingDir) => {
+ validateCreationPlan: async (params, resolvedWorkingDir, resolvedRoute) => {
const epoch = getCurrentDbClientSnapshot();
if (!epoch) throw new PluginTaskError('HOST_NOT_READY','Task storage unavailable');
const receipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
@@ -11711,18 +11711,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 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 data = JSON.parse(currentReceipt.payload);
+ const item = data.teamPlan?.items.find((x: {label:string})=>x.label===params.label);
+ const plannedDirectory = item && resolvedRoute
+ ? await realpathWorkingDirectory(item.workingDir) : undefined;
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);
if (!item || data.settledLabels?.includes(params.label)) throw new PluginTaskError('INVALID_REQUEST','Worker is not pending in the registered plan');
const route = item.route;
- if (params.workingDir!==item.workingDir || params.model!==route.model || params.providerId!==route.providerId || params.effort!==route.effort || params.fast!==route.fastMode || params.agent!==(route.agentKind==='cc'?'claude-code':route.agentKind)) throw new PluginTaskError('INVALID_REQUEST','Worker configuration differs from registered plan');
+ // Defaults and provider capabilities are resolved by the creation service.
+ // Compare that exact spawn route at the post-reservation admission check.
+ if (resolvedRoute && (directory!==plannedDirectory || resolvedRoute.model!==route.model || resolvedRoute.providerId!==route.providerId || resolvedRoute.effort!==route.effort || resolvedRoute.fastMode!==route.fastMode || params.agent!==(route.agentKind==='cc'?'claude-code':route.agentKind))) throw new PluginTaskError('INVALID_REQUEST','Worker configuration differs from registered plan');
return data.teamPlan.concurrency;
},
getLeadSessionRow: async (leadSessionId) => {