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(orca): 排队派活的 accepted 改走交付级凭证

Zhang Yunjind9ab9208fc22
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
index 7335f5e2c3..d437ca829e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
@@ -525,6 +525,12 @@ function createDeps(overrides: Partial<OrcaTeamServiceDeps> = {}) {
},
...overrides,
};
+ // Acceptance may settle after the caller's turn: default the delivery guard to the same
+ // authority the caller wired, so a revocation still cancels unless a test splits them.
+ deps.captureDeliveryAuthority = overrides.captureDeliveryAuthority
+ ?? (deps.captureControlAuthority
+ ? async (leadSessionId) => deps.captureControlAuthority!(leadSessionId)
+ : undefined);
return {
calls,
@@ -1518,6 +1524,127 @@ describe('OrcaTeamService', () => {
},
);
+ it('delivers a queued dispatch after the issuing turn is gone', async () => {
+ let delayed: (() => void | Promise<void>) | undefined;
+ let turnAlive = true;
+ const roundGuard = vi.fn(async () => {
+ if (!turnAlive) throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
+ });
+ const deliveryGuard = vi.fn(async () => {});
+ const h = createDeps({
+ captureControlAuthority: async () => roundGuard,
+ captureDeliveryAuthority: async () => deliveryGuard,
+ dispatchWorkerMessage: vi.fn(async (params) => {
+ delayed = () =>
+ runAcceptedCallback(params.onAccepted, params.targetSessionId, 'queued-input', h.deps.log);
+ return {
+ ok: true as const,
+ mode: 'queued' as const,
+ clientId: 'queued-input',
+ dispatchOutcome: {
+ kind: 'session-dispatch' as const,
+ source: params.dispatchMeta.source,
+ dispatched: true as const,
+ wakeKind: 'queued' as const,
+ },
+ targetTitle: 'Worker',
+ targetLastUserSendAt: null,
+ };
+ }),
+ });
+
+ await expect(
+ h.service.sendToWorker({
+ callerLeadSessionId: 'lead-1',
+ targetSessionId: 'worker-session-1',
+ message: 'queued while the worker was busy',
+ }),
+ ).resolves.toMatchObject({ wakeKind: 'queued' });
+
+ // The worker drains its queue much later: the issuing turn is long over.
+ turnAlive = false;
+ await expect(delayed!()).resolves.toBeUndefined();
+
+ expect(deliveryGuard).toHaveBeenCalled();
+ expect(h.getWorker().status).toBe('running');
+ });
+
+ it('cancels a queued dispatch when delivery authority is revoked', async () => {
+ let delayed: (() => void | Promise<void>) | undefined;
+ let deliverable = true;
+ const h = createDeps({
+ captureControlAuthority: async () => async () => {},
+ captureDeliveryAuthority: async () => async () => {
+ if (!deliverable) throw new Error('Orca task is no longer deliverable');
+ },
+ dispatchWorkerMessage: vi.fn(async (params) => {
+ delayed = () =>
+ runAcceptedCallback(params.onAccepted, params.targetSessionId, 'queued-input', h.deps.log);
+ return {
+ ok: true as const,
+ mode: 'queued' as const,
+ clientId: 'queued-input',
+ dispatchOutcome: {
+ kind: 'session-dispatch' as const,
+ source: params.dispatchMeta.source,
+ dispatched: true as const,
+ wakeKind: 'queued' as const,
+ },
+ targetTitle: 'Worker',
+ targetLastUserSendAt: null,
+ };
+ }),
+ });
+
+ await h.service.sendToWorker({
+ callerLeadSessionId: 'lead-1',
+ targetSessionId: 'worker-session-1',
+ message: 'queued before the team ended',
+ });
+ deliverable = false;
+
+ await expect(delayed!()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);
+ expect(h.getWorker().status).toBe('idle');
+ });
+
+ it('retries a deferred done acknowledgement after the issuing turn ended', async () => {
+ let turnRunning = true;
+ let roundAlive = true;
+ let deliverable = true;
+ const deliveryGuard = vi.fn(async () => {
+ if (!deliverable) throw new Error('Orca task is no longer deliverable');
+ });
+ const h = createDeps({
+ getLiveSession: vi.fn(() => ({ isTurnRunning: () => turnRunning })),
+ captureDeliveryAuthority: async () => deliveryGuard,
+ });
+ h.setWorker(createWorker({ status: 'done' }));
+
+ await expect(
+ h.service.idleWorker(
+ { callerLeadSessionId: 'lead-1', workerId: 'worker-1', expectedStatus: 'done' },
+ {
+ assertCurrent: async () => {
+ if (!roundAlive) throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
+ },
+ assertDeliveryCurrent: deliveryGuard,
+ },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'WORKER_STATE_CHANGED' });
+
+ // The issuing turn ends before the worker's terminal boundary.
+ turnRunning = false;
+ roundAlive = false;
+ await h.service.handleWorkerTerminalTurn({
+ sessionId: 'worker-session-1',
+ status: 'done',
+ finalText: 'finished',
+ });
+
+ expect(deliveryGuard).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;
@@ -3642,3 +3769,99 @@ it('release closes under its own send fence and fails closed on close error',asy
expect((await service.archiveWorker({callerLeadSessionId:'lead-1',workerId:'worker-1',onlyIfIdle:true})).ok).toBe(false);
expect(deps.archiveWorkerSession).not.toHaveBeenCalled();
});
+
+describe('Orca delivery authority', () => {
+ // The delivery gate lives in register.ts. Slice it the same way the cleanup-authority
+ // suite does: real source, fake host bindings.
+ const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
+ const start = source.indexOf(' const captureOrcaDeliveryAuthority = async (');
+ const end = source.indexOf(' async function discardWorkerWorktree(', start);
+
+ function compile(initialLine: { status: string; clearedAt: number | null } | null) {
+ let line = initialLine;
+ let live: unknown = null;
+ const epoch = {
+ client: {
+ drizzle: {
+ select: () => ({
+ from: () => ({
+ where: () => ({ limit: async () => (line ? [line] : []) }),
+ }),
+ }),
+ },
+ },
+ };
+ const bindings = {
+ PluginTaskError,
+ getCurrentDbClientSnapshot: () => epoch,
+ createPluginTaskStore: () => ({ get: async () => undefined }),
+ hasRevokedPluginTaskOwnership: () => false,
+ sessions: {},
+ eq: () => ({}),
+ isAppSessionBoundaryPending: () => false,
+ maker: { getSession: () => live },
+ pluginTaskServiceForCurrentOwner: () => ({
+ get: async () => ({ status: 'active', permissionMode: 'auto' }),
+ }),
+ assertPluginWorkerAutoAuthorized: () => undefined,
+ };
+ const factory = new Function(
+ ...Object.keys(bindings),
+ ts.transpileModule(`${source.slice(start, end)}\nreturn captureOrcaDeliveryAuthority;`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText,
+ )(...Object.values(bindings)) as (leadSessionId: string) => Promise<() => Promise<void>>;
+ return {
+ setLive: (session: unknown) => {
+ live = session;
+ },
+ setLine: (next: { status: string; clearedAt: number | null } | null) => {
+ line = next;
+ },
+ authorize: () => factory('lead-1'),
+ };
+ }
+
+ const permission = (mode: string, generation: number, plan = false) => ({
+ stablePermissionModeState: { mode, generation },
+ stablePlanModeState: { enabled: plan, generation },
+ });
+
+ it('accepts a rehydrated runtime whose permission counters restarted', async () => {
+ const h = compile({ status: 'active', clearedAt: 100 });
+ h.setLive(permission('bypassPermissions', 3));
+ const assertDelivery = await h.authorize();
+
+ // Idle release + rehydrate: a new Session instance restarts its in-memory generations.
+ h.setLive(permission('bypassPermissions', 0));
+ await expect(assertDelivery()).resolves.toBeUndefined();
+
+ // A released runtime is not a revocation either.
+ 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 });
+ h.setLive(permission('bypassPermissions', 3));
+ const assertDelivery = await h.authorize();
+
+ 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');
+
+ h.setLive(permission('bypassPermissions', 0));
+ h.setLine({ status: 'active', clearedAt: 200 });
+ await expect(assertDelivery()).rejects.toThrow('Orca task is no longer deliverable');
+
+ h.setLine(null);
+ await expect(assertDelivery()).rejects.toThrow('Orca task is no longer deliverable');
+ });
+
+ 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*=>/);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
index 76d58b8121..89762acf0b 100644
--- a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
@@ -271,6 +271,11 @@ export interface WorkerTerminalTurnCapture {
/** service 的 I/O 边界。register.ts 只负责把 DB、Maker、IPC broadcast 作为依赖组合进来。 */
export interface OrcaTeamServiceDeps {
captureControlAuthority?(leadSessionId: string): Promise<() => Promise<void>>;
+ /**
+ * Delivery-scope authority for callbacks that may settle after the caller's turn ended
+ * (queued acceptance, terminal-time retries). Round-scoped authority is already expired there.
+ */
+ captureDeliveryAuthority?(leadSessionId: string): Promise<() => Promise<void>>;
getWorkerLinkBySessionId(workerSessionId: string): Promise<OrcaWorkerLinkSnapshot | null>;
getWorkerLinkByWorkerId(workerId: string): Promise<OrcaWorkerLinkSnapshot | null>;
listWorkersByLead(leadSessionId: string): Promise<OrcaWorkerRecordSnapshot[]>;
@@ -412,7 +417,7 @@ export interface OrcaTeamService {
callerLeadSessionId: string;
workerId: string;
expectedStatus?: 'done';
- }, opts?: { deferredRetry?: boolean; assertCurrent?: () => Promise<void> }): Promise<OrcaOkResult>;
+ }, opts?: { deferredRetry?: boolean; assertCurrent?: () => Promise<void>; assertDeliveryCurrent?: () => Promise<void> }): Promise<OrcaOkResult>;
/** 外部调用边界:按 caller lead 校验 worker 可见性。 */
archiveWorker(params: { callerLeadSessionId: string; workerId: string; onlyIfIdle?: boolean; beforeArchive?: () => Promise<void> }): Promise<OrcaOkResult>;
/** 外部调用边界:修改 worker 的展示角色名(role)与 team 内唯一标识(label),不改执行单元本身。 */
@@ -554,14 +559,25 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
* 下一次 done 广播仍会走 renderer 的可见性 ack 路径。done 的产品语义是
* 「保持到用户看到为止」,所以只在 renderer 已尝试过确认时补收口,不做无条件自动 ack。
*/
- const deferredDoneAcknowledgements = new Map<string, { assertCurrent?: () => Promise<void> }>();
- const deferDoneAcknowledgement = (workerId: string, assertCurrent?: () => Promise<void>) => {
+ const deferredDoneAcknowledgements = new Map<string, { assertDeliveryCurrent?: () => Promise<void> }>();
+ const deferDoneAcknowledgement = (workerId: string, assertDeliveryCurrent?: () => Promise<void>) => {
// An independent UI acknowledgement must not acquire a model caller's guard.
- if (!deferredDoneAcknowledgements.has(workerId) || deferredDoneAcknowledgements.get(workerId)?.assertCurrent) {
- deferredDoneAcknowledgements.set(workerId, { assertCurrent });
+ if (!deferredDoneAcknowledgements.has(workerId) || deferredDoneAcknowledgements.get(workerId)?.assertDeliveryCurrent) {
+ deferredDoneAcknowledgements.set(workerId, { assertDeliveryCurrent });
}
};
+ /**
+ * Deferred retries run at a later terminal boundary, where the issuing turn's guard is gone.
+ * A failed snapshot capture keeps the existing guard rather than failing the call.
+ */
+ const 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;
+
async function withWorkerTransition<T>(
workerId: string,
operation: () => Promise<T>,
@@ -906,6 +922,8 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
...(params.imagePaths ? { imagePaths: params.imagePaths } : {}),
dispatchMeta: params.dispatchMeta,
assertCurrent,
+ // Creation can queue its first task too; acceptance then lands after this call.
+ assertDeliveryCurrent: await deps.captureDeliveryAuthority?.(link.leadSessionId),
});
return mapNormalDispatchResult(target, execution);
}
@@ -967,6 +985,8 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
imagePaths?: string[];
dispatchMeta: DispatchWorkerTaskParams['dispatchMeta'];
assertCurrent?: () => Promise<void>;
+ /** Rechecked when the target accepts, possibly after the caller's turn is over. */
+ assertDeliveryCurrent?: () => Promise<void>;
}): Promise<ResolvedWorkerDispatchExecution> {
const { worker: target, link } = params.resolved;
await reserveWorkerDispatch(target.id);
@@ -1036,13 +1056,19 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
settled?.resolveSettlement({ outcome: 'committed' });
};
const onAccepted = async (): Promise<void> => {
+ // Fail closed: without a delivery guard, keep the round check instead of skipping it.
+ const assertAcceptedCurrent = params.assertDeliveryCurrent ?? params.assertCurrent;
try {
- await params.assertCurrent?.();
+ // Acceptance can land after the caller's turn ended (queued item, cold resume).
+ await assertAcceptedCurrent?.();
await withWorkerTransition(target.id, async () => {
const currentWorkers = await deps.listWorkersByLead(link.leadSessionId);
const currentWorker = currentWorkers.find((worker) => worker.id === target.id);
+ // The store lists only active teams and worker sessions: absence is a real
+ // revocation (team ended / worker archived), not a stale turn.
+ if (!currentWorker) throw new Error('worker no longer belongs to an active team');
acceptedSnapshot = {
- previousStatus: currentWorker?.status ?? target.status,
+ previousStatus: currentWorker.status,
previousPending: autoBridge.get(target.sessionId),
previousManualInterrupt: deps.getManualInterrupt(target.sessionId),
};
@@ -1067,7 +1093,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
deps.broadcastOrcaWorkerChanged(link.leadSessionId);
await markPendingReady(target.sessionId, currentPending);
});
- await params.assertCurrent?.();
+ await assertAcceptedCurrent?.();
} catch (err) {
try {
await rollbackAccepted();
@@ -1212,6 +1238,9 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
};
}
const assertCurrent = captured ?? await deps.captureControlAuthority?.(params.callerLeadSessionId);
+ // A queued item is accepted only when the worker drains it, which can be long after this
+ // turn ended: that callback must use the delivery guard instead.
+ const assertDeliveryCurrent = await deps.captureDeliveryAuthority?.(params.callerLeadSessionId);
const resolved = await resolveWorkerRef(params.callerLeadSessionId, params.targetSessionId);
if (!resolved.ok) {
return {
@@ -1230,6 +1259,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
...(params.delivery ? { delivery: params.delivery } : {}),
...(params.imagePaths ? { imagePaths: params.imagePaths } : {}),
assertCurrent,
+ assertDeliveryCurrent,
dispatchMeta: {
source: 'maker-ipc/collab',
context:
@@ -1282,7 +1312,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
* 否则 fire-once 契约被打破,且该 terminal 边界之后未必还有下一个 terminal
* 事件来消费,worker 会带着悬置登记卡回 done(正是本机制要修的状态)。
*/
- opts?: { deferredRetry?: boolean; assertCurrent?: () => Promise<void> },
+ opts?: { deferredRetry?: boolean; assertCurrent?: () => Promise<void>; assertDeliveryCurrent?: () => Promise<void> },
): Promise<OrcaOkResult> {
const found = await resolveWorkerRef(params.callerLeadSessionId, params.workerId);
if (!found.ok) return workerRefFailureForControl(params.workerId, found);
@@ -1310,7 +1340,8 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
// 回报 settle 先落库、worker 自己的 turn 还在收尾:登记后由 terminal 边界重试(#3153)。
// terminal 重试自身被拒时不登记(见 idleWorker 的 opts 注释)。
if (params.expectedStatus === 'done' && !opts?.deferredRetry) {
- deferDoneAcknowledgement(worker.id, opts?.assertCurrent);
+ // The retry runs at a later terminal boundary: keep the delivery guard, not the turn's.
+ deferDoneAcknowledgement(worker.id, await captureDeferredAuthority(params.callerLeadSessionId, opts));
}
return {
ok: false,
@@ -1320,7 +1351,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
}
if (params.expectedStatus && deps.hasSendToSessionLock(worker.sessionId)) {
if (params.expectedStatus === 'done' && !opts?.deferredRetry) {
- deferDoneAcknowledgement(worker.id, opts?.assertCurrent);
+ deferDoneAcknowledgement(worker.id, await captureDeferredAuthority(params.callerLeadSessionId, opts));
}
return {
ok: false,
@@ -2076,7 +2107,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
// 即 ack」在 active-turn 守卫处被拒后没有重试闭环,worker 会永久停在 done
// (runtime/attention 悬置)。这里在该 turn 的 terminal 边界补一次收口;
// 没登记过被拒确认的 done 保持原样(维持「done 保持到用户看到为止」语义)。
- retryAuthority = deferredDoneAcknowledgements.get(link.workerId)?.assertCurrent;
+ retryAuthority = deferredDoneAcknowledgements.get(link.workerId)?.assertDeliveryCurrent;
retryAcknowledgeDone =
worker.status === 'done' && deferredDoneAcknowledgements.delete(link.workerId);
clearRuntimeState(params.sessionId);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bf88cb1401..d69afed74b 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -15122,6 +15122,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const orcaTeamService = createOrcaTeamService(orcaRemoteWorkers.wrapTeamDeps({
captureControlAuthority: async (leadSessionId) => (await captureOrcaPluginAuthority(leadSessionId)).assertCurrent,
+ // Queued dispatch acceptance and terminal-time retries land after this turn is gone.
+ captureDeliveryAuthority: (leadSessionId) => captureOrcaDeliveryAuthority(leadSessionId),
withSessionSendLock: withSendToSessionLock,
getWorkerLinkBySessionId: (workerSessionId) => getWorkerLink({ workerSessionId }),
getWorkerLinkByWorkerId: (workerId) => getWorkerLink({ workerId }),
@@ -15477,6 +15479,63 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return { permissionMode: pluginId === null ? undefined : 'auto' as const, assertCurrent };
};
+ /**
+ * Delivery-scope authority for Orca callbacks that can settle after the caller's turn ended
+ * (queued acceptance, terminal-time retries). Durable facts only: the round-scoped guard from
+ * `captureOrcaPluginAuthority` is already expired there, and a released runtime is not a
+ * revocation. See docs/dev-rules/orca-team-architecture.md「派发与排队」#10.
+ */
+ const captureOrcaDeliveryAuthority = async (leadSessionId: string) => {
+ const epoch = getCurrentDbClientSnapshot();
+ if (!epoch) throw new PluginTaskError('HOST_NOT_READY', 'Task storage unavailable', true);
+ const store = createPluginTaskStore(epoch.client);
+ const receipt = await store.get(leadSessionId);
+ 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 })
+ .from(sessions)
+ .where(eq(sessions.id, leadSessionId))
+ .limit(1);
+ return row ?? null;
+ };
+ 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.
+ const permissionAtCapture = liveAtCapture?.stablePermissionModeState && liveAtCapture.stablePlanModeState
+ ? {
+ mode: liveAtCapture.stablePermissionModeState.mode,
+ planEnabled: liveAtCapture.stablePlanModeState.enabled,
+ }
+ : null;
+ return async () => {
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ if (isAppSessionBoundaryPending()) throw new PluginTaskError('HOST_NOT_READY', 'Account is switching');
+ const current = await store.get(leadSessionId);
+ const currentPluginId = current?.operation === 'create' && !hasRevokedPluginTaskOwnership(current) ? current.pluginId : null;
+ if (epoch !== getCurrentDbClientSnapshot() || currentPluginId !== pluginId) throw new PluginTaskError('PERMISSION_DENIED', 'Orca task ownership changed');
+ 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) {
+ 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))
+ throw new PluginTaskError('PERMISSION_DENIED', 'Task permissions changed before delivery');
+ }
+ if (pluginId === null) return;
+ const task = await pluginTaskServiceForCurrentOwner!().get(pluginId, leadSessionId);
+ if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
+ assertPluginWorkerAutoAuthorized(pluginId, task);
+ };
+ };
+
async function discardWorkerWorktree(sessionId: string): Promise<void> {
await withSendToSessionLock(sessionId, async () => {
await worktreeManager.awaitBackgroundCheckout(sessionId);