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): avoid duplicate completion follow-up wakeups

Chris57d4362ab6b9
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts
index 782753a43d..a7b8a69ff0 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts
@@ -14,7 +14,7 @@ import type { BotGlance } from '../../../shared/botAutonomy.js';
const h = vi.hoisted(() => ({
scope: 'a', scheduler: 'sched' as string | null, ready: true,
glance: vi.fn(), refreshRemote: vi.fn(),
- readMetas: vi.fn(), readOwnership: vi.fn(),
+ readMetas: vi.fn(), readOwnership: vi.fn(), handled: vi.fn(),
}));
vi.mock('../../appSessionState.js', () => ({
activeOwnerScopeKey: () => h.scope, isAppSessionBoundaryPending: () => false,
@@ -28,7 +28,7 @@ vi.mock('../../maker-host/bot-autonomy-settings-store.js', () => ({
vi.mock('../hostData.js', () => ({
readLocalSessionMetas: h.readMetas, readTaskOwnership: h.readOwnership, readBotDirectory: vi.fn(),
}));
-import { currentFollowUpEvents, getBotAutonomyGlance, setActiveBotAutonomy } from '../hub.js';
+import { configureBotAutonomyHost, currentFollowUpEvents, getBotAutonomyGlance, setActiveBotAutonomy } from '../hub.js';
const meta = (id: string, source = 'desktop'): LocalSessionMeta => ({
id, source, title: 'Completed task', workingDir: null, status: 'active', hiddenAt: null,
@@ -40,6 +40,8 @@ const events = ['mine', 'delegated', 'shared', 'deleted'].map(subject => ({
}));
beforeEach(() => {
h.scope = 'a'; h.scheduler = 'sched'; h.ready = true;
+ h.handled.mockReset().mockResolvedValue(false);
+ configureBotAutonomyHost({ isCompletionHandledByTeammate: h.handled });
h.refreshRemote.mockReset().mockResolvedValue(undefined);
h.glance.mockReset().mockReturnValue({
botId: 'sched', scope: 'all', waiting: [], working: [], lastSweepAt: 0, doneToday: 0, offlineDevices: [],
@@ -122,3 +124,26 @@ it('returns the cached glance while a remote peer is still pending or fails', as
}
expect(await getBotAutonomyGlance('sched', undefined, false)).toBe(projection);
});
+
+// #6440 / unit: a queued finished event and a dedicated receipt previously both
+// woke the parent. Exercise the production built-in dispatch gate, preserving
+// the published event for custom routines and unrelated events in the same batch.
+it('filters only receipt-owned completion from built-in follow-up without mutating published events', async () => {
+ h.handled.mockImplementation(async id => id === 'delegated');
+ const failed = { ...events[1], event: { ...events[1].event, type: 'errored' } };
+ const batch = [...events, failed];
+ const result = await currentFollowUpEvents('sched', batch);
+ expect(result?.events).toEqual([events[0], failed]);
+ expect(result?.canDispatch()).toBe(true);
+ expect(batch).toEqual([...events, failed]);
+ expect(h.handled).toHaveBeenCalledWith('delegated', 'sched');
+});
+
+it.each(['unready', 'failed', 'account-changed'] as const)('defers a %s receipt read and retries the original completion batch', async state => {
+ if (state === 'unready') h.handled.mockResolvedValueOnce(null);
+ else if (state === 'failed') h.handled.mockRejectedValueOnce(new Error('database unavailable'));
+ else h.handled.mockImplementationOnce(async () => { h.scope = 'b'; return false; });
+ expect(await currentFollowUpEvents('sched', events)).toBeNull();
+ h.scope = 'a';
+ expect((await currentFollowUpEvents('sched', events))?.events).toEqual([events[0], events[1]]);
+});
diff --git a/apps/desktop/src/main/bot-autonomy/hub.ts b/apps/desktop/src/main/bot-autonomy/hub.ts
index 0894d1f5ce..5b24b1eb11 100644
--- a/apps/desktop/src/main/bot-autonomy/hub.ts
+++ b/apps/desktop/src/main/bot-autonomy/hub.ts
@@ -27,6 +27,8 @@ import { errorCode, type BotAutonomyInputProjection } from './taskWatch.js';
const log = createLogger('bot-autonomy');
export interface BotAutonomyHostDeps {
+ /** Same native execution has a dedicated receipt for this follower, including pending delivery. */
+ isCompletionHandledByTeammate(sessionId: string, botId: string): Promise<boolean | null>;
/** 某个本机任务当前挂起的交互请求(只读)。 */
getPendingInteractions(sessionId: string): readonly unknown[];
getMainWindow(): BrowserWindow | null;
@@ -154,7 +156,22 @@ export async function currentFollowUpEvents(botId: string, events: RoutineRun['e
});
const allowedNow = () => filterFollowUpEvents(botId, events, watch.list(),
resolveSchedulerBotId(readBotAutonomySettingsOverride(), ownership.bots), ownership.bots, Date.now(), subjects);
- const allowed = allowedNow();
+ const eligible = allowedNow();
+ // Only the built-in follow-up consumes this gate. Keep publishing host events
+ // for user-authored routines, and recheck persisted batches before model work.
+ let handled: (boolean | null)[];
+ try {
+ handled = await Promise.all(eligible.map(({ event }) => event.type === 'finished'
+ && typeof event.subject === 'string'
+ ? hostDeps.isCompletionHandledByTeammate?.(event.subject, botId) ?? Promise.resolve(null)
+ : Promise.resolve(false)));
+ } catch (error) {
+ log.warn('autonomy completion ownership deferred', { error: errorCode(error) });
+ return null;
+ }
+ if (current !== active || !scopeIsCurrent(active.scope) || watch.getBots() !== botsAtRead
+ || handled.includes(null)) return null;
+ const allowed = eligible.filter((_event, index) => !handled[index]);
return { events: allowed, canDispatch: () => current === active && scopeIsCurrent(active.scope) && watch.isReady()
- && watch.getBots() === botsAtRead && allowedNow().length === allowed.length };
+ && watch.getBots() === botsAtRead && allowedNow().length === eligible.length };
}
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 8f977380ba..6ce0cfe6c9 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -1,5 +1,5 @@
import { captureAgentRequest } from '../../../maker-ipc/forwardedRequest';
-import { admitTaskAction, TaskActionAuthorizationError } from '../../../maker-ipc/taskActionAuthorization';
+import { admitTaskAction, assertTaskActionCurrent, TaskActionAuthorizationError } from '../../../maker-ipc/taskActionAuthorization';
import { formatForwardedRequest } from '../../../../shared/forwardedRequest';
import { AcceptedCallbackDispatchCancelled, runAcceptedCallback } from '../../../maker-ipc/acceptedCallbackRunner';
import { setSessionOpeningModelAdmission } from '../../sessionOpening';
@@ -8828,6 +8828,40 @@ describe('Bot Session task end-to-end runtime', () => {
}
});
+ // #6440 / db: real start -> terminal -> retry with the original tool's expired
+ // async scope. Earlier dispatch fakes never checked the production action guard.
+ it('delivers and retries a durable completion after its starting tool scope expires', async () => {
+ await seedPair();
+ vi.useFakeTimers();
+ let current = true;
+ let rejectCompletion = true;
+ const execution = { instanceId: 'completion-scope', generation: 1 };
+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution,
+ decorateDispatch: dispatch => async params => {
+ await assertTaskActionCurrent();
+ if (params.clientId?.startsWith('bot-delegation-completion:') && rejectCompletion) {
+ rejectCompletion = false;
+ return { ok: false, errorCode: 'NOT_FOUND', message: 'temporary fixture rejection' };
+ }
+ return dispatch(params);
+ },
+ });
+ try {
+ await runOwnerAction('start_session_task', () => current, async () => {
+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Completion scope fixture.' });
+ if (!task.ok) throw new Error(task.message);
+ current = false;
+ await expect(assertTaskActionCurrent()).rejects.toThrow('TASK_ACTION_AUTHORIZATION_EXPIRED');
+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, execution, outcome: 'done', resultText: 'Scoped result' });
+ expect(h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).toBeNull();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).not.toBeNull();
+ expect(h.sqlite!.prepare("SELECT count(*) FROM messages WHERE session_id='session-1' AND client_id LIKE 'bot-delegation-completion:%'").pluck().get()).toBe(1);
+ await expect(assertTaskActionCurrent()).rejects.toThrow('TASK_ACTION_AUTHORIZATION_EXPIRED');
+ });
+ } finally { runtime.dispose(); vi.useRealTimers(); }
+ });
+
it.each(['accepted', 'rejected', 'paused', 'archived'] as const)('delegated completion notification ownership follows the durable handoff (%s)', async boundary => {
await seedPair();
let execution = { instanceId: 'notification-child', generation: 1 };
@@ -8852,9 +8886,15 @@ describe('Bot Session task end-to-end runtime', () => {
// receipt, not source=bot, an avatar, title, or a Bot Session link.
expect(h.sqlite!.prepare('SELECT source FROM sessions WHERE id=?').pluck().get(task.childSessionId)).toBe('desktop');
expect(h.sqlite!.prepare('SELECT count(*) FROM bot_session_links WHERE session_id=?').pluck().get(task.childSessionId)).toBe(0);
+ // #6440 / db: follow-up yields before settlement and during delivery
+ // failure, but only for the requester and this accepted execution.
+ const followUp = () => runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a' });
+ expect(await followUp()).toBe(true);
+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'other' })).toBe(false);
const settlement = runtime.delegation.settleSession({ childSessionId: task.childSessionId, execution, outcome: 'done', resultText: 'Final fixture result' });
const ownership = runtime.delegation.isCompletionHandledByTeammate(task.childSessionId);
await waiting;
+ expect(await followUp()).toBe(true);
let resolved = false;
void ownership.then(() => { resolved = true; });
await Promise.resolve();
@@ -8866,7 +8906,9 @@ describe('Bot Session task end-to-end runtime', () => {
expect(h.sqlite!.prepare("SELECT content FROM messages WHERE session_id='session-1' AND client_id LIKE 'bot-delegation-result:%'").pluck().get()).toBe('Final fixture result');
expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id=?').pluck().get(task.childSessionId)).toBe('active');
expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId)).toBe(boundary === 'accepted');
+ expect(await followUp()).toBe(true);
execution = { ...execution, generation: 2 };
+ expect(await followUp()).toBe(false);
expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId)).toBe(false);
} finally { release(); runtime.dispose(); }
});
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index 7d47a03a96..d46438b76e 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -2,7 +2,7 @@ import { signalBotAutonomyBotsChanged } from '../bot-autonomy/botsChangedSignal.
import { formatForwardedRequest, captureAgentRequest, type CapturedAgentRequest } from './forwardedRequest.js';
import { readForwardedRequestSource, type AgentRequestReceipt, type ForwardedRequestSource } from '../../shared/forwardedRequest.js';
import { openSession } from '../localDb/sessionOpening.js';
-import { approvedTaskDelegation, captureTaskActionGuard, captureTaskActionSyncGuard, TaskActionAuthorizationError } from './taskActionAuthorization.js';
+import { approvedTaskDelegation, captureTaskActionGuard, captureTaskActionSyncGuard, runHostCompletionDelivery, TaskActionAuthorizationError } from './taskActionAuthorization.js';
import { authorizeGroupTool, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';
import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';
import { existsSync, statSync } from 'node:fs';
@@ -1028,7 +1028,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
resultSummary?: string | null;
artifacts?: BotDelegationArtifact[];
lastError?: string | null;
- }, attempt = 0): Promise<boolean> => {
+ }, attempt = 0): Promise<boolean> => runHostCompletionDelivery(async () => {
const previousDelivery = completionInFlight.get(params.id);
if (previousDelivery) await previousDelivery.catch(() => undefined);
let releaseDelivery!: () => void;
@@ -1271,7 +1271,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
completionInFlight.delete(params.id);
}
}
- };
+ });
function scheduleCompletionRetry(
params: Parameters<typeof deliverCompletion>[0],
@@ -4347,20 +4347,29 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
return settlement;
};
- const isCompletionHandledByTeammate = async (childSessionId: string): Promise<boolean> => {
+ const isCompletionHandledByTeammate = async (
+ childSessionId: string,
+ options?: { pendingForBotId: string },
+ ): Promise<boolean> => {
const execution = deps.readSessionExecution?.(childSessionId);
if (!execution) return false;
- await terminalSettlements.get(childSessionId);
+ // Follow-up must yield to the dedicated receipt even before settlement or
+ // during delivery retries. System notifications still require accepted delivery.
+ if (!options) await terminalSettlements.get(childSessionId);
const [row] = await getDbClient().drizzle.select().from(botDelegations)
.where(eq(botDelegations.childSessionId, childSessionId)).limit(1);
- if (!row || row.status !== 'completed' || row.completionDeliveredAt == null || row.acceptedAt == null) return false;
+ if (!row || row.acceptedAt == null) return false;
const snapshot = parseRecord(row.permissionSnapshotJson);
const accepted = snapshot.taskExecution as (DelegationExecutionReceipt & { runSequence: number }) | undefined;
+ if (accepted?.runSequence !== row.runSequence || !isSameSessionExecution(accepted, execution)
+ || !sameExecution(childSessionId, execution)) return false;
+ if (options) return row.requestingBotId === options.pendingForBotId;
+ if (row.status !== 'completed' || row.completionDeliveredAt == null) return false;
const terminal = snapshot.taskTerminal as {
runSequence: number; execution: DelegationExecutionReceipt; outcome: string;
} | undefined;
- if (accepted?.runSequence !== row.runSequence || terminal?.runSequence !== row.runSequence
- || terminal.outcome !== 'done' || !isSameSessionExecution(accepted, execution)
+ if (terminal?.runSequence !== row.runSequence
+ || terminal.outcome !== 'done'
|| !isSameSessionExecution(terminal.execution, execution) || !sameExecution(childSessionId, execution)) return false;
// An archived/paused requester cannot produce a new public reply. Preserve
// the task notice in that case, including delivery failures held for resume.
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 6f0afdd886..ff5163bf99 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -3585,6 +3585,8 @@ function getPendingInteractionsForSession(sessionId: string): PendingInteraction
// 伙伴自主跟进:状态表读「等你的那句话」只取请求本身(不含 persistId 等宿主内部字段)。
configureBotAutonomyHost({
+ isCompletionHandledByTeammate: (sessionId, botId) => botDelegationServiceHolder
+ ?.isCompletionHandledByTeammate(sessionId, { pendingForBotId: botId }) ?? Promise.resolve(null),
getPendingInteractions: (sessionId) => getPendingInteractionsForSession(sessionId).map((entry) => entry.request),
});
diff --git a/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts b/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts
index 55eb856982..0dd767a170 100644
--- a/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts
+++ b/apps/desktop/src/main/maker-ipc/taskActionAuthorization.ts
@@ -169,6 +169,13 @@ export async function assertTaskActionCurrent(): Promise<void> {
await actionContext.getStore()?.assertCurrent();
}
+/** Host lifecycle only: durable completion delivery is not another invocation
+ * of the tool that started the task. Its caller must validate the persisted
+ * delegation/run and recipient; this does not authorize any Agent task action. */
+export function runHostCompletionDelivery<T>(operation: () => Promise<T>): Promise<T> {
+ return actionContext.exit(operation);
+}
+
/** Existing lifecycle callbacks can outlive the AsyncLocalStorage call itself. */
export function captureTaskActionGuard(): (() => Promise<void>) | undefined {
return actionContext.getStore()?.assertCurrent;
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index b34f79f65d..7a9b5ce527 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -678,3 +678,23 @@ it('skips revoked follow-up batches and still dispatches authorized delegated ev
expect(mock.storage.insert.mock.calls[0][0].prompt).toContain('Assigned work');
expect(mock.storage.insert.mock.calls[0][0].prompt).not.toContain('PRIVATE_OLD_SUMMARY');
});
+
+// #6440 / unit: one completion can match both built-in and explicitly configured
+// follow-up. A receipt-owned batch must skip only the former, before model work.
+it('preserves user routines while skipping receipt-owned built-in completion', async () => {
+ const engine = await getRoutineEngine();
+ engine.registerSource({ id: 'host:sessions', name: 'Sessions', status: 'listening',
+ events: [{ type: 'finished', name: 'Finished', fields: [] }] });
+ const input = { name: 'Completion', prompt: 'Handle result', enabled: true,
+ triggers: [{ id: 'done', kind: 'event' as const, sourceId: 'host:sessions', eventType: 'finished', filters: [] }] };
+ const builtin = await engine.ensureBuiltin('bot', 'follow-up', input, 'builtin-follow-up-bot');
+ const custom = await routineTools.save('bot', input);
+ if (!builtin) throw new Error('Follow-up routine was not created');
+ mock.followUpEvents.mockReturnValue([]);
+ await engine.publish('host:sessions', { id: 'done', type: 'finished', subject: 'delegated', occurredAt: Date.now(), data: {} });
+ await vi.waitFor(async () => {
+ expect((await routineTools.history('bot', builtin.id))[0]?.status).toBe('skipped');
+ expect((await routineTools.history('bot', custom.id))[0]?.status).toBe('success');
+ });
+ expect(mock.scheduler.runNow).toHaveBeenCalledOnce();
+});
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 71f2bc8a72..33dda145cd 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -561,7 +561,11 @@ Session 任务遵守同一套机制与呈现契约:
里不得出现机读文本或内部 id。
- **可靠送达**:任务终态与“完成信号尚未送达”一起持久化;只有当前发起方主任务接受后才记为
已送达。临时失败指数退避,Host 重启后重投未送达终态,固定 client id 保证重复投递不产生
- 第二条消息。
+ 第二条消息。宿主依据持久委派投递完成回执,不继承启动工具调用的临时授权上下文;父轮结束
+ 不使结果回传失效,普通工具操作的授权校验保持不变。
+- **完成只唤醒一次**:内置跟进消费 `finished` 前,按委派轮次与实际执行身份核验完成回执归属。
+ 同一执行已有发给当前跟进伙伴的专属回执时(包括尚未结算和投递重试中),不再为此启动内置跟进;
+ 完成事件仍保留供用户自建规则使用;结果、文件和可靠重试仍由原回执链交付。手动接手但无回执的任务、用户另起的执行及卡住/失败/待确认跟进保持原行为。
- **不静默丢失**:发起方的原父任务已被异常恢复流程替换时,完成信号改投该伙伴当前的
canonical Session;只有伙伴本身已暂停 / 归档才暂缓投递,此时卡片终态仍然可见,完成信号
保持未送达且不轮询重试,伙伴恢复时补投一次(实现见 `botDelegationService.ts` 的