Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(orca): 交付凭证在权限切换时 fail closed,UI 确认不取凭证
Zhang Yunjin92aeb8a30504
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.tsindex d437ca829e..468ecab1f8 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts@@ -1645,6 +1645,33 @@ describe('OrcaTeamService', () => {expect(h.getWorker().status).toBe('idle');});+ it('does not acquire delivery authority for an independent UI acknowledgement', async () => {+ let turnRunning = true;+ const captureDeliveryAuthority = vi.fn(async () => async () => {+ throw new Error('Orca task is no longer deliverable');+ });+ const h = createDeps({+ getLiveSession: vi.fn(() => ({ isTurnRunning: () => turnRunning })),+ captureDeliveryAuthority,+ });+ h.setWorker(createWorker({ status: 'done' }));++ // A renderer confirmation carries no caller guard, so it keeps the no-credential semantics.+ await expect(+ h.service.idleWorker({ callerLeadSessionId: 'lead-1', workerId: 'worker-1', expectedStatus: 'done' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'WORKER_STATE_CHANGED' });++ turnRunning = false;+ await h.service.handleWorkerTerminalTurn({+ sessionId: 'worker-session-1',+ status: 'done',+ finalText: 'finished',+ });++ expect(captureDeliveryAuthority).not.toHaveBeenCalled();+ expect(h.getWorker().status).toBe('idle');+ });+it('does not let an older provisional rollback overwrite a newer manual interrupt', async () => {let accepted: (() => void | Promise<void>) | undefined;let rollback: (() => void | Promise<void>) | undefined;@@ -3777,7 +3804,9 @@ describe('Orca delivery authority', () => {const start = source.indexOf(' const captureOrcaDeliveryAuthority = async (');const end = source.indexOf(' async function discardWorkerWorktree(', start);- function compile(initialLine: { status: string; clearedAt: number | null } | null) {+ type Row = { status: string; clearedAt: number | null; permissionMode: string; planModeEnabled: boolean };++ function compile(initialLine: Row | null) {let line = initialLine;let live: unknown = null;const epoch = {@@ -3807,7 +3836,8 @@ describe('Orca delivery authority', () => {};const factory = new Function(...Object.keys(bindings),- ts.transpileModule(`${source.slice(start, end)}\nreturn captureOrcaDeliveryAuthority;`, {+ ts.transpileModule(`${source.slice(start, end)}+return captureOrcaDeliveryAuthority;`, {compilerOptions: { target: ts.ScriptTarget.ES2022 },}).outputText,)(...Object.values(bindings)) as (leadSessionId: string) => Promise<() => Promise<void>>;@@ -3815,7 +3845,7 @@ describe('Orca delivery authority', () => {setLive: (session: unknown) => {live = session;},- setLine: (next: { status: string; clearedAt: number | null } | null) => {+ setLine: (next: Row | null) => {line = next;},authorize: () => factory('lead-1'),@@ -3826,9 +3856,16 @@ describe('Orca delivery authority', () => {stablePermissionModeState: { mode, generation },stablePlanModeState: { enabled: plan, generation },});+ const row = (overrides: Partial<Row> = {}): Row => ({+ status: 'active',+ clearedAt: 100,+ permissionMode: 'bypassPermissions',+ planModeEnabled: false,+ ...overrides,+ });it('accepts a rehydrated runtime whose permission counters restarted', async () => {- const h = compile({ status: 'active', clearedAt: 100 });+ const h = compile(row());h.setLive(permission('bypassPermissions', 3));const assertDelivery = await h.authorize();@@ -3836,24 +3873,50 @@ describe('Orca delivery authority', () => {h.setLive(permission('bypassPermissions', 0));await expect(assertDelivery()).resolves.toBeUndefined();- // A released runtime is not a revocation either.+ // A released runtime is not a revocation on its own: the persisted mode still matches.h.setLive(null);await expect(assertDelivery()).resolves.toBeUndefined();});- it('rejects delivery when the task or its permissions really changed', async () => {- const h = compile({ status: 'active', clearedAt: 100 });+ it('rejects delivery while the owner is switching permissions or when the mode changed', async () => {+ const h = compile(row());h.setLive(permission('bypassPermissions', 3));const assertDelivery = await h.authorize();+ // Mid-switch: the stable snapshots disappear. Work must not start on the old snapshot.+ h.setLive({+ stablePermissionModeState: null,+ stablePlanModeState: { enabled: false, generation: 0 },+ });+ await expect(assertDelivery()).rejects.toThrow('Task permissions are changing');+h.setLive(permission('ask', 0));await expect(assertDelivery()).rejects.toThrow('Task permissions changed before delivery');h.setLive(permission('bypassPermissions', 0, true));await expect(assertDelivery()).rejects.toThrow('Task permissions changed before delivery');+ });++ it('compares the persisted mode when the runtime is gone', async () => {+ const h = compile(row());+ h.setLive(permission('bypassPermissions', 3));+ const assertDelivery = await h.authorize();+ h.setLive(null);++ h.setLine(row({ permissionMode: 'ask' }));+ await expect(assertDelivery()).rejects.toThrow('Task permissions changed before delivery');++ h.setLine(row({ planModeEnabled: true }));+ await expect(assertDelivery()).rejects.toThrow('Task permissions changed before delivery');+ });++ it('rejects delivery when the task really changed', async () => {+ const h = compile(row());+ h.setLive(permission('bypassPermissions', 3));+ const assertDelivery = await h.authorize();h.setLive(permission('bypassPermissions', 0));- h.setLine({ status: 'active', clearedAt: 200 });+ h.setLine(row({ clearedAt: 200 }));await expect(assertDelivery()).rejects.toThrow('Orca task is no longer deliverable');h.setLine(null);@@ -3861,7 +3924,6 @@ describe('Orca delivery authority', () => {});it('is wired into the Orca team service', () => {- const teamService = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');- expect(teamService).toMatch(/captureDeliveryAuthority:\s*\(leadSessionId\)\s*=>/);+ expect(source).toMatch(/captureDeliveryAuthority:\s*\(leadSessionId\)\s*=>/);});});diff --git a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts b/apps/desktop/src/main/maker-ipc/orcaTeamService.tsindex 89762acf0b..b95a137e82 100644--- a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts+++ b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts@@ -574,9 +574,14 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServicconst captureDeferredAuthority = async (leadSessionId: string,opts?: { assertCurrent?: () => Promise<void>; assertDeliveryCurrent?: () => Promise<void> },- ): Promise<(() => Promise<void>) | undefined> => opts?.assertDeliveryCurrent- ?? await deps.captureDeliveryAuthority?.(leadSessionId).catch(() => undefined)- ?? opts?.assertCurrent;+ ): Promise<(() => Promise<void>) | undefined> => {+ // An independent UI acknowledgement carries no caller authority: it must keep the+ // no-credential semantics, otherwise a later permission change strands the worker on done.+ if (!opts?.assertCurrent && !opts?.assertDeliveryCurrent) return undefined;+ return opts.assertDeliveryCurrent+ ?? await deps.captureDeliveryAuthority?.(leadSessionId).catch(() => undefined)+ ?? opts.assertCurrent;+ };async function withWorkerTransition<T>(workerId: string,diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex d69afed74b..35b140e7e5 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -15493,7 +15493,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const pluginId = receipt?.operation === 'create' && !hasRevokedPluginTaskOwnership(receipt) ? receipt.pluginId : null;const readSessionRow = async () => {const [row] = await epoch.client.drizzle- .select({ status: sessions.status, clearedAt: sessions.clearedAt })+ .select({+ status: sessions.status,+ clearedAt: sessions.clearedAt,+ permissionMode: sessions.permissionMode,+ planModeEnabled: sessions.planModeEnabled,+ }).from(sessions).where(eq(sessions.id, leadSessionId)).limit(1);@@ -15501,14 +15506,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)};const sessionAtCapture = await readSessionRow();const liveAtCapture = maker.getSession(leadSessionId);- // Permission generation counters are per Session instance, so only the persisted semantics- // are comparable across a released/rehydrated runtime.+ // Permission baselines are persisted semantics: instance generation counters restart on+ // rehydrate, so they can never be compared across a released runtime. Fall back to the row+ // when the runtime has no stable snapshot at admission.const permissionAtCapture = liveAtCapture?.stablePermissionModeState && liveAtCapture.stablePlanModeState? {mode: liveAtCapture.stablePermissionModeState.mode,planEnabled: liveAtCapture.stablePlanModeState.enabled,}- : null;+ : sessionAtCapture+ ? {+ mode: sessionAtCapture.permissionMode,+ planEnabled: sessionAtCapture.planModeEnabled,+ }+ : null;return async () => {if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');if (isAppSessionBoundaryPending()) throw new PluginTaskError('HOST_NOT_READY', 'Account is switching');@@ -15518,16 +15529,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const row = await readSessionRow();if (!row || row.status === 'deleted' || row.clearedAt !== (sessionAtCapture?.clearedAt ?? null))throw new PluginTaskError('PERMISSION_DENIED', 'Orca task is no longer deliverable');- // An absent runtime is released or not rehydrated yet, never a revocation.const live = maker.getSession(leadSessionId);- if (live && permissionAtCapture) {+ if (live) {const permission = live.stablePermissionModeState;const plan = live.stablePlanModeState;- // An in-flight mode/Plan switch (null stable state) is not observable as a revocation.- if (permission && plan- && (permission.mode !== permissionAtCapture.mode- || plan.enabled !== permissionAtCapture.planEnabled))+ // A permission/Plan switch in flight is a live revocation: never start work on the old+ // snapshot while the owner is changing it.+ if (!permission || !plan)+ throw new PluginTaskError('PERMISSION_DENIED', 'Task permissions are changing');+ if (permissionAtCapture && (permission.mode !== permissionAtCapture.mode+ || plan.enabled !== permissionAtCapture.planEnabled))throw new PluginTaskError('PERMISSION_DENIED', 'Task permissions changed before delivery');+ } else if (permissionAtCapture+ && (row.permissionMode !== permissionAtCapture.mode+ || row.planModeEnabled !== permissionAtCapture.planEnabled)) {+ // An absent runtime is released or not rehydrated yet, not a revocation by itself —+ // but the persisted row is then the only authority left to compare against.+ throw new PluginTaskError('PERMISSION_DENIED', 'Task permissions changed before delivery');}if (pluginId === null) return;const task = await pluginTaskServiceForCurrentOwner!().get(pluginId, leadSessionId);diff --git a/docs/dev-rules/orca-team-architecture.md b/docs/dev-rules/orca-team-architecture.mdindex d363d7d43d..f4990f0055 100644--- a/docs/dev-rules/orca-team-architecture.md+++ b/docs/dev-rules/orca-team-architecture.md@@ -437,7 +437,9 @@ Worker turn 被 vendor 报终止型 error,但 interrupted-turn auto-resume 仍排队消息的 accepted 回调要等目标排空队列才跑,此时发起它的那一轮早已结束;因此它只能复核交付级不变量(账号 epoch、会话行仍 active 且 `cleared_at` 未变、任务归属未变、权限档未被撤销、Worker 仍属于该 Lead 的活跃团队),不能复用轮次级凭证(本轮输入来源、`turnOrigin`)。- 运行时被释放/重建不算撤销:会话行与权限按准入快照比对,不能比 live 会话实例。+ 运行时被释放/重建本身不算撤销:权限按持久化的 permission mode / Plan 与准入快照比对+ (不能比 live 会话的 generation 计数——它随实例重建归零);权限档正在切换(stable 快照为空)+ 时拒绝投递。独立 UI 的 done 确认不带调用方凭证,不取交付凭证。只有身份/归属/权限真的变了才取消,并按既有 rollback 恢复;accepted 里的状态写与广播失败仍走既有失败路径(簿记失败是否该取消投递是另一个议题,另单处理)。同步控制面(归档、结束团队、改名、切焦点、队列增删改)仍用轮次凭证。实现指针:`register.ts` 的 `captureOrcaPluginAuthority`(轮次)与