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(bots): revalidate delegation permission generation before dispatch

zqchris21fa3358cdee
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index ef9cb51b1e..170630088d 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -3465,6 +3465,71 @@ describe('Bot Session task end-to-end runtime', () => {
}
});
+ it.each(['ask', 'bypassPermissions', null])('revalidates permission generation after asynchronous child creation: %s', async (mode) => {
+ await seedPair();
+ let permission: { mode: string; generation: number } | null = { mode: 'bypassPermissions', generation: 1 };
+ const originalTx = h.tx!;
+ let persisted = false;
+ let release!: () => void;
+ const pendingReply = new Promise<void>((resolve) => { release = resolve; });
+ h.tx = async (name, args) => {
+ const result = await originalTx(name, args);
+ if (name === 'bots.createDelegation') {
+ persisted = true;
+ await pendingReply;
+ }
+ return result;
+ };
+ const runtime = createDelegationRuntime({ readCallerPermission: () => permission });
+ const starting = runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Do not retain stale Full Access.' });
+ try {
+ await vi.waitFor(() => expect(persisted).toBe(true));
+ permission = mode === null ? null : { mode, generation: 2 };
+ release();
+ expect(await starting).toMatchObject({ ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE' });
+ expect(runtime.started).toEqual([]);
+ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE parent_session_id = ?').pluck().get('session-1')).toBe('ask');
+ expect(h.sqlite!.prepare('SELECT status FROM bot_delegations').pluck().get()).toBe('failed');
+ } finally {
+ release();
+ await starting;
+ h.tx = originalTx;
+ runtime.dispose();
+ }
+ });
+
+ it('rechecks permission after the asynchronous dispatch-plan reads', async () => {
+ await seedPair();
+ let permission = { mode: 'bypassPermissions', generation: 1 };
+ const realSelect = h.db!.select.bind(h.db!);
+ let crossedDispatchBoundary = false;
+ const select = vi.spyOn(h.db!, 'select').mockImplementation((fields) => {
+ const query = realSelect(fields);
+ // Keep the real SQLite query, but model a user change while the worker
+ // replies to validateDispatchPlan's final child-status read.
+ if (fields?.status === sessions.status && fields?.source === sessions.source) {
+ crossedDispatchBoundary = true;
+ queueMicrotask(() => { permission = { mode: 'ask', generation: 2 }; });
+ }
+ return query;
+ });
+ const runtime = createDelegationRuntime({ readCallerPermission: () => permission });
+ try {
+ const result = await runtime.delegation.startSessionTask({
+ callerSessionId: 'session-1', objective: 'Run the requested checks.',
+ });
+ expect(crossedDispatchBoundary).toBe(true);
+ expect(result).toMatchObject({ status: 'failed' });
+ // Failure wakes the parent with the completion notice, never the child.
+ expect(runtime.started.map((turn) => turn.sessionId)).toEqual(['session-1']);
+ expect(h.sqlite!.prepare('SELECT permission_mode, status FROM sessions WHERE parent_session_id = ?')
+ .get('session-1')).toMatchObject({ permission_mode: 'ask', status: 'archived' });
+ } finally {
+ select.mockRestore();
+ runtime.dispose();
+ }
+ });
+
it('does not start a child with stale permissions during a live permission change', async () => {
await seedPair();
const runtime = createDelegationRuntime({ readCallerPermission: () => null });
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index 4177450297..7cc27f0711 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -112,7 +112,7 @@ export interface BotDelegationServiceDeps {
'model' | 'agentKind' | 'providerId' | 'fastMode'
> & { effort?: (typeof sessions.$inferSelect)['effort'] }) | null;
/** null means the live permission is changing or the caller is closing. */
- readCallerPermission?: (sessionId: string) => string | null;
+ readCallerPermission?: (sessionId: string) => string | { mode: string; generation: number } | null;
now?: () => number;
createId?: () => string;
maxActiveChildren?: number;
@@ -1126,12 +1126,12 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
return { ok: true };
};
- function scheduleDispatchRetry(delegationId: string, attempt: number): void {
+ function scheduleDispatchRetry(delegationId: string, attempt: number, isCreationPermissionCurrent?: () => boolean): void {
clearRetryTimer(delegationId);
const delay = Math.min(MAX_RETRY_DELAY_MS, 1_000 * 2 ** Math.min(attempt, 6));
const timer = setTimeout(() => {
retryTimers.delete(delegationId);
- void attemptDispatch(delegationId, attempt + 1);
+ void attemptDispatch(delegationId, attempt + 1, isCreationPermissionCurrent);
}, delay);
timer.unref?.();
retryTimers.set(delegationId, timer);
@@ -1163,6 +1163,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
async function attemptDispatch(
delegationId: string,
attempt = 0,
+ isCreationPermissionCurrent?: () => boolean,
): Promise<{
ok: boolean;
status: 'queued' | 'running' | 'failed';
@@ -1187,6 +1188,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
await failDelegationDispatch(row, `${validation.errorCode}: ${validation.message}`);
return { ok: false, status: 'failed' };
}
+ if (isCreationPermissionCurrent && !isCreationPermissionCurrent()) {
+ await db.update(sessions).set({ permissionMode: 'ask' }).where(eq(sessions.id, row.childSessionId));
+ await failDelegationDispatch(row, 'CALLER_PERMISSION_UNAVAILABLE: 伙伴权限已变更,任务未启动');
+ return { ok: false, status: 'failed' };
+ }
const dispatched = await deps.dispatch({
targetSessionId: row.childSessionId,
message: buildDelegationPrompt(row),
@@ -1261,7 +1267,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
childSessionId: retrying.childSessionId,
status: 'queued',
});
- scheduleDispatchRetry(retrying.id, attempt);
+ scheduleDispatchRetry(retrying.id, attempt, isCreationPermissionCurrent);
}
return { ok: false, status: 'queued', error: dispatched };
}
@@ -1532,7 +1538,15 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
if (callerPermission === null) {
return { ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE', message: '伙伴权限正在切换或任务正在关闭,请稍后重试' };
}
- const permissionMode = permissionModeOrAsk(callerPermission);
+ const permissionMode = permissionModeOrAsk(typeof callerPermission === 'string' ? callerPermission : callerPermission.mode);
+ const isCreationPermissionCurrent = (): boolean => {
+ if (!deps.readCallerPermission) return true;
+ const current = deps.readCallerPermission(input.callerSessionId);
+ if (current === null) return false;
+ if (typeof callerPermission === 'string') return current === callerPermission;
+ return typeof current !== 'string' && current.mode === callerPermission.mode
+ && current.generation === callerPermission.generation;
+ };
const plan: BotDelegationPlanSnapshot = {
...input.plan,
permission: {
@@ -1566,23 +1580,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
title: input.session.title,
source: input.session.source,
};
- const liveCallerPermission = (): string | null =>
- deps.readCallerPermission
- ? deps.readCallerPermission(input.callerSessionId)
- : input.caller.permissionMode;
- const rejectStaleCallerPermission = async () => {
- await updateTerminal({
- delegationId,
- status: 'failed',
- lastError: 'CALLER_PERMISSION_UNAVAILABLE: 伙伴权限已变更,任务未启动',
- abortChild: true,
- });
- return {
- ok: false as const,
- errorCode: 'CALLER_PERMISSION_UNAVAILABLE',
- message: '伙伴权限正在切换或任务正在关闭,请稍后重试',
- };
- };
try {
await getDbClient().tx('bots.createDelegation', {
maxActiveChildren,
@@ -1619,10 +1616,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
createdAt,
},
});
- // Persistence itself is asynchronous (worker RPC). Recheck the live
- // permission generation/mode before the child becomes visible or starts.
- if (liveCallerPermission() !== callerPermission) {
- return await rejectStaleCallerPermission();
+ // The worker transaction yields: a permission switch may complete while
+ // creation is pending. Never publish or start the stale Full Access child.
+ if (!isCreationPermissionCurrent()) {
+ await getDbClient().drizzle.update(sessions)
+ .set({ permissionMode: 'ask' }).where(eq(sessions.id, childSessionId));
+ await updateTerminal({ delegationId, status: 'failed',
+ lastError: 'CALLER_PERMISSION_UNAVAILABLE', abortChild: true });
+ return { ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE', message: '伙伴权限正在切换或任务正在关闭,请稍后重试' };
}
emitChanged({
delegationId,
@@ -1676,10 +1677,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
};
}
scheduleTimeout(delegationId, plan.limits.deadlineAt);
- if (liveCallerPermission() !== callerPermission) {
- return await rejectStaleCallerPermission();
- }
- const dispatchResult = await attemptDispatch(delegationId);
+ const dispatchResult = await attemptDispatch(delegationId, 0, isCreationPermissionCurrent);
return {
ok: true,
delegationId,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index eaa625fa82..30ad1d6059 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -9160,8 +9160,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
botDelegationServiceHolder?.dispose();
botDelegationServiceHolder = createBotDelegationService({
- readCallerPermission: (sessionId) =>
- maker.getSession(sessionId)?.stablePermissionModeState?.mode ?? null,
+ readCallerPermission: (sessionId) => {
+ const state = maker.getSession(sessionId)?.stablePermissionModeState;
+ return state?.mode ? { mode: state.mode, generation: state.generation } : null;
+ },
readCallerRuntime: (sessionId) => {
const session = maker.getSession(sessionId);
return session ? {