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 plugin runtime creation provenance fix into delegated Auto

Dash4e8d93369913
diff --cc apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index 8fe29f1480,ba2f216c58..156c18eb72
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@@ -22,6 -21,116 +21,116 @@@ import { CredentialModeSwitchBusyError
import { isActiveWorkerStatus } from '../../../shared/orca-worker-status';
import { sshCodexWorkerRoutingContext } from '../orcaProviderRoutingContext';
import type { ProviderView } from '@cindy/model-providers';
+ import { createOrcaLifecycleService, type OrcaLifecycleDeps } from '../orcaLifecycleService';
+
+ describe('Host provenance across Orca creation waits', () => {
+ const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
+ const helper = source.slice(source.indexOf(' const assertPluginWorkerAutoAuthorized ='), source.indexOf(' const orcaWorkerCreationService ='));
+ function callback(start: string, end: string, bindings: Record<string, unknown>) {
+ const from = source.indexOf(start), to = source.indexOf(end, from);
+ expect(from).toBeGreaterThan(0);
+ expect(to).toBeGreaterThan(from);
+ const js = ts.transpileModule(`${helper}\nreturn ({${source.slice(from, to)}});`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ return new Function(...Object.keys(bindings), js)(...Object.values(bindings));
+ }
+ type Action = 'createWorker' | 'enableTeam' | 'startNew' | 'startExisting';
+ const phases: Record<Action, string[]> = {
+ createWorker: ['team-query', 'worker-list', 'bootstrap', 'renewal', 'worker-write'],
+ enableTeam: ['team-query', 'team-create', 'worker-list', 'bootstrap', 'renewal', 'worker-write', 'lead-activation'],
+ startNew: ['team-query', 'team-create', 'lead-activation'],
+ startExisting: ['team-query', 'lead-activation'],
+ };
+ function setup(action: Action, phase: string, change: string) {
+ let epoch = { client: {} }, enabled = true;
+ let receipt: { operation: string; pluginId: string; payload: string } | null = {
+ operation: 'create', pluginId: 'plugin', payload: JSON.stringify({ ownershipRevoked: change === 'already-revoked' }),
+ };
+ const task = { revision: 1, status: 'active', permissionMode: 'auto', planModeEnabled: false, workingDir: path.resolve('synthetic-project') };
+ const mutate = (point: string) => {
+ if (point !== phase) return;
+ if (change === 'uninstalled' || change === 'reinstalled') {
+ receipt!.payload = '{"ownershipRevoked":true}'; enabled = change === 'reinstalled';
+ } else if (change === 'owner') receipt!.pluginId = 'other-plugin';
+ else if (change === 'missing') receipt = null;
+ else if (change === 'account') epoch = { client: {} };
+ else if (change === 'ask') task.permissionMode = 'default';
+ else if (change === 'plan') task.planModeEnabled = true;
+ else if (change === 'archived') task.status = 'archived';
+ else if (change === 'disabled') enabled = false;
+ };
+ const bindings = {
- PluginTaskError, getCurrentDbClientSnapshot: () => epoch,
++ PluginTaskError, readPluginTaskPlanReceipt: JSON.parse, getCurrentDbClientSnapshot: () => epoch,
+ createPluginTaskStore: () => ({ get: async () => receipt && { ...receipt } }),
+ pluginTaskServiceForCurrentOwner: () => ({ get: async (pluginId: string) => {
+ if (!receipt || receipt.pluginId !== pluginId || JSON.parse(receipt.payload).ownershipRevoked) throw new PluginTaskError('TASK_NOT_FOUND', 'Revoked');
+ return { ...task };
+ } }),
+ isPluginTaskAuthorized: () => enabled, readGhostErrandConfig: () => ({ permissionMode: 'auto', workingDir: task.workingDir }),
+ resolvePluginWorkerDirectory: async () => task.workingDir, isGhostPickedDir: () => false,
+ };
+ const { deps, service: creation } = createDeps(callback(' validateCreationPlan: async (', ' getLeadSessionRow: async (', bindings));
+ for (const [key, point] of [
+ ['listWorkersByLead', 'worker-list'], ['bootstrapSession', 'bootstrap'],
+ ['renewWorkerCreationReservation', 'renewal'], ['addOrUpdateWorker', 'worker-write'],
+ ] as const) {
+ const original = deps[key] as (...args: unknown[]) => Promise<unknown>;
+ (deps as unknown as Record<string, unknown>)[key] = vi.fn(async (...args: unknown[]) => {
+ const result = await original(...args); mutate(point); return result;
+ });
+ }
+ const lifecycleDeps: OrcaLifecycleDeps = {
+ ...callback(' getWorkerPermissionModeOverride: async (', ' setWorkerPermissionMode: applyWorkerPermissionModePreference,', bindings),
+ ...callback(' createWorkerInTeam: (params', ' dispatchWorkerTask: (params)', { ...bindings, orcaWorkerCreationService: creation }),
+ getActiveTeamByLead: vi.fn(async () => { mutate('team-query'); return action === 'createWorker' || action === 'startExisting' ? { id: 'team-1', leadSessionId: 'lead-1' } : null; }),
+ createActiveTeam: vi.fn(async () => { mutate('team-create'); return { id: 'new-team', leadSessionId: 'lead-1' }; }),
+ isOrphanedTeamInit: vi.fn(async () => false), getWorkerPermissionMode: () => 'bypassPermissions', setWorkerPermissionMode: vi.fn(),
+ dispatchWorkerTask: deps.dispatchWorkerTask, markTeamEnded: vi.fn(async () => undefined), setSessionOrcaRole: vi.fn(async () => undefined),
+ clearKnownNonOrcaSession: vi.fn(), setLeadVendorOptions: vi.fn(async () => { mutate('lead-activation'); }), clearLeadVendorOptions: vi.fn(async () => undefined),
+ sendWorkerReadyPlaceholder: vi.fn(async () => undefined), rollbackCreatedWorker: vi.fn(async () => undefined),
+ broadcastSessionCreated: vi.fn(), broadcastOrcaWorkerChanged: vi.fn(),
+ };
+ const lifecycle = createOrcaLifecycleService(lifecycleDeps);
+ const run = () => action === 'createWorker'
+ ? lifecycle.createWorker({ leadSessionId: 'lead-1', agent: 'codex', role: 'eval', label: 'sample', initialTask: 'Synthetic task' })
+ : action === 'enableTeam'
+ ? lifecycle.enableTeam({ leadSessionId: 'lead-1', workerAgent: 'codex', role: 'eval', label: 'sample', delegateTask: 'Synthetic task' })
+ : lifecycle.startTeam({ leadSessionId: 'lead-1' });
+ return { deps, lifecycleDeps, run };
+ }
+ const cases = (Object.keys(phases) as Action[]).flatMap(action => phases[action].flatMap(phase =>
+ ['uninstalled', 'reinstalled', 'account'].map(change => ({ action, phase, change }))));
+ cases.push(...(['createWorker', 'enableTeam'] as Action[]).flatMap(action =>
+ ['owner', 'missing', 'ask', 'plan', 'archived', 'disabled'].map(change => ({ action, phase: 'bootstrap', change }))));
+ it.each(cases)('rejects $action after $change during $phase without dispatch', async ({ action, phase, change }) => {
+ const { deps, lifecycleDeps, run } = setup(action, phase, change);
+ const result = await run().catch(() => ({ ok: false }));
+ expect(result.ok).toBe(false);
+ expect(deps.dispatchWorkerTask).not.toHaveBeenCalled();
+ expect(lifecycleDeps.sendWorkerReadyPlaceholder).not.toHaveBeenCalled();
+ if (phase === 'bootstrap' || phase === 'renewal') {
+ expect(deps.addOrUpdateWorker).not.toHaveBeenCalled();
+ expect(deps.closeWorkerSession).toHaveBeenCalled();
+ expect(deps.releaseWorkerCreationReservation).toHaveBeenCalled();
+ }
+ if (phase === 'worker-write' || (action === 'enableTeam' && phase === 'lead-activation')) {
+ expect(lifecycleDeps.rollbackCreatedWorker).toHaveBeenCalled();
+ }
+ if (vi.mocked(lifecycleDeps.createActiveTeam).mock.calls.length) expect(lifecycleDeps.markTeamEnded).toHaveBeenCalledWith('new-team', 'failed');
+ else expect(lifecycleDeps.markTeamEnded).not.toHaveBeenCalled();
+ expect(lifecycleDeps.setWorkerPermissionMode).not.toHaveBeenCalled();
+ });
+ it.each((Object.keys(phases) as Action[]).flatMap(action => ['healthy', 'already-revoked'].map(change => ({ action, change }))))(
+ 'preserves $change behavior for $action', async ({ action, change }) => {
+ const { deps, lifecycleDeps, run } = setup(action, '', change);
+ expect(await run()).toMatchObject({ ok: true });
+ if (action === 'createWorker' || action === 'enableTeam') {
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({ permissionMode: change === 'healthy' ? 'auto' : 'bypassPermissions' }));
+ expect(deps.dispatchWorkerTask).toHaveBeenCalledTimes(1);
+ }
+ expect(lifecycleDeps.setWorkerPermissionMode).not.toHaveBeenCalled();
+ },
+ );
+ });
describe('SSH Codex Worker catalog', () => {
it.each([undefined, 'remote-next', 'controller-only'])('uses remote membership and defaults for %s', async (model) => {
@@@ -2728,13 -2837,13 +2837,13 @@@ describe('SSH remote worker model/provi
});
});
- it('applies plan limit in atomic reservation',async()=>{const {deps,service}=createDeps({createCreationPlanValidator:()=>vi.fn(async()=>2)});await service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'});expect(deps.reserveWorkerCreation).toHaveBeenCalledWith(expect.objectContaining({hardLimit:2}));});
- it('uses one canonical label at all plan checks without mutating the caller', async () => {
+ it('applies plan limit in atomic reservation',async()=>{const {deps,service}=createDeps({validateCreationPlan:vi.fn(async()=>2)});await service.createWorker({leadSessionId:'lead-1',role:'eval',agent:'codex',label:'sample'});expect(deps.reserveWorkerCreation).toHaveBeenCalledWith(expect.objectContaining({hardLimit:2}));});
+ it('uses one canonical label at every plan check without mutating the caller', async () => {
const validateCreationPlan = vi.fn(async (_params: OrcaWorkerCreateParams) => 2);
- const { service } = createDeps({ createCreationPlanValidator: () => validateCreationPlan });
+ 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(3);
+ expect(validateCreationPlan).toHaveBeenCalledTimes(4);
for (const call of validateCreationPlan.mock.calls) expect(call[0]).toMatchObject({ label: 'sample' });
expect(params.label).toBe(' SAMPLE ');
});
@@@ -2754,10 -2863,10 +2863,10 @@@ it('revalidates a plan registered durin
it('checks the resolved creation directory before bootstrap and releases a rejected reservation', async () => {
const resolved = path.resolve('resolved-candidate');
const validateCreationPlan = vi.fn(async (_params, directory?: string) => {
- if (directory !== undefined) throw new Error('Directory authorization revoked');
+ if (directory !== undefined && validateCreationPlan.mock.calls.length >= 3) throw new Error('Directory authorization revoked');
return undefined;
});
- const {deps, service} = createDeps({createCreationPlanValidator: () => validateCreationPlan, resolveWorkerWorkingDir: vi.fn(async () => resolved)});
+ 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.objectContaining({ model: 'gpt-5.5', providerId: 'xd' }));
@@@ -2768,85 -2877,8 +2877,89 @@@
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(' createCreationPlanValidator: () => {'), source.indexOf(' getLeadSessionRow: async (leadSessionId) => {'));
- const js = ts.transpileModule(`${helper}\nreturn ({${callback}}).createCreationPlanValidator;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ 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;
++ 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 = {
+ readPluginTaskPlanReceipt: JSON.parse, 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 createCreationPlanValidator = new Function(...Object.keys(callbackDeps), js)(...Object.values(callbackDeps));
- const { deps, service } = createDeps({ createCreationPlanValidator });
++ 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(...Object.keys(callbackDeps), overrideJs)(...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'); });
@@@ -2914,11 -2945,8 +3027,11 @@@
isGhostPickedDir: () => false,
PluginTaskError,
};
- const createCreationPlanValidator = new Function(...Object.keys(depsForCallback), js)(...Object.values(depsForCallback));
- const { deps, service } = createDeps({ createCreationPlanValidator, withLeadSendLock: async (_id, operation) => {
+ const validateCreationPlan = new Function(...Object.keys(depsForCallback), js)(...Object.values(depsForCallback));
- const { deps, service } = createDeps({ validateCreationPlan });
++ const { deps, service } = createDeps({ validateCreationPlan, withLeadSendLock: async (_id, operation) => {
+ if (point === 'archive-admission') taskStatus = 'archived';
+ return operation();
+ } });
if (point === 'normalized-fast') {
const models = deps.getAvailableModels;
deps.getAvailableModels = agent => models(agent).map(model => ({ ...model, supportsFastMode: false }));
@@@ -2953,32 -2976,6 +3066,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({
- createCreationPlanValidator: () => validateCreationPlan,
++ 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(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({createCreationPlanValidator:()=>validate,withLeadSendLock:async (_id, operation)=>operation()});
++ 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 6a49f4b75e,6b72cf6d1b..ce75f4619c
--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
@@@ -214,9 -208,8 +214,8 @@@ export interface OrcaWorkerCreationDep
getActiveTeamByLead(leadSessionId: string): Promise<OrcaTeamSnapshot | null>;
listWorkersByLead(leadSessionId: string): Promise<OrcaWorkerListSnapshot[]>;
isActiveWorkerStatus(status: OrcaWorkerStatus): boolean;
- validateCreationPlan?(params: OrcaWorkerCreateInTeamParams, resolvedWorkingDir?: string,
- resolvedRoute?: { model: string; providerId: string | null; effort: string | null; fastMode: boolean }): Promise<number | null | undefined>;
+ withLeadSendLock?<T>(leadSessionId: string, operation: () => Promise<T>): Promise<T>;
- /** One validator per creation keeps its original account and ownership across awaits. */
- createCreationPlanValidator?(): OrcaWorkerCreationPlanValidator;
++ validateCreationPlan?: OrcaWorkerCreationPlanValidator;
readCollaborationSettings(): { workerSoftLimit: number; workerHardLimit: number };
getLeadSessionRow(leadSessionId: string): Promise<OrcaLeadSessionSnapshot | null>;
getWorkerDefaults(agent: AgentKind): OrcaWorkerDefaultsSnapshot;
@@@ -628,7 -621,12 +627,12 @@@ 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 validateCreationPlan = deps.createCreationPlanValidator?.();
- 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;
+ };
const existing = await deps.listWorkersByLead(params.leadSessionId);
if (existing.some((worker) => worker.label?.toLowerCase() === label.value)) {
@@@ -1000,23 -998,13 +1004,23 @@@
| { ok: true; occupiedSlotsBefore: number }
| { ok: false; errorCode: 'DUPLICATE_LABEL' | 'WORKER_CREATION_IN_PROGRESS' | 'WORKER_LIMIT_HARD_EXCEEDED' };
try {
- reservation = await deps.reserveWorkerCreation({
- reservationId: workerId,
- teamId: params.teamId,
- label: label.value,
- hardLimit: settings.workerHardLimit,
- leaseMs: ORCA_WORKER_CREATION_RESERVATION_LEASE_MS,
- });
+ const admit = async () => {
+ // Preparation may await providers or remote state. Re-read the plan at
+ // the final admission boundary shared with plan registration and input.
- const latestLimit = await validateCreationPlan?.(params, workingDir, resolved);
++ const latestLimit = await validatePlan(workingDir, resolved);
+ settings.workerHardLimit = deps.readCollaborationSettings().workerHardLimit;
+ if (latestLimit != null) settings.workerHardLimit = Math.min(settings.workerHardLimit, latestLimit);
+ return deps.reserveWorkerCreation({
+ reservationId: workerId,
+ teamId: params.teamId,
+ label: label.value,
+ hardLimit: settings.workerHardLimit,
+ leaseMs: ORCA_WORKER_CREATION_RESERVATION_LEASE_MS,
+ });
+ };
+ reservation = deps.withLeadSendLock
+ ? await deps.withLeadSendLock(params.leadSessionId, admit)
+ : await admit();
} catch (err) {
return toInternalFailure(err);
}
@@@ -1102,13 -1091,13 +1107,13 @@@
}
try {
- await validatePlan(workingDir, resolved);
- } catch (err) {
- await cleanupBootstrappedWorkerSession(workerSession.id);
- return toInternalFailure(err);
- }
-
- try {
+ // Bootstrap and lease renewal both await external work. Reuse the same
+ // admission validator before recording a Worker that lifecycle can dispatch.
- const finalPlanLimit = await validateCreationPlan?.(params, workingDir, resolved);
++ const finalPlanLimit = await validatePlan(workingDir, resolved);
+ if (finalPlanLimit != null && reservation.occupiedSlotsBefore >= finalPlanLimit) {
+ await cleanupBootstrappedWorkerSession(workerSession.id);
+ return { ok: false, errorCode: 'WORKER_LIMIT_HARD_EXCEEDED', message: 'Registered plan concurrency reached' };
+ }
await deps.addOrUpdateWorker({
id: workerId,
teamId: params.teamId,
diff --cc apps/desktop/src/main/maker-ipc/register.ts
index 1087782541,f34e67e365..6d01701b92
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@@ -11984,58 -11951,48 +11984,49 @@@ export function registerMakerIpc(maker
listWorkersByLead,
isActiveWorkerStatus,
readCollaborationSettings,
- createCreationPlanValidator: () => {
+ validateCreationPlan: async (params, resolvedWorkingDir, resolvedRoute) => {
const epoch = getCurrentDbClientSnapshot();
- // Keep provenance only for this create call. An in-flight plugin request
- // must not become ordinary Orca after uninstall or switch to another account.
- let originalPluginId: string | null | undefined;
- return async (params, resolvedWorkingDir, resolvedRoute) => {
- if (!epoch) throw new PluginTaskError('HOST_NOT_READY','Task storage unavailable');
- if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
- const receipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
- if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
- const currentPluginId = receipt?.operation === 'create' && !hasRevokedPluginTaskOwnership(receipt) ? receipt.pluginId : null;
- if (originalPluginId === undefined) originalPluginId = currentPluginId;
- if (currentPluginId !== originalPluginId) throw new PluginTaskError('PERMISSION_DENIED', 'Task ownership changed');
- if (!receipt || currentPluginId === null) 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 resolveAuthorizedDirectory = (requested: string) => resolvePluginWorkerDirectory({
- requested, leadDirectory: task.workingDir,
- configuredDirectory: cfg.workingDir, isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId,dir),
- assertCurrent: () => {
- if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId) || cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');
- },
- });
- const directory = await resolveAuthorizedDirectory(params.workingDir ?? task.workingDir ?? '');
- if (resolvedWorkingDir !== undefined && directory !== await resolveAuthorizedDirectory(resolvedWorkingDir)) throw new PluginTaskError('PERMISSION_DENIED','Worker directory changed during creation');
- // Drain plan registration before taking the receipt snapshot. Waiting only
- // after this read leaves a stale no-plan payload even when get() sees the
- // newly persisted plan. Keep the final task check after directory awaits.
- await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
- if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
- const currentReceipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
- if (!currentReceipt || currentReceipt.operation !== 'create' || currentReceipt.pluginId !== originalPluginId || hasRevokedPluginTaskOwnership(currentReceipt) || epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Task ownership changed');
- const data = readPluginTaskPlanReceipt(currentReceipt.payload);
- const item = data.teamPlan?.items.find((x: {label:string})=>x.label===params.label);
- const plannedDirectory = item && resolvedRoute
- ? await resolveAuthorizedDirectory(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');
- if (!data.teamPlan) return undefined; // Existing plugins retain their original behavior.
- if (!item || data.settledLabels?.includes(params.label)) throw new PluginTaskError('INVALID_REQUEST','Worker is not pending in the registered plan');
- const route = item.route;
- // 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;
- };
+ if (!epoch) throw new PluginTaskError('HOST_NOT_READY','Task storage unavailable');
+ const receipt = await createPluginTaskStore(epoch.client).get(params.leadSessionId);
++ 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');
+ assertPluginWorkerAutoAuthorized(receipt.pluginId, task);
+ const cfg = readGhostErrandConfig(receipt.pluginId);
+ const resolveAuthorizedDirectory = (requested: string) => resolvePluginWorkerDirectory({
+ requested, leadDirectory: task.workingDir,
+ configuredDirectory: cfg.workingDir, isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId,dir),
+ assertCurrent: () => {
+ if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId) || cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');
+ },
+ });
+ const directory = await resolveAuthorizedDirectory(params.workingDir ?? task.workingDir ?? '');
+ if (resolvedWorkingDir !== undefined && directory !== await resolveAuthorizedDirectory(resolvedWorkingDir)) throw new PluginTaskError('PERMISSION_DENIED','Worker directory changed during creation');
+ // Drain plan registration before taking the receipt snapshot. Waiting only
+ // after this read leaves a stale no-plan payload even when get() sees the
+ // newly persisted plan. Keep the final task check after directory awaits.
+ await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');
+ 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);
++ if (!currentReceipt || currentReceipt.operation !== 'create' || currentReceipt.pluginId !== receipt.pluginId || hasRevokedPluginTaskOwnership(currentReceipt) || epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Task ownership changed');
++ const data = readPluginTaskPlanReceipt(currentReceipt.payload);
+ const item = data.teamPlan?.items.find((x: {label:string})=>x.label===params.label);
+ const plannedDirectory = item && resolvedRoute
+ ? await resolveAuthorizedDirectory(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');
+ if (!data.teamPlan) return undefined; // Existing plugins retain their original behavior.
+ if (!item || data.settledLabels?.includes(params.label)) throw new PluginTaskError('INVALID_REQUEST','Worker is not pending in the registered plan');
+ const route = item.route;
+ // 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) => {
const db = getDbClient().drizzle;