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): retry completion delivery when prerequisite reads fail

xd6cba783dcb7b
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 2dff4e93a2..57037c229e 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -9355,6 +9355,85 @@ describe('Bot Session task end-to-end runtime', () => {
} finally { runtime.dispose(); vi.useRealTimers(); }
});
+ it.each((['pending', 'snapshot', 'after-result'] as const).flatMap(stage =>
+ (['retry', 'restart'] as const).map(recovery => ({ stage, recovery })),
+ ))(
+ 'recovers completion after a $stage read timeout via $recovery without duplicate wake-ups', async ({ stage, recovery }) => {
+ await seedPair();
+ vi.useFakeTimers();
+ const execution = { instanceId: 'completion-read-timeout', generation: 1 };
+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });
+ let restarted: ReturnType<typeof createDelegationRuntime> | undefined;
+ const originalDb = h.db;
+ try {
+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Report the completed result.' });
+ if (!task.ok) throw new Error(task.message);
+ const resultCount = () => h.sqlite!.prepare(
+ "SELECT count(*) FROM messages WHERE session_id='session-1' AND client_id LIKE 'bot-delegation-result:%'",
+ ).pluck().get();
+ const wakeCount = () => h.sqlite!.prepare(
+ "SELECT count(*) FROM messages WHERE session_id='session-1' AND client_id LIKE 'bot-delegation-completion:%'",
+ ).pluck().get();
+ const delivered = () => h.sqlite!.prepare(
+ 'SELECT completion_delivered_at FROM bot_delegations WHERE id=?',
+ ).pluck().get(task.delegationId);
+ let failures = 0;
+ // Use the production async query proxy: both the initial delivery and
+ // its timer must handle a rejected worker read, not just sync SQLite.
+ const transport: DbTransport = {
+ async send<R>(op: string, args: unknown): Promise<R> {
+ const { sql, params } = args as { sql: string; params: unknown[] };
+ const pendingRead = sql.startsWith('select "status", "child_session_id", "run_sequence", "completion_delivered_at" from "bot_delegations"');
+ const snapshotRead = sql.startsWith('select "permission_snapshot_json" from "bot_delegations"');
+ if (failures < 2 && (stage === 'snapshot' ? snapshotRead
+ : pendingRead && (stage === 'pending' || resultCount() === 1))) {
+ failures++;
+ throw new Error('db-worker RPC timeout after 30000ms');
+ }
+ const statement = h.sqlite!.prepare(sql);
+ if (op === 'rawAll') return statement.raw().all(...params) as R;
+ if (op === 'rawGet') return statement.raw().get(...params) as R;
+ if (op === 'run') return statement.run(...params) as R;
+ throw new Error(`unexpected completion operation: ${op}`);
+ },
+ on() {}, onTerminated() {}, async close() {},
+ };
+ h.db = createDrizzleProxy(transport);
+ await expect(runtime.settleChild(task.childSessionId, 'Completed output', execution)).resolves.toBeUndefined();
+ expect(failures).toBe(1);
+ expect(delivered()).toBeNull();
+ expect(wakeCount()).toBe(0);
+ // Ownership suppresses autonomous follow-up while reliable delivery
+ // retries; it must not be mistaken for evidence of a successful send.
+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a', execution })).toBe(true);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(failures).toBe(2);
+ expect(delivered()).toBeNull();
+ expect(wakeCount()).toBe(0);
+ if (recovery === 'restart') {
+ runtime.dispose();
+ restarted = createDelegationRuntime({ readSessionExecution: () => execution });
+ await restarted.delegation.restore();
+ } else {
+ await vi.advanceTimersByTimeAsync(1_999);
+ expect(wakeCount()).toBe(0);
+ await vi.advanceTimersByTimeAsync(1);
+ }
+ expect(delivered()).not.toBeNull();
+ expect(resultCount()).toBe(1);
+ expect(wakeCount()).toBe(1);
+ runtime.dispose(); restarted?.dispose();
+ restarted = createDelegationRuntime({ readSessionExecution: () => execution });
+ await restarted.delegation.restore();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(resultCount()).toBe(1);
+ expect(wakeCount()).toBe(1);
+ } finally {
+ runtime.dispose(); restarted?.dispose(); h.db = originalDb; vi.useRealTimers();
+ }
+ },
+ );
+
// #6737 review / db: accepted input is not a terminal receipt. Fail both
// sides of terminal persistence; follow-up must not be consumed as handled.
it.each(['terminal', 'status'] as const)('does not consume completion when %s persistence fails', async stage => {
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index 1163ca6cb2..cd2d689518 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -1037,48 +1037,47 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
});
completionInFlight.set(params.id, thisDelivery);
try {
- const completionStillPending = async (): Promise<boolean> => {
- const [current] = await getDbClient().drizzle
- .select({
- status: botDelegations.status,
- childSessionId: botDelegations.childSessionId,
- runSequence: botDelegations.runSequence,
- completionDeliveredAt: botDelegations.completionDeliveredAt,
- })
- .from(botDelegations)
- .where(eq(botDelegations.id, params.id))
- .limit(1);
- return !!current
- && current.status === params.status
- && current.childSessionId === params.childSessionId
- && current.runSequence === params.runSequence
- && current.completionDeliveredAt === null;
- };
- // A retry from an earlier run may fire while the same task card is being
- // continued. Never let that stale receipt wake or mark the new run.
- if (!(await completionStillPending())) {
- clearCompletionRetryTimer(params.id);
- return false;
- }
- const artifacts = params.artifacts ?? [];
- // 发给模型的回执正文不带 [UI_ACTION_TRIGGER] 前缀;前缀只留在落库 / 排队可见内容上,
- // 让这条主机内部消息在时间线与排队区保持隐藏(同 botDirectMessageService 的私信)。
- // 正文有界(结果摘要 / 文件清单截断):完整结果在下面持久化的回执行里,模型按需读取。
- const completionSnapshot = (await getDbClient().drizzle
- .select({ snapshot: botDelegations.permissionSnapshotJson }).from(botDelegations)
- .where(eq(botDelegations.id, params.id)).get())?.snapshot ?? '{}';
- const completionTerminal = parseRecord(completionSnapshot).taskTerminal as {
- runSequence: number; execution: DelegationExecutionReceipt;
- } | undefined;
- const completionMessage = buildDelegationCompletionMessage({
- id: params.id,
- objective: params.objective,
- status: params.status,
- resultSummary: params.resultSummary,
- artifacts,
- lastError: params.lastError,
- });
- try {
+ const completionStillPending = async (): Promise<boolean> => {
+ const [current] = await getDbClient().drizzle
+ .select({
+ status: botDelegations.status,
+ childSessionId: botDelegations.childSessionId,
+ runSequence: botDelegations.runSequence,
+ completionDeliveredAt: botDelegations.completionDeliveredAt,
+ })
+ .from(botDelegations)
+ .where(eq(botDelegations.id, params.id))
+ .limit(1);
+ return !!current
+ && current.status === params.status
+ && current.childSessionId === params.childSessionId
+ && current.runSequence === params.runSequence
+ && current.completionDeliveredAt === null;
+ };
+ // A retry from an earlier run may fire while the same task card is being
+ // continued. Never let that stale receipt wake or mark the new run.
+ if (!(await completionStillPending())) {
+ clearCompletionRetryTimer(params.id);
+ return false;
+ }
+ const artifacts = params.artifacts ?? [];
+ // 发给模型的回执正文不带 [UI_ACTION_TRIGGER] 前缀;前缀只留在落库 / 排队可见内容上,
+ // 让这条主机内部消息在时间线与排队区保持隐藏(同 botDirectMessageService 的私信)。
+ // 正文有界(结果摘要 / 文件清单截断):完整结果在下面持久化的回执行里,模型按需读取。
+ const completionSnapshot = (await getDbClient().drizzle
+ .select({ snapshot: botDelegations.permissionSnapshotJson }).from(botDelegations)
+ .where(eq(botDelegations.id, params.id)).get())?.snapshot ?? '{}';
+ const completionTerminal = parseRecord(completionSnapshot).taskTerminal as {
+ runSequence: number; execution: DelegationExecutionReceipt;
+ } | undefined;
+ const completionMessage = buildDelegationCompletionMessage({
+ id: params.id,
+ objective: params.objective,
+ status: params.status,
+ resultSummary: params.resultSummary,
+ artifacts,
+ lastError: params.lastError,
+ });
if (!(await completionStillPending())) {
clearCompletionRetryTimer(params.id);
return false;
@@ -1271,7 +1270,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
});
scheduleCompletionRetry(params, attempt);
return false;
- }
} finally {
releaseDelivery();
if (completionInFlight.get(params.id) === thisDelivery) {