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。

merge: sync final Worker authority checks from plugin runtime

Dashd7769dd5ac6c
diff --cc apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index bfdf987de1,5f5186b171..f944c739e0
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@@ -61,9 -70,14 +70,14 @@@ describe('Host provenance across Orca c
};
const bindings = {
maker: {getSession:()=>null}, inputCoordinator: { getAcceptedInputProvenance: () => null },
- PluginTaskError, getCurrentDbClientSnapshot: () => epoch,
+ PluginTaskError, readPluginTaskPlanReceipt: JSON.parse, getCurrentDbClientSnapshot: () => epoch,
createPluginTaskStore: () => ({ get: async () => receipt && { ...receipt } }),
pluginTaskServiceForCurrentOwner: () => ({ get: async (pluginId: string) => {
+ if (directoryResolved) {
+ directoryReads++;
+ if (directoryReads === 2) mutate('final-task');
+ if (directoryReads === 3) mutate('final-source');
+ }
if (!receipt || receipt.pluginId !== pluginId || JSON.parse(receipt.payload).ownershipRevoked) throw new PluginTaskError('TASK_NOT_FOUND', 'Revoked');
return { ...task };
} }),
@@@ -2845,7 -2922,7 +2922,7 @@@ it('uses one canonical label at every p
const { service } = createDeps({ validateCreationPlan });
const params = Object.freeze({ leadSessionId: 'lead-1', teamId: 'team-1', role: 'eval', agent: 'codex' as const, label: ' SAMPLE ', workerPermissionMode: 'auto' as const });
await expect(service.createWorkerInTeam(params)).resolves.toMatchObject({ ok: true });
-- expect(validateCreationPlan).toHaveBeenCalledTimes(4);
++ expect(validateCreationPlan).toHaveBeenCalledTimes(5);
for (const call of validateCreationPlan.mock.calls) expect(call[0]).toMatchObject({ label: 'sample' });
expect(params.label).toBe(' SAMPLE ');
});
@@@ -2879,90 -2956,8 +2956,90 @@@ it('checks the resolved creation direct
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, resolvedRoute) => {'), source.indexOf(' getLeadSessionRow: async (leadSessionId) => {'));
+ const callback = source.slice(source.indexOf(' validateCreationPlan: async ('), source.indexOf(' getLeadSessionRow: async (leadSessionId) => {'));
const js = ts.transpileModule(`${helper}\nreturn ({${callback}}).validateCreationPlan;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const override = source.slice(source.indexOf(' getWorkerPermissionModeOverride: async (leadSessionId) => {'), source.indexOf(' setWorkerPermissionMode: applyWorkerPermissionModePreference,'));
+ const overrideJs = ts.transpileModule(`${helper}\nreturn ({${override}}).getWorkerPermissionModeOverride;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+
+ it.each([false, true].flatMap(planned => ['bootstrap', 'renewal'].flatMap(stage =>
+ ['disabled', 'uninstalled', 'reinstalled', 'account', 'owner', 'missing', 'downgraded', 'plan', 'archived', 'storage', 'healthy'].map(change => ({ planned, stage, change })),
+ )))('rechecks $change after $stage with planned=$planned before persistence and dispatch', async ({ planned, stage, change }) => {
+ let epoch = { client: {} };
+ let enabled = true, missing = false, storageFailed = false;
+ const task = { revision: 1, status: 'active', permissionMode: 'auto', planModeEnabled: false, workingDir: path.resolve('repo') };
+ const receipt = { pluginId: 'plugin', operation: 'create', payload: JSON.stringify(planned ? {
+ teamPlan: { concurrency: 2, items: [{ label: 'sample', workingDir: task.workingDir,
+ route: { agentKind: 'codex', model: 'gpt-5.5', providerId: 'xd', effort: 'medium', fastMode: false } }] },
+ } : {}) };
+ const callbackDeps = {
+ maker: {getSession:()=>null}, inputCoordinator: { getAcceptedInputProvenance: () => null },
- readPluginTaskPlanReceipt: JSON.parse, getCurrentDbClientSnapshot: () => epoch,
++ readPluginTaskPlanReceipt: JSON.parse, assertPluginWorkerDirectoryScope, getCurrentDbClientSnapshot: () => epoch,
+ createPluginTaskStore: () => ({ get: async () => {
+ if (storageFailed) throw new Error('storage unavailable');
+ return missing ? null : structuredClone(receipt);
+ } }),
+ pluginTaskServiceForCurrentOwner: () => ({ get: async () => {
+ if (JSON.parse(receipt.payload).ownershipRevoked) throw new PluginTaskError('TASK_NOT_FOUND', 'Not owned');
+ return { ...task };
+ } }),
+ readGhostErrandConfig: () => ({ permissionMode: 'auto', workingDir: task.workingDir }),
+ isPluginTaskAuthorized: () => enabled,
+ resolvePluginWorkerDirectory: async () => task.workingDir,
+ isGhostPickedDir: () => false, PluginTaskError,
+ };
+ const validateCreationPlan = new Function(...Object.keys(callbackDeps), js)(...Object.values(callbackDeps));
+ const { deps, service } = createDeps({ validateCreationPlan });
+ const mutate = () => {
+ if (change === 'disabled') enabled = false;
+ if (['uninstalled', 'reinstalled'].includes(change)) {
+ receipt.payload = JSON.stringify({ ...JSON.parse(receipt.payload), ownershipRevoked: true });
+ enabled = change === 'reinstalled';
+ }
+ if (change === 'account') epoch = { client: {} };
+ if (change === 'owner') receipt.pluginId = 'other-plugin';
+ if (change === 'missing') missing = true;
+ if (change === 'downgraded') task.permissionMode = 'default';
+ if (change === 'plan') task.planModeEnabled = true;
+ if (change === 'archived') task.status = 'archived';
+ if (change === 'storage') storageFailed = true;
+ };
+ const bootstrap = deps.bootstrapSession;
+ deps.bootstrapSession = vi.fn(async opts => { const result = await bootstrap(opts); if (stage === 'bootstrap') mutate(); return result; });
+ deps.renewWorkerCreationReservation = vi.fn(async () => { if (stage === 'renewal') mutate(); return true; });
+ const markTeamEnded = vi.fn(async () => undefined);
+ const getWorkerPermissionModeOverride = new Function('hasAcceptedUserTaskInput', ...Object.keys(callbackDeps), overrideJs)(hasAcceptedUserTaskInput, ...Object.values(callbackDeps));
+ const lifecycle = createOrcaLifecycleService({
+ getWorkerPermissionModeOverride,
+ getActiveTeamByLead: async () => planned ? null : { id: 'team-1', leadSessionId: 'lead-1' },
+ createActiveTeam: async () => ({ id: 'team-1', leadSessionId: 'lead-1' }),
+ isOrphanedTeamInit: async () => false, getWorkerPermissionMode: () => 'auto',
+ setWorkerPermissionMode: vi.fn(), createWorkerInTeam: service.createWorkerInTeam,
+ dispatchWorkerTask: deps.dispatchWorkerTask, markTeamEnded, setSessionOrcaRole: vi.fn(async () => undefined),
+ clearKnownNonOrcaSession: vi.fn(), setLeadVendorOptions: vi.fn(async () => undefined), clearLeadVendorOptions: vi.fn(async () => undefined),
+ sendWorkerReadyPlaceholder: vi.fn(async () => undefined), rollbackCreatedWorker: vi.fn(async () => undefined),
+ broadcastSessionCreated: deps.broadcastSessionCreated, broadcastOrcaWorkerChanged: deps.broadcastOrcaWorkerChanged,
+ });
+ const result = planned
+ ? await lifecycle.enableTeam({ leadSessionId: 'lead-1', workerAgent: 'codex', role: 'eval', label: 'sample', delegateTask: 'Evaluate sample' })
+ : await lifecycle.createWorker({ leadSessionId: 'lead-1', agent: 'codex', role: 'eval', label: 'sample', initialTask: 'Evaluate sample' });
+ expect(deps.bootstrapSession).toHaveBeenCalledOnce();
+ expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledOnce();
+ if (change === 'healthy') {
+ expect(result.ok).toBe(true);
+ expect(deps.addOrUpdateWorker).toHaveBeenCalledOnce();
+ expect(deps.dispatchWorkerTask).toHaveBeenCalledOnce();
+ expect(deps.closeWorkerSession).not.toHaveBeenCalled();
+ } else {
+ expect(result).toMatchObject({ ok: false, errorCode: 'INTERNAL' });
+ expect(deps.addOrUpdateWorker).not.toHaveBeenCalled();
+ expect(deps.markOrcaRoleIfNeeded).not.toHaveBeenCalled();
+ expect(deps.dispatchWorkerTask).not.toHaveBeenCalled();
+ for (const cleanup of [deps.closeWorkerSession, deps.forgetWorkerSession, deps.archiveWorkerSession]) {
+ expect(cleanup).toHaveBeenCalledExactlyOnceWith(WORKER_SESSION_ID);
+ }
+ if (planned) expect(markTeamEnded).toHaveBeenCalledExactlyOnceWith('team-1', 'failed');
+ }
+ });
it.each(['uninstalled', 'reinstalled', 'malformed'])('keeps ordinary Worker creation separate from %s plugin receipts', async state => {
const epoch = { client: {} }, get = vi.fn(async () => { throw new PluginTaskError('TASK_NOT_FOUND', 'Not owned'); });
@@@ -3004,9 -2999,9 +3081,10 @@@
const payload = () => JSON.stringify(planned ? { teamPlan: { concurrency: 2, items: [planItem] }, settledLabels: point === 'settled-label' ? ['sample'] : [] } : {});
const receipt = { pluginId: 'plugin', operation: 'create', payload: payload() };
const depsForCallback = {
+ readPluginTaskPlanReceipt: JSON.parse,
+ assertPluginWorkerDirectoryScope,
getCurrentDbClientSnapshot: () => epoch,
- createPluginTaskStore: () => ({ get: async () => { if (++receiptReads === 4 && point === 'receipt') revoke(); return structuredClone(receipt); } }),
+ createPluginTaskStore: () => ({ get: async () => { if (++receiptReads === 6 && point === 'receipt') revoke(); return structuredClone(receipt); } }),
pluginTaskServiceForCurrentOwner: () => ({ get: async () => {
if (reserved) ++reservedTaskReads;
if (reservedTaskReads === 3 && point === 'final-task') revoke();
@@@ -3069,32 -3056,6 +3147,32 @@@
await expect(result).rejects.toMatchObject({ code: point.startsWith('archive-') ? 'TASK_BUSY' : ['different-model', 'different-directory', 'normalized-fast', 'changed-plan', 'queued-plan-excludes', 'queued-plan-route', 'settled-label'].includes(point) ? 'INVALID_REQUEST' : 'PERMISSION_DENIED' });
expect(deps.bootstrapSession).not.toHaveBeenCalled();
}
- expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledTimes(['archive-first', 'plan-first', 'settled-label'].includes(point) ? 0 : 1);
+ expect(deps.releaseWorkerCreationReservation).toHaveBeenCalledTimes(reserved ? 1 : 0);
+ });
+});
+it('rechecks a newly registered plan under the Lead send lock before reserving', async () => {
+ let locked = false, limit: number | undefined;
+ const validateCreationPlan = vi.fn(async () => limit);
+ const {deps,service}=createDeps({
+ validateCreationPlan,
+ withLeadSendLock: async (_id, operation) => {
+ limit = 1; locked = true;
+ try { return await operation(); } finally { locked = false; }
+ },
+ });
+ vi.mocked(deps.reserveWorkerCreation).mockImplementation(async input => {
+ expect(locked).toBe(true);expect(input.hardLimit).toBe(1);
+ return {ok:true,occupiedSlotsBefore:0};
});
+ const bootstrap=deps.bootstrapSession;
+ deps.bootstrapSession=vi.fn(async (opts: MakerSessionCreateOpts) => {expect(locked).toBe(false);return bootstrap(opts);});
+ await service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'});
- expect(validateCreationPlan).toHaveBeenCalledTimes(4);
++ expect(validateCreationPlan).toHaveBeenCalledTimes(5);
+ expect(deps.reserveWorkerCreation).toHaveBeenCalledOnce();
+});
+it('rejects a plan changed during preparation without reserving or bootstrapping', async () => {
+ const validate=vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error('not pending'));
+ const {deps,service}=createDeps({validateCreationPlan:validate,withLeadSendLock:async (_id, operation)=>operation()});
+ const result=await service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'});
+ expect(result.ok).toBe(false);expect(deps.reserveWorkerCreation).not.toHaveBeenCalled();expect(deps.bootstrapSession).not.toHaveBeenCalled();
});
diff --cc apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
index ce75f4619c,a35a791a55..a1a521e863
--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
@@@ -203,12 -203,6 +203,13 @@@ export interface OrcaWorkerCreateInTeam
workerPermissionMode: OrcaWorkerPermissionMode;
}
+export type OrcaWorkerCreationPlanValidator = (
+ params: OrcaWorkerCreateInTeamParams,
+ resolvedWorkingDir?: string,
+ resolvedRoute?: { model: string; providerId: string | null; effort: string | null; fastMode: boolean },
++ assertCurrent?: () => Promise<void>,
+) => Promise<number | null | undefined>;
+
/** creation service 的 I/O 边界;register.ts 负责把 DB、Maker 与 broadcast 注入进来。 */
export interface OrcaWorkerCreationDeps {
getActiveTeamByLead(leadSessionId: string): Promise<OrcaTeamSnapshot | null>;
@@@ -627,11 -624,11 +630,11 @@@ export function createOrcaWorkerCreatio
const label = normalizeOrcaWorkerLabel(params.label);
if (!label.ok) return { ok: false, errorCode: 'INVALID_PARAMS', message: label.message };
params = { ...params, label: label.value };
- const validatePlan = async (workingDir?: string, route?: Parameters<NonNullable<OrcaWorkerCreationDeps['validateCreationPlan']>>[2]) => {
+ const validatePlan = async (workingDir?: string, route?: Parameters<OrcaWorkerCreationPlanValidator>[2]) => {
await assertCurrent?.();
- const limit = await deps.validateCreationPlan?.(params, workingDir, route);
- await assertCurrent?.();
- return limit;
+ // Host validation runs the captured source check before its final synchronous
+ // directory grant check. No trailing await may stale that grant observation.
+ return deps.validateCreationPlan?.(params, workingDir, route, assertCurrent);
};
const existing = await deps.listWorkersByLead(params.leadSessionId);
diff --cc apps/desktop/src/main/maker-ipc/register.ts
index 106a6e4972,e7770467bd..c211fdc0a8
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -1,6 -1,5 +1,6 @@@
-import { isPluginTaskPermissionAllowed, assertPluginTaskResult, createPluginTaskService, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';
+import { createPluginTaskReviewResolver } from './pluginTaskReviewContext.js';
+import { isPluginTaskPermissionAllowed, assertPluginTaskResult, createPluginTaskService, readPluginTaskPlanReceipt, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';
- import { resolvePluginWorkerDirectory } from './pluginWorkerDirectory.js';
+ import { assertPluginWorkerDirectoryScope, resolvePluginWorkerDirectory } from './pluginWorkerDirectory.js';
import { PluginWriteAccessGate } from './pluginWriteAccessGate.js';
import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';
import { createPluginTaskStore } from './pluginTaskStore.js';
@@@ -12047,7 -12034,7 +12067,8 @@@ export function registerMakerIpc(maker
const epoch = getCurrentDbClientSnapshot();
if (!epoch) throw new PluginTaskError('HOST_NOT_READY','Task storage unavailable');
const receipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
+ await assertCurrent?.();
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
if (!receipt || receipt.operation !== 'create' || hasRevokedPluginTaskOwnership(receipt)) return undefined;
const task = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');