Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): retain completion ownership across settlement and replay
Chris270077fd9512
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.tsindex a7b8a69ff0..e9907d357b 100644--- a/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts+++ b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts@@ -36,7 +36,7 @@ const meta = (id: string, source = 'desktop'): LocalSessionMeta => ({activeTurnStartedAt: 1, lastTurnEndedAt: 2,});const events = ['mine', 'delegated', 'shared', 'deleted'].map(subject => ({- sourceId: 'host:sessions', event: { id: subject, type: 'finished', subject, occurredAt: 2, data: {} },+ sourceId: 'host:sessions', event: { id: subject, type: 'finished', subject, occurredAt: 2, data: { executionInstanceId: 'event-instance', executionGeneration: 1 } },}));beforeEach(() => {h.scope = 'a'; h.scheduler = 'sched'; h.ready = true;@@ -136,7 +136,7 @@ it('filters only receipt-owned completion from built-in follow-up without mutatiexpect(result?.events).toEqual([events[0], failed]);expect(result?.canDispatch()).toBe(true);expect(batch).toEqual([...events, failed]);- expect(h.handled).toHaveBeenCalledWith('delegated', 'sched');+ expect(h.handled).toHaveBeenCalledWith('delegated', 'sched', { instanceId: 'event-instance', generation: 1 });});it.each(['unready', 'failed', 'account-changed'] as const)('defers a %s receipt read and retries the original completion batch', async state => {@@ -147,3 +147,11 @@ it.each(['unready', 'failed', 'account-changed'] as const)('defers a %s receipth.scope = 'a';expect((await currentFollowUpEvents('sched', events))?.events).toEqual([events[0], events[1]]);});++// A pre-upgrade event has no execution identity; never infer it from a live turn.+it('keeps unattributed legacy completion events', async () => {+ h.handled.mockResolvedValue(true);+ const legacy = [{ ...events[1], event: { ...events[1].event, data: {} } }];+ expect((await currentFollowUpEvents('sched', legacy))?.events).toEqual(legacy);+ expect(h.handled).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.tsindex 00102663e4..6d57d877cf 100644--- a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts+++ b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts@@ -17,7 +17,7 @@ import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activiimport { describe, expect, it, vi } from 'vitest';import { AUTONOMY_THRESHOLDS } from '../../../shared/botAutonomy.js';-import { AutonomyEventLedger } from '../events.js';+import { AutonomyEventLedger, toRoutineEvent } from '../events.js';import {REMOTE_BACKOFF_MAX_MS,TaskWatch,@@ -41,6 +41,7 @@ function activity(sessionId: string, phase: string, extra: Partial<SessionActivi}function harness(options: {+ readSessionExecution?: TaskWatchDeps['readSessionExecution'];metas?: LocalSessionMeta[];snapshots?: SessionActivitySnapshot[];devices?: RemoteDeviceTarget[] | null;@@ -79,6 +80,7 @@ function harness(options: {now: () => now,log: { info: vi.fn(), warn: vi.fn(), debug: vi.fn() },getActivitySnapshots: () => options.snapshots ?? [],+ readSessionExecution: options.readSessionExecution,isToolCallInFlight: (id) => toolsInFlight.has(id),getPendingInteractions: (id) => pending.get(id) ?? [],readLocalSessions,@@ -480,3 +482,25 @@ it('keeps remote IO out of scheduled sweeps and notifies coalesced view reads ofawait h.watch.sweep();expect(h.invokeRemote).toHaveBeenCalledTimes(2);});++// #6737 review / unit: metadata IO can outlive the terminal boundary. The event+// saved to the routine queue must retain the original native execution.+it('captures completion execution before asynchronous reads or a later turn', async () => {+ let execution = { instanceId: 'native-1', generation: 1 };+ const h = harness({ metas: [meta('child')], creators: { child: 'a' }, readSessionExecution: () => execution });+ await h.watch.start();+ h.watch.applyActivity('child', activity('child', 'running', { turnGeneration: null }));+ await h.watch.settled();+ h.watch.applyActivity('child', activity('child', 'completed', { turnGeneration: null }));+ execution = { instanceId: 'native-2', generation: 2 };+ await h.watch.settled();+ const [candidate] = new AutonomyEventLedger().evaluate(h.watch.list(), h.now()).due;+ expect(candidate).toBeDefined();+ const saved = JSON.parse(JSON.stringify(toRoutineEvent(candidate, h.now())));+ expect(saved.data).toMatchObject({ executionInstanceId: 'native-1', executionGeneration: 1 });+ h.watch.applyActivity('child', activity('child', 'running', { turnGeneration: 2 }));+ await h.watch.settled();+ expect(h.watch.get('child')?.execution).toEqual(execution);+ expect(saved.data).toMatchObject({ executionInstanceId: 'native-1', executionGeneration: 1 });+ h.watch.stop();+});diff --git a/apps/desktop/src/main/bot-autonomy/events.ts b/apps/desktop/src/main/bot-autonomy/events.tsindex 368fb2516f..18dbb3703a 100644--- a/apps/desktop/src/main/bot-autonomy/events.ts+++ b/apps/desktop/src/main/bot-autonomy/events.ts@@ -41,6 +41,8 @@ export const AUTONOMY_EVENT_FIELDS: readonly (keyof AutonomyEventData)[] = ['creatorBotId','followerBotId','occurrence',+ 'executionInstanceId',+ 'executionGeneration',];/** 宿主内置事件源声明;引擎每次创建后由宿主重新登记。 */@@ -166,6 +168,10 @@ export function toRoutineEvent(candidate: AutonomyEventCandidate, now: number):creatorBotId: row.creatorBotId ?? '',followerBotId: row.followerBotId ?? '',occurrence: candidate.occurrence,+ ...(row.execution ? {+ executionInstanceId: row.execution.instanceId,+ executionGeneration: row.execution.generation,+ } : {}),};return {id: candidate.id,diff --git a/apps/desktop/src/main/bot-autonomy/hub.ts b/apps/desktop/src/main/bot-autonomy/hub.tsindex 5b24b1eb11..eef1fb6e10 100644--- a/apps/desktop/src/main/bot-autonomy/hub.ts+++ b/apps/desktop/src/main/bot-autonomy/hub.ts@@ -10,6 +10,7 @@ import type { RoutineEngine, RoutineRun } from '@cindy/maker-scheduler';import {type BotAutonomySettingsView,type BotGlance,+ type BotAutonomyExecution,} from '../../shared/botAutonomy.js';import { activeOwnerScopeKey, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';import { createLogger } from '../logger.js';@@ -27,8 +28,9 @@ 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>;+ readSessionExecution(sessionId: string): BotAutonomyExecution | null;+ /** A durable terminal receipt owns this event's execution, including pending delivery. */+ isCompletionHandledByTeammate(sessionId: string, botId: string, execution: BotAutonomyExecution): Promise<boolean | null>;/** 某个本机任务当前挂起的交互请求(只读)。 */getPendingInteractions(sessionId: string): readonly unknown[];getMainWindow(): BrowserWindow | null;@@ -161,10 +163,16 @@ export async function currentFollowUpEvents(botId: string, events: RoutineRun['e// 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)));+ handled = await Promise.all(eligible.map(({ event }) => {+ const { executionInstanceId, executionGeneration } = event.data;+ // Legacy batches have no execution proof. Preserve their follow-up rather+ // than attributing them to whichever native turn happens to be live now.+ if (event.type !== 'finished' || typeof event.subject !== 'string'+ || typeof executionInstanceId !== 'string' || !executionInstanceId+ || typeof executionGeneration !== 'number' || !Number.isSafeInteger(executionGeneration)) return false;+ return hostDeps.isCompletionHandledByTeammate?.(event.subject, botId,+ { instanceId: executionInstanceId, generation: executionGeneration }) ?? null;+ }));} catch (error) {log.warn('autonomy completion ownership deferred', { error: errorCode(error) });return null;diff --git a/apps/desktop/src/main/bot-autonomy/service.ts b/apps/desktop/src/main/bot-autonomy/service.tsindex 151ba98abd..735fbb7024 100644--- a/apps/desktop/src/main/bot-autonomy/service.ts+++ b/apps/desktop/src/main/bot-autonomy/service.ts@@ -102,6 +102,7 @@ function startRuntime(engine: RoutineEngine, scope: string): void {log,onChange,getActivitySnapshots: () => getAgentIslandService()?.getSessionActivitySnapshots() ?? [],+ readSessionExecution: (id) => getBotAutonomyHostDeps().readSessionExecution?.(id) ?? null,isToolCallInFlight: (sessionId) => getAgentIslandService()?.isToolCallInFlight(sessionId) ?? false,getPendingInteractions: (sessionId) => {try {diff --git a/apps/desktop/src/main/bot-autonomy/taskWatch.ts b/apps/desktop/src/main/bot-autonomy/taskWatch.tsindex f872db650f..182e379cb1 100644--- a/apps/desktop/src/main/bot-autonomy/taskWatch.ts+++ b/apps/desktop/src/main/bot-autonomy/taskWatch.ts@@ -15,6 +15,7 @@import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';import {AUTONOMY_THRESHOLDS,+ type BotAutonomyExecution,type WatchedPhase,type WatchedSession,type WatchedSource,@@ -105,6 +106,7 @@ export interface TaskWatchDeps {now(): number;log: TaskWatchLogger;getActivitySnapshots(): readonly SessionActivitySnapshot[];+ readSessionExecution?(sessionId: string): BotAutonomyExecution | null;/** 本机任务是否有前台工具调用在途(tool_use 已发、tool_result 未回);只是布尔事实。 */isToolCallInFlight(sessionId: string): boolean;getPendingInteractions(sessionId: string): readonly unknown[];@@ -136,6 +138,7 @@ function inputProjectionErrorReason(projection: BotAutonomyInputProjection): strinterface LocalFacts {activity: SessionActivitySnapshot | null;+ execution?: BotAutonomyExecution;/** Live activity reached completion before ownership/metadata could create a row. */observedCompletion: boolean;inputError: string | null;@@ -256,7 +259,7 @@ export class TaskWatch {async start(): Promise<void> {await this.refreshOwnership();for (const snapshot of this.deps.getActivitySnapshots()) {- this.local.set(snapshot.sessionId, { ...this.factsFor(snapshot.sessionId), activity: snapshot });+ this.local.set(snapshot.sessionId, { ...this.factsFor(snapshot.sessionId), ...this.activityFacts(snapshot) });if (this.observesLocal(snapshot.sessionId) || !this.ownershipLoaded) this.pending.add(snapshot.sessionId);}// 归属没读到时不补「上一轮被打断」的任务:空归属会把它判成没人开、先落到总调度;留给读到归属后的扫描。@@ -276,7 +279,7 @@ export class TaskWatch {const observedCompletion = current?.phase === 'completed' && previous.activity !== null&& previous.activity.turnGeneration === current.turnGeneration&& (previous.activity.phase !== 'completed' || previous.observedCompletion);- const facts = { ...previous, activity: current, observedCompletion };+ const facts = { ...previous, ...this.activityFacts(current), observedCompletion };if (!current && !facts.inputError && !facts.usageLimitWait) this.local.delete(sessionId);else this.local.set(sessionId, facts);if (this.observesLocal(sessionId) || !this.ownershipLoaded) this.queue(sessionId);@@ -309,7 +312,7 @@ export class TaskWatch {await this.refreshOwnership(true);if (this.stopped) return;for (const snapshot of this.deps.getActivitySnapshots()) {- this.local.set(snapshot.sessionId, { ...this.factsFor(snapshot.sessionId), activity: snapshot });+ this.local.set(snapshot.sessionId, { ...this.factsFor(snapshot.sessionId), ...this.activityFacts(snapshot) });}for (const id of this.local.keys()) if (this.observesLocal(id)) this.pending.add(id);if (!this.interruptedSeeded && this.ownershipLoaded) await this.seedInterrupted();@@ -354,6 +357,17 @@ export class TaskWatch {return this.local.get(sessionId) ?? { activity: null, observedCompletion: false, inputError: null, inputErrorReason: null, usageLimitWait: false };}+ private activityFacts(activity: SessionActivitySnapshot | null): Pick<LocalFacts, 'activity' | 'execution'> {+ const live = activity ? this.deps.readSessionExecution?.(activity.sessionId) : null;+ const previous = activity ? this.local.get(activity.sessionId) : undefined;+ // Island snapshots can omit native generation. Capture the live identity+ // synchronously here, before metadata IO or the next queued turn can run.+ const execution = live && (activity?.turnGeneration == null || live.generation === activity.turnGeneration) ? { ...live } :+ activity && previous?.activity?.turnGeneration === activity.turnGeneration+ && previous.activity.startedAtMs === activity.startedAtMs ? previous.execution : undefined;+ return { activity, execution };+ }+private queue(sessionId: string): void {this.pending.add(sessionId);this.scheduleFlush();@@ -494,6 +508,7 @@ export class TaskWatch {phaseSince,lastActivityAt: activity?.lastActivityAtMs ?? previous?.lastActivityAt ?? phaseSince,startedAt: activity?.startedAtMs ?? previous?.startedAt ?? null,+ ...(facts.execution ? { execution: facts.execution } : {}),pendingQuestion,pendingRequestId,pendingInteractionId,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 6ce0cfe6c9..48afa1563d 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -8862,9 +8862,58 @@ describe('Bot Session task end-to-end runtime', () => {} finally { runtime.dispose(); 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 => {+ await seedPair();+ const execution = { instanceId: 'failed-settlement', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Settlement failure fixture.' });+ if (!task.ok) throw new Error(task.message);+ const condition = stage === 'terminal'+ ? "json_extract(NEW.permission_snapshot_json, '$.taskTerminal') IS NOT NULL"+ : "NEW.status = 'completed'";+ h.sqlite!.exec(`CREATE TEMP TRIGGER fail_completion BEFORE UPDATE ON bot_delegations WHEN ${condition} BEGIN SELECT RAISE(FAIL, 'fixture terminal unavailable'); END`);+ const settlement = runtime.settleChild(task.childSessionId, 'Completed output', execution);+ const check = runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a', execution });+ await Promise.all([+ expect(settlement).rejects.toThrow('fixture terminal unavailable'),+ expect(check).rejects.toThrow('fixture terminal unavailable'),+ ]);+ await expect(runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a', execution })).rejects.toThrow('fixture terminal unavailable');+ h.sqlite!.exec('DROP TRIGGER fail_completion');+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a', execution })).toBe(true);+ } finally { h.sqlite!.exec('DROP TRIGGER IF EXISTS fail_completion'); runtime.dispose(); }+ });++ // #6737 review / db: the original result survives runSequence replacement.+ // Reopen through the task API, then read after the native runtime unloads.+ it('matches queued completion to its frozen receipt after continuation and host reload', async () => {+ await seedPair();+ let execution: { instanceId: string; generation: number } | null = { instanceId: 'history-native', generation: 1 };+ const first = { ...execution };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Receipt history fixture.' });+ if (!task.ok) throw new Error(task.message);+ await runtime.settleChild(task.childSessionId, 'First result', first);+ execution = { instanceId: 'history-native', generation: 2 };+ const next = await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Second run' });+ expect(next.ok).toBe(true);+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a', execution: first })).toBe(true);+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a', execution })).toBe(false);+ await runtime.settleChild(task.childSessionId, 'Second result', execution);+ execution = null;+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a', execution: first })).toBe(true);+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'other', execution: first })).toBe(false);+ } finally { runtime.dispose(); }+ });+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 };+ let execution: { instanceId: string; generation: number } | null = { instanceId: 'notification-child', generation: 1 };+ const originalExecution = { ...execution };let release!: () => void;let entered!: () => void;const waiting = new Promise<void>(resolve => { entered = resolve; });@@ -8886,29 +8935,35 @@ 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);+ // #6440 / db: accepted input alone is not durable completion proof.+ const followUp = () => runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a', execution: originalExecution });+ expect(await followUp()).toBe(false);+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'other', execution: originalExecution })).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);+ const followUpOwnership = followUp();+ let followUpResolved = false;+ void followUpOwnership.then(() => { followUpResolved = true; });let resolved = false;void ownership.then(() => { resolved = true; });await Promise.resolve();expect(resolved).toBe(false);+ expect(followUpResolved).toBe(false);release();await settlement;if (boundary === 'paused' || boundary === 'archived') h.sqlite!.prepare('UPDATE bot_profiles SET status=? WHERE id=?').run(boundary, 'bot-a');+ expect(await followUpOwnership).toBe(true);expect(await ownership).toBe(boundary === 'accepted');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);+ execution = { ...originalExecution, generation: 2 };+ expect(await followUp()).toBe(true);+ expect(await runtime.delegation.isCompletionHandledByTeammate(task.childSessionId, { pendingForBotId: 'bot-a', execution })).toBe(false);+ execution = null;+ expect(await followUp()).toBe(true);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.tsindex d46438b76e..1163ca6cb2 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -1067,6 +1067,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {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,@@ -1114,6 +1117,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {...(child?.title?.trim() ? { title: child.title.trim() } : {}),workingDir: child?.workingDir ?? '',runSequence: params.runSequence,+ // Keep the native identity with the immutable per-run result:+ // the delegation row is reused when the owner continues the task.+ ...(completionTerminal?.runSequence === params.runSequence+ ? { execution: completionTerminal.execution } : {}),status: sessionTaskViewStatus({ status: params.status, lastError: params.lastError ?? null }),// A receipt is the in-app result, not a lock-screen preview. Keep// image and link targets so a result with no prose remains usable.@@ -4338,36 +4345,65 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {// Register synchronously: completion notices can arrive while settlement is// still reading the DB. Await only this terminal attempt, never retry timers.+ const terminalSettlementRetries = new Map<string, Parameters<typeof settleSessionUnserialized>[0]>();const settleSession = (params: Parameters<typeof settleSessionUnserialized>[0]): Promise<void> => {const settlement = settleSessionSerialized(params);terminalSettlements.set(params.childSessionId, settlement);- void settlement.finally(() => {+ terminalSettlementRetries.delete(params.childSessionId);+ void settlement.then(() => {if (terminalSettlements.get(params.childSessionId) === settlement) terminalSettlements.delete(params.childSessionId);- }).catch(() => undefined);+ }, () => {+ if (terminalSettlements.get(params.childSessionId) !== settlement) return;+ terminalSettlements.delete(params.childSessionId);+ terminalSettlementRetries.set(params.childSessionId, params);+ });return settlement;};const isCompletionHandledByTeammate = async (childSessionId: string,- options?: { pendingForBotId: string },+ options?: { pendingForBotId: string; execution: DelegationExecutionReceipt },): Promise<boolean> => {- const execution = deps.readSessionExecution?.(childSessionId);+ const execution = options?.execution ?? deps.readSessionExecution?.(childSessionId);if (!execution) return false;- // 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);+ // A failed settlement must leave the event pending, not consume it merely+ // because task input was accepted. The hub defers on this rejection.+ const retry = options && terminalSettlementRetries.get(childSessionId);+ if (retry?.execution && isSameSessionExecution(retry.execution, execution)) await settleSession(retry);+ else await terminalSettlements.get(childSessionId);const [row] = await getDbClient().drizzle.select().from(botDelegations).where(eq(botDelegations.childSessionId, childSessionId)).limit(1);- if (!row || row.acceptedAt == null) return false;+ if (!row) 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 (options) {+ if (row.requestingBotId !== options.pendingForBotId) return false;+ if (row.status === 'completed' && terminal?.runSequence === row.runSequence+ && terminal.outcome === 'done' && isSameSessionExecution(terminal.execution, execution)) return true;+ // A later run may already have replaced taskTerminal. Reuse the frozen+ // result in the original/current parent, not a new execution's live state.+ const [bot] = await getDbClient().drizzle.select({ canonicalSessionId: botProfiles.canonicalSessionId })+ .from(botProfiles).where(eq(botProfiles.id, options.pendingForBotId)).limit(1);+ const parents = [...new Set([row.parentSessionId, bot?.canonicalSessionId].filter((id): id is string => !!id))];+ if (!parents.length) return false;+ const receipt = await getDbClient().drizzle.select({ id: messages.id }).from(messages).where(and(+ inArray(messages.sessionId, parents),+ sql`json_extract(${messages.agentMeta}, '$.botCollaboration.role') = 'delegation-result'`,+ sql`json_extract(${messages.agentMeta}, '$.botCollaboration.delegationId') = ${row.id}`,+ sql`json_extract(${messages.agentMeta}, '$.botCollaboration.fromBotId') = ${options.pendingForBotId}`,+ sql`json_extract(${messages.agentMeta}, '$.botCollaboration.childSessionId') = ${childSessionId}`,+ sql`json_extract(${messages.agentMeta}, '$.botCollaboration.result.status') = 'completed'`,+ sql`json_extract(${messages.agentMeta}, '$.botCollaboration.result.execution.instanceId') = ${execution.instanceId}`,+ sql`json_extract(${messages.agentMeta}, '$.botCollaboration.result.execution.generation') = ${execution.generation}`,+ )).get();+ return !!receipt;+ }+ if (row.acceptedAt == null || accepted?.runSequence !== row.runSequence || !isSameSessionExecution(accepted, execution)+ || !sameExecution(childSessionId, execution)) return false;+ if (row.status !== 'completed' || row.completionDeliveredAt == null) return false;if (terminal?.runSequence !== row.runSequence|| terminal.outcome !== 'done'|| !isSameSessionExecution(terminal.execution, execution) || !sameExecution(childSessionId, execution)) return false;@@ -4577,6 +4613,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {);const dispose = (): void => {+ terminalSettlementRetries.clear();unregisterParentCancellation();pendingExecutionInputs.clear();pendingBoundaryValidations.clear();diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex ff5163bf99..57279f079b 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -3585,8 +3585,12 @@ function getPendingInteractionsForSession(sessionId: string): PendingInteraction// 伙伴自主跟进:状态表读「等你的那句话」只取请求本身(不含 persistId 等宿主内部字段)。configureBotAutonomyHost({- isCompletionHandledByTeammate: (sessionId, botId) => botDelegationServiceHolder- ?.isCompletionHandledByTeammate(sessionId, { pendingForBotId: botId }) ?? Promise.resolve(null),+ readSessionExecution: (id) => {+ const session = getMakerIfReady()?.getSession(id);+ return session ? { instanceId: session.instanceId, generation: session.getTurnGeneration() } : null;+ },+ isCompletionHandledByTeammate: (sessionId, botId, execution) => botDelegationServiceHolder+ ?.isCompletionHandledByTeammate(sessionId, { pendingForBotId: botId, execution }) ?? Promise.resolve(null),getPendingInteractions: (sessionId) => getPendingInteractionsForSession(sessionId).map((entry) => entry.request),});diff --git a/apps/desktop/src/shared/botAutonomy.ts b/apps/desktop/src/shared/botAutonomy.tsindex 504676a516..85ad8d1c79 100644--- a/apps/desktop/src/shared/botAutonomy.ts+++ b/apps/desktop/src/shared/botAutonomy.ts@@ -54,6 +54,12 @@ export type WatchedPhase =export type WatchedSource = 'user' | 'bot-task' | 'routine' | 'other';+/** Captured at the activity boundary; persisted events must not sample a later turn. */+export interface BotAutonomyExecution {+ instanceId: string;+ generation: number;+}+/** 状态表里的一行。远程任务的 `sessionId` 带 `deviceId::` 前缀,与历史工具一致。 */export interface WatchedSession {sessionId: string;@@ -68,6 +74,7 @@ export interface WatchedSession {phaseSince: number;lastActivityAt: number;startedAt: number | null;+ execution?: BotAutonomyExecution;/** 等回答 / 等权限时的一句摘要(≤ 140 字),否则 null。 */pendingQuestion: string | null;/**@@ -122,6 +129,9 @@ export const AUTONOMY_EVENT_TYPES: readonly AutonomyEventType[] = [/** `RoutineEvent.data` 的扁平字段(引擎要求 string|number|boolean)。 */export interface AutonomyEventData {+ /** Optional for queues saved before execution attribution was introduced. */+ executionInstanceId?: string;+ executionGeneration?: number;sessionId: string;deviceId: string;deviceName: string;diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 33dda145cd..7f68b057ef 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -563,8 +563,9 @@ Session 任务遵守同一套机制与呈现契约:已送达。临时失败指数退避,Host 重启后重投未送达终态,固定 client id 保证重复投递不产生第二条消息。宿主依据持久委派投递完成回执,不继承启动工具调用的临时授权上下文;父轮结束不使结果回传失效,普通工具操作的授权校验保持不变。-- **完成只唤醒一次**:内置跟进消费 `finished` 前,按委派轮次与实际执行身份核验完成回执归属。- 同一执行已有发给当前跟进伙伴的专属回执时(包括尚未结算和投递重试中),不再为此启动内置跟进;+- **完成只唤醒一次**:内置跟进消费 `finished` 前,等待在途结算,按事件中保存的原执行身份核验持久终态回执归属。+ 同一执行已有发给当前跟进伙伴的专属回执时(包括已结算但投递重试中),不再为此启动内置跟进;+ 结算或读取失败时保留批次待重试;本机保留失败结算的原参数,由同一批次重试该执行,不借后续执行补记旧结果;仅接受输入或仅写入终态快照尚不算完成送达责任成立。原轮执行身份也保存在冻结结果里,Host 重启或子任务续跑不改用当前执行判断旧事件。旧事件缺少执行身份时保留原跟进,不猜归属。完成事件仍保留供用户自建规则使用;结果、文件和可靠重试仍由原回执链交付。手动接手但无回执的任务、用户另起的执行及卡住/失败/待确认跟进保持原行为。- **不静默丢失**:发起方的原父任务已被异常恢复流程替换时,完成信号改投该伙伴当前的canonical Session;只有伙伴本身已暂停 / 归档才暂缓投递,此时卡片终态仍然可见,完成信号