Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): preserve delegated session lifecycle across execution turns (#4610)
Chris Zhang07a1acfd3515
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex a040ee7730..869ddb56b7 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -716,6 +716,8 @@ export interface BotsFinishRuntimeArgs {eventPayloadJson: string;}export interface BotsFinishDelegationArgs {+ expectedRunSequence?: number;+ expectedExecution?: { instanceId: string; generation: number };delegationId: string;status: 'completed' | 'failed' | 'cancelled' | 'timed-out';resultSummary: string | null;@@ -727,6 +729,8 @@ export interface BotsFinishDelegationArgs {export interface BotsFinishDelegationResult {id: string;+ targetBotId: string | null;+ runSequence: number;parentSessionId: string | null;childSessionId: string | null;status: 'queued' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled' | 'timed-out';diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 286739cc52..27a03b328e 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -212,7 +212,7 @@ import {} from '../../../maker-ipc/botProfileRuntime';import { createBotLifecycleService } from '../../../maker-ipc/botLifecycleService';import { createBotDirectMessageService } from '../../../maker-ipc/botDirectMessageService';-import { createBotDelegationService } from '../../../maker-ipc/botDelegationService';+import { createBotDelegationService, discardDelegationQueuedInputs } from '../../../maker-ipc/botDelegationService';import {BOT_DELEGATION_MAX_DISPATCH_ATTEMPTS,} from '../../../maker-ipc/botDelegationDispatchOutcome';@@ -3353,6 +3353,11 @@ describe('Bot Session task end-to-end runtime', () => {}function createDelegationRuntime(options: {+ discardDelegationQueuedInputs?: Parameters<typeof createBotDelegationService>[0]['discardDelegationQueuedInputs'];+ collectArtifacts?: Parameters<typeof createBotDelegationService>[0]['collectArtifacts'];+ readSessionExecution?: Parameters<typeof createBotDelegationService>[0]['readSessionExecution'];+ withSessionLock?: Parameters<typeof createBotDelegationService>[0]['withSessionLock'];+ closeSession?: Parameters<typeof createBotDelegationService>[0]['closeSession'];getWorktree?: Parameters<typeof createBotDelegationService>[0]['getWorktree'];withTransferredWorktree?: Parameters<typeof createBotDelegationService>[0]['withTransferredWorktree'];prepareWorktree?: Parameters<typeof createBotDelegationService>[0]['prepareWorktree'];@@ -3360,6 +3365,8 @@ describe('Bot Session task end-to-end runtime', () => {taskControl?: boolean;queueSnapshots?: Map<string, AgentInputQueuedMessage[]>;onNativeStarted?: (sessionId: string) => void;+ beforeNativeAcceptance?: (sessionId: string) => void;+ rejectAfterNativeAcceptance?: () => boolean;appliedOnResume?: () => string[];reconcileWorktree?: Parameters<typeof createBotDelegationService>[0]['reconcileWorktree'];stopUnsupported?: boolean;@@ -3427,10 +3434,10 @@ describe('Bot Session task end-to-end runtime', () => {message: string;persistedContent?: string;clientId?: string;- onAccepted?: () => void | Promise<void>;+ onAccepted?: (replayed?: boolean) => void | Promise<void>;}) => {if (params.clientId && hasMessage(params.targetSessionId, params.clientId)) {- await params.onAccepted?.();+ await params.onAccepted?.(true);return {ok: true as const,targetSessionId: params.targetSessionId,@@ -3496,7 +3503,12 @@ describe('Bot Session task end-to-end runtime', () => {);if (params.dispatcherSessionId) h.sqlite!.prepare('UPDATE messages SET agent_meta = ? WHERE session_id = ? AND client_id = ?').run(JSON.stringify({ origin: { kind: 'session', senderSessionId: params.dispatcherSessionId } }), params.targetSessionId, clientId);+ options.beforeNativeAcceptance?.(params.targetSessionId);await params.onAccepted?.();+ if (options.rejectAfterNativeAcceptance?.()) {+ started.pop();+ return { ok: false as const, errorCode: 'TEMPORARILY_UNAVAILABLE', message: 'Cancelled before vendor dispatch' };+ }h.sqlite!.prepare('UPDATE sessions SET active_turn_started_at = ? WHERE id = ?').run(currentTime, params.targetSessionId);pendingTurns.push({ sessionId: params.targetSessionId, queued: queuedBehindRunningTurn });@@ -3525,6 +3537,7 @@ describe('Bot Session task end-to-end runtime', () => {const persisted = sendOpts.persistUserMessage;if (!persisted) throw new Error('Missing coordinator user row');writeMessage(id, persisted.clientId, 'user', persisted.content);+ options.beforeNativeAcceptance?.(id);await persisted.onPersisted?.();const row = readSession(id)!;started.push({ sessionId: id, ...row });@@ -3533,7 +3546,11 @@ describe('Bot Session task end-to-end runtime', () => {options.onNativeStarted?.(id);return { kind: 'session-dispatch', source: 'fixture-native-turn', dispatched: true };},- onAcceptedQueuedMessage: async (_id, item) => { await acceptedCallbacks.get(item.clientId)?.(); },+ onDispatchedUserTurn: async (id, item) => { delegation.confirmQueuedSessionInputDispatched(id, item.clientId); },+ onAcceptedQueuedMessage: async (id, item, restoredFromSnapshot) => {+ await acceptedCallbacks.get(item.clientId)?.();+ if (options.readSessionExecution) await delegation.acceptQueuedSessionInput(id, item.clientId, item.supersedesUserClientId, restoredFromSnapshot, item.retrySourceClientId);+ },}) : undefined;const dispatch = vi.fn(async (params: Parameters<typeof dispatchDirect>[0]) => {if (coordinator) {@@ -3567,7 +3584,14 @@ describe('Bot Session task end-to-end runtime', () => {const waitForInputBoundary = vi.fn(async () => undefined);const preparePause = vi.fn(async () => undefined);const flushInput = vi.fn(async (): Promise<void> => undefined);+ const closeSession = vi.fn(options.closeSession ?? (async () => undefined));const delegation = createBotDelegationService({+ readSessionExecution: options.readSessionExecution,+ collectArtifacts: options.collectArtifacts,+ discardDelegationQueuedInputs: options.discardDelegationQueuedInputs ?? (coordinator+ ? (id, delegationId) => discardDelegationQueuedInputs(coordinator, id, delegationId, async () => undefined)+ : undefined),+ withSessionLock: options.withSessionLock,prepareWorktree: options.prepareWorktree,getWorktree: options.getWorktree,reconcileWorktree: options.reconcileWorktree,@@ -3591,9 +3615,10 @@ describe('Bot Session task end-to-end runtime', () => {readCallerPermission: options.readCallerPermission,dispatch,abortSession,- closeSession: vi.fn(async () => undefined),+ closeSession,broadcastSessionCreated: vi.fn(),resolveInteraction: options.resolveInteraction,+ readPendingInputClientIds: coordinator ? id => coordinator.getQueueControlSnapshot(id).pendingQueue.flatMap(item => [item.clientId, ...(item.supersedesUserClientId ? [item.supersedesUserClientId] : []), ...(item.retrySourceClientId ? [item.retrySourceClientId] : [])]) : undefined,hasPendingInput: (sessionId) => coordinator?.hasPendingQueuedWork(sessionId) || pendingTurns.some((turn) => turn.sessionId === sessionId && turn.queued,),@@ -3625,7 +3650,7 @@ describe('Bot Session task end-to-end runtime', () => {}};- const settleChild = async (sessionId: string, reply: string): Promise<void> => {+ const settleChild = async (sessionId: string, reply: string, execution?: { instanceId: string; generation: number }): Promise<void> => {const pendingIndex = pendingTurns.findIndex((turn) => turn.sessionId === sessionId);if (pendingIndex >= 0) pendingTurns.splice(pendingIndex, 1);writeMessage(sessionId, `assistant-${++seq}`, 'assistant', reply);@@ -3638,11 +3663,12 @@ describe('Bot Session task end-to-end runtime', () => {childSessionId: sessionId,outcome: 'done',resultText: reply,+ ...(execution ? { execution } : {}),});};return {- delegation, coordinator,+ delegation, coordinator, closeSession,heldInputs, steer, stopTurn, waitForInputBoundary, preparePause, flushInput,dispatch,abortSession,@@ -3937,7 +3963,7 @@ describe('Bot Session task end-to-end runtime', () => {// 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' });+ .get('session-1')).toMatchObject({ permission_mode: 'ask', status: 'active' });} finally {select.mockRestore();runtime.dispose();@@ -4014,6 +4040,939 @@ describe('Bot Session task end-to-end runtime', () => {}});+ it.each(['done', 'error'] as const)('keeps the Session visible and background work alive after %s, without restarting on restore', async (outcome) => {+ await seedPair();+ const runtime = createDelegationRuntime();+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Wait for background checks.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome, resultText: 'Checks are still pending.' });+ expect(runtime.closeSession).not.toHaveBeenCalled();+ expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(h.sqlite!.prepare("SELECT id FROM sessions WHERE status = 'active' AND source = 'desktop'").all())+ .toContainEqual({ id: task.childSessionId });+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { session_id: task.childSessionId, session_status: 'active', status: outcome === 'done' ? 'completed' : 'failed' } });+ const before = runtime.started.length;+ await runtime.delegation.restore();+ expect(runtime.started).toHaveLength(before);+ } finally { runtime.dispose(); }+ });++ it('retries a persisted start without a current-run acceptance receipt after restart', async () => {+ await seedPair();+ const before = createDelegationRuntime({ beforeNativeAcceptance: () => { throw new Error('host exited before acceptance'); } });+ await expect(before.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Unaccepted start.' })).rejects.toThrow('host exited');+ const row = h.sqlite!.prepare('SELECT id, child_session_id AS child, status FROM bot_delegations').get() as { id: string; child: string; status: string };+ expect(row.status).toBe('queued');+ before.dispose();+ const after = createDelegationRuntime({ readSessionExecution: () => ({ instanceId: 'restarted', generation: 1 }) });+ try {+ await after.delegation.restore();+ expect(after.started.filter(turn => turn.sessionId === row.child)).toHaveLength(1);+ expect(await after.delegation.getSessionTask('session-1', row.id)).toMatchObject({ task: { status: 'running' } });+ expect(after.dispatch.mock.calls.at(-1)?.[0].clientId).not.toBe(`bot-delegation-start:${row.id}`);+ const retry = after.dispatch.mock.calls.at(-1)?.[0].clientId;+ expect(h.sqlite!.prepare("SELECT json_extract(permission_snapshot_json, '$.taskDispatchRetry.clientId') FROM bot_delegations WHERE id = ?").pluck().get(row.id)).toBe(retry);+ expect(h.sqlite!.prepare('SELECT COUNT(*) FROM messages WHERE session_id = ? AND client_id = ?').pluck().get(row.child, `bot-delegation-start:${row.id}`)).toBe(1);+ await after.delegation.settleSession({ childSessionId: row.child, outcome: 'done', execution: { instanceId: 'restarted', generation: 1 }, resultText: 'Recovered result.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT result_summary FROM bot_delegations WHERE id = ?').pluck().get(row.id)).toBe('Recovered result.');+ } finally { after.dispose(); }+ });++ it.each(['restart', 'unpause'] as const)('retries a persisted %s prompt without its own acceptance receipt', async kind => {+ await seedPair();+ const oldExecution = { instanceId: 'old-runtime', generation: 1 };+ const before = createDelegationRuntime({ taskControl: true, readSessionExecution: () => oldExecution });+ const task = await before.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Continue the original task.' });+ if (!task.ok) throw new Error('missing task');+ if (kind === 'unpause') {+ await before.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ await before.settleChild(task.childSessionId, 'Paused.', oldExecution);+ }+ const snapshot = JSON.parse(h.sqlite!.prepare('SELECT permission_snapshot_json FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId) as string);+ const clientId = kind === 'restart'+ ? `bot-delegation-resume:${task.delegationId}:10000`+ : `bot-delegation-unpause:${task.delegationId}:${snapshot.taskPause.token}`;+ // Crash after saving this recovery input, before native acceptance. The+ // existing receipt belongs to the interrupted original turn, not this input.+ h.sqlite!.prepare('INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)')+ .run('persisted-recovery-fixture', clientId, task.childSessionId, 'user', 'Continue existing work.', 10_500);+ before.dispose();+ const execution = { instanceId: 'new-runtime', generation: 1 };+ const after = createDelegationRuntime({ taskControl: true, startTime: 11_000, readSessionExecution: () => execution });+ try {+ if (kind === 'restart') await after.delegation.restore();+ else expect(await after.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: true });+ expect(after.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(1);+ const retryId = after.dispatch.mock.calls.at(-1)![0].clientId!;+ expect(retryId).not.toBe(clientId);+ const saved = JSON.parse(h.sqlite!.prepare('SELECT permission_snapshot_json FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId) as string);+ expect(saved.taskExecution).toMatchObject({ ...execution, runSequence: 1, clientId: retryId });+ expect(saved.taskRecoveryRetry.clientId).toBe(retryId);+ expect(h.sqlite!.prepare('SELECT COUNT(*) FROM messages WHERE session_id = ? AND client_id = ?').pluck().get(task.childSessionId, clientId)).toBe(1);+ if (kind === 'restart') await after.delegation.restore();+ else expect(await after.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: true });+ expect(after.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(1);+ await after.delegation.settleSession({ childSessionId: task.childSessionId, execution, outcome: 'done', resultText: 'Recovered.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ expect(await after.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'completed', result: 'Recovered.' } });+ } finally { after.dispose(); }+ });++ it.each(['restart', 'unpause'] as const)('retries %s after acceptance is followed by dispatch rejection', async kind => {+ await seedPair();+ const oldExecution = { instanceId: 'original-runtime', generation: 1 };+ const before = createDelegationRuntime({ taskControl: true, readSessionExecution: () => oldExecution });+ const task = await before.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish existing work.' });+ if (!task.ok) throw new Error('missing task');+ if (kind === 'unpause') {+ await before.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ await before.settleChild(task.childSessionId, 'Paused.', oldExecution);+ }+ before.dispose();+ let reject = true;+ const execution = { instanceId: 'recovery-runtime', generation: 1 };+ const after = createDelegationRuntime({ taskControl: true, startTime: 11_000,+ readSessionExecution: () => execution, rejectAfterNativeAcceptance: () => reject });+ const resume = () => kind === 'restart' ? after.delegation.restore()+ : after.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' });+ try {+ await resume();+ expect(after.started).toHaveLength(0);+ const saved = JSON.parse(h.sqlite!.prepare('SELECT permission_snapshot_json FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId) as string);+ expect(saved.taskExecution).toMatchObject(oldExecution);+ reject = false;+ await resume();+ expect(after.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(1);+ await resume();+ expect(after.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(1);+ await after.delegation.settleSession({ childSessionId: task.childSessionId, execution, outcome: 'done', resultText: 'Recovered after cancellation.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ expect(await after.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'completed' } });+ } finally { after.dispose(); }+ });++ it('retries a rejected supplement without replacing its previous execution receipt', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ let reject = false;+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution,+ rejectAfterNativeAcceptance: () => reject });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original work.' });+ if (!task.ok) throw new Error('missing task');+ const input = { kind: 'message' as const, text: 'Add a conclusion.', idempotencyKey: 'rejected-supplement' };+ execution = { instanceId: 'native', generation: 2 };+ reject = true;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, input)).toMatchObject({ ok: false });+ const saved = JSON.parse(h.sqlite!.prepare('SELECT permission_snapshot_json FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId) as string);+ expect(saved.taskExecution).toMatchObject({ instanceId: 'native', generation: 1 });+ reject = false;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, input)).toMatchObject({ ok: true });+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(2);+ // A later accepted supplement cannot erase the first one's idempotency receipt.+ execution = { instanceId: 'native', generation: 3 };+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { ...input, idempotencyKey: 'later-supplement' });+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, input);+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(3);+ } finally { runtime.dispose(); }+ });++ it('collects artifacts using only inputs accepted in the reopened run', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const collectArtifacts = vi.fn(async () => []);+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution, collectArtifacts });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Initial work.' });+ if (!task.ok) throw new Error('missing task');+ const firstId = runtime.dispatch.mock.calls.find(([p]) => p.targetSessionId === task.childSessionId)![0].clientId!;+ await runtime.settleChild(task.childSessionId, 'First result.', execution);+ expect(collectArtifacts).toHaveBeenLastCalledWith(task.childSessionId, [firstId]);+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Continue.' });+ const nextId = runtime.dispatch.mock.calls.filter(([p]) => p.targetSessionId === task.childSessionId).at(-1)![0].clientId!;+ await runtime.settleChild(task.childSessionId, 'Next result.', execution);+ expect(nextId).not.toBe(firstId);+ expect(collectArtifacts).toHaveBeenLastCalledWith(task.childSessionId, [nextId]);+ } finally { runtime.dispose(); }+ });++ it('does not rebind an idempotent supplement replay to a later direct turn', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original task.' });+ if (!task.ok) throw new Error('missing task');+ const input = { kind: 'message' as const, text: 'Supplement.', idempotencyKey: 'same-input' };+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, input);+ const original = h.sqlite!.prepare('SELECT permission_snapshot_json FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId);+ execution = { instanceId: 'native', generation: 3 };+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, input);+ expect(h.sqlite!.prepare('SELECT permission_snapshot_json FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId)).toBe(original);+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution, resultText: 'Unrelated result.' });+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'running' } });+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution: { instanceId: 'native', generation: 2 }, resultText: 'Supplement result.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT result_summary FROM bot_delegations WHERE id = ?').pluck().get(task.delegationId)).toBe('Supplement result.');+ } finally { runtime.dispose(); }+ });++ it.each([false, true])('binds queued continuation start only at native acceptance (cold: %s)', async cold => {+ await seedPair();+ const receipts = new Map<string, { instanceId: string; generation: number }>();+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots: new Map(),+ readSessionExecution: id => receipts.get(id) ?? null,+ beforeNativeAcceptance: id => receipts.set(id, {+ instanceId: receipts.get(id)?.instanceId ?? `native-${id}`,+ generation: (receipts.get(id)?.generation ?? 0) + 1,+ }),+ });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Initial task.' });+ if (!task.ok) throw new Error('missing task');+ const initialReceipt = receipts.get(task.childSessionId)!;+ await runtime.settleChild(task.childSessionId, 'Initial result.', initialReceipt);+ await runtime.dispatch({ targetSessionId: task.childSessionId, message: 'Independent user turn.', clientId: 'direct-user-turn' });+ const directReceipt = receipts.get(task.childSessionId)!;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Continue the task.' }))+ .toMatchObject({ ok: false, errorCode: 'STOP_UNCONFIRMED' });+ await runtime.settleChild(task.childSessionId, 'Direct turn ended.', directReceipt);+ runtime.coordinator!.setExecutionPaused(task.childSessionId, true);+ const continued = await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Continue the task.' });+ expect(continued).toMatchObject({ ok: true });+ expect(runtime.coordinator!.getQueueControlSnapshot(task.childSessionId).pendingQueue.map(item => item.clientId))+ .toContain(`bot-delegation-start:${task.delegationId}:2`);+ const read = () => h.sqlite!.prepare("SELECT status, json_extract(permission_snapshot_json, '$.taskExecution') AS receipt FROM bot_delegations WHERE id = ?").get(task.delegationId);+ expect(read()).toEqual({ status: 'queued', receipt: JSON.stringify({ ...initialReceipt, runSequence: 1, clientId: `bot-delegation-start:${task.delegationId}` }) });+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution: directReceipt, resultText: 'Unrelated direct result.',+ pendingInputClientIds: [`bot-delegation-start:${task.delegationId}:2`], hadPendingInputAtTerminal: true });+ expect(read()).toEqual({ status: 'queued', receipt: JSON.stringify({ ...initialReceipt, runSequence: 1, clientId: `bot-delegation-start:${task.delegationId}` }) });+ if (cold) receipts.delete(task.childSessionId);+ runtime.coordinator!.setExecutionPaused(task.childSessionId, false);+ runtime.coordinator!.resume(task.childSessionId);+ await vi.waitFor(() => expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(3));+ expect(read()).toEqual({ status: 'running', receipt: JSON.stringify({ ...receipts.get(task.childSessionId), runSequence: 2, clientId: `bot-delegation-start:${task.delegationId}:2` }) });+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution: directReceipt, resultText: 'Late direct result.' });+ expect((read() as { status: string }).status).toBe('running');+ await runtime.settleChild(task.childSessionId, 'Continuation result.', receipts.get(task.childSessionId));+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Continuation result.' });+ } finally { runtime.dispose(); }+ });++ it.each(['archived', 'deleted'] as const)('refuses continuation of a %s Session without creating a replacement', async (status) => {+ await seedPair();+ const runtime = createDelegationRuntime();+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.settleChild(task.childSessionId, 'Done.');+ h.sqlite!.prepare('UPDATE sessions SET status = ? WHERE id = ?').run(status, task.childSessionId);+ const count = h.sqlite!.prepare('SELECT COUNT(*) AS n FROM sessions').get();+ const before = runtime.started.length;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Continue.' }))+ .toMatchObject({ ok: false, errorCode: status.toUpperCase() });+ expect(h.sqlite!.prepare('SELECT COUNT(*) AS n FROM sessions').get()).toEqual(count);+ expect(runtime.started).toHaveLength(before);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { session_id: task.childSessionId, session_status: status, status: 'completed' } });+ } finally { runtime.dispose(); }+ });++ it('does not let a failed cancellation cleanup close a later continuation', async () => {+ await seedPair();+ vi.useFakeTimers();+ const runtime = createDelegationRuntime({ closeSession: async () => { throw new Error('runtime close unavailable'); } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Do the work.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.stopSessionTask('session-1', task.delegationId);+ expect(runtime.closeSession).toHaveBeenCalledTimes(1);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'cancelled', session_status: 'active' } });+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Continue with new instructions.' }))+ .toMatchObject({ ok: true, childSessionId: task.childSessionId });+ await vi.advanceTimersByTimeAsync(2_000);+ expect(runtime.closeSession).toHaveBeenCalledTimes(1);+ expect(runtime.abortSession).toHaveBeenCalledTimes(1);+ } finally { runtime.dispose(); vi.useRealTimers(); }+ });++ it.each(['new-turn', 'new-instance'] as const)('does not retry cancellation cleanup against a direct %s', async (replacement) => {+ await seedPair();+ vi.useFakeTimers();+ let execution = { instanceId: 'native-1', generation: 1 };+ const withSessionLock = vi.fn(async (_id: string, operation: () => Promise<void>) => operation());+ const runtime = createDelegationRuntime({+ readSessionExecution: () => execution,+ withSessionLock,+ closeSession: async () => { throw new Error('close temporarily failed'); },+ });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Work.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.stopSessionTask('session-1', task.delegationId);+ expect(runtime.closeSession).toHaveBeenCalledTimes(1);+ const locksBeforeRetry = withSessionLock.mock.calls.length;+ // Opening the visible task and sending directly does not reopen delegation.+ execution = replacement === 'new-turn'+ ? { instanceId: 'native-1', generation: 2 }+ : { instanceId: 'native-2', generation: 1 };+ await vi.advanceTimersByTimeAsync(2_000);+ expect(runtime.closeSession).toHaveBeenCalledTimes(1);+ expect(runtime.abortSession).toHaveBeenCalledTimes(1);+ expect(withSessionLock).toHaveBeenCalledTimes(locksBeforeRetry);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'cancelled', session_status: 'active' } });+ } finally { runtime.dispose(); vi.useRealTimers(); }+ });++ it.each((['cancel', 'pause', 'request-stop'] as const).flatMap(mode =>+ [false, true].map(changeInsideLock => ({ mode, changeInsideLock })),+ ))('does not apply first $mode to a newer direct execution (lock race: $changeInsideLock)', async ({ mode, changeInsideLock }) => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const discard = vi.fn(async () => undefined);+ const runtime = createDelegationRuntime({ taskControl: true,+ readSessionExecution: () => execution, discardDelegationQueuedInputs: discard,+ withSessionLock: async (_id, operation) => {+ execution = { instanceId: 'native', generation: 2 };+ await operation();+ },+ });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original work.' });+ if (!task.ok) throw new Error('missing task');+ if (!changeInsideLock) execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.stopSessionTask('session-1', task.delegationId, mode);+ expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(runtime.stopTurn).not.toHaveBeenCalled();+ expect(runtime.preparePause).not.toHaveBeenCalled();+ expect(runtime.closeSession).not.toHaveBeenCalled();+ expect(discard).toHaveBeenCalledWith(task.childSessionId, task.delegationId);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'cancelled', session_status: 'active' } });+ } finally { runtime.dispose(); }+ });++ it.each(['done', 'error'] as const)('ignores a delayed %s from an earlier execution after same-Session continuation', async (outcome) => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'First run.' });+ if (!task.ok) throw new Error('missing task');+ const previousExecution = execution;+ await runtime.settleChild(task.childSessionId, 'First result.');+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Second run.' });+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome,+ execution: previousExecution, resultText: 'Stale result.', error: 'Stale failure.' });+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'running' } });+ expect(h.sqlite!.prepare('SELECT result_summary, last_error FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ result_summary: null, last_error: null });+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done',+ execution, resultText: 'Second result.' });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Second result.' });+ } finally { runtime.dispose(); }+ });++ it.each(['new-turn', 'no-instance', 'never-accepted'] as const)('timeout cleanup preserves unrelated work with %s', async replacement => {+ await seedPair();+ vi.useFakeTimers();+ let execution: { instanceId: string; generation: number } | null = { instanceId: 'native', generation: 1 };+ const discardDelegationQueuedInputs = vi.fn(async () => undefined);+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution, discardDelegationQueuedInputs,+ transientUnavailable: () => replacement === 'never-accepted' });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Deadline work.', timeoutMs: 1000 });+ if (!task.ok) throw new Error('missing task');+ execution = replacement === 'new-turn' ? { instanceId: 'native', generation: 2 } : null;+ runtime.advance(1000);+ await vi.advanceTimersByTimeAsync(1000);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'timed-out', session_status: 'active' } });+ expect(discardDelegationQueuedInputs).toHaveBeenCalledExactlyOnceWith(task.childSessionId, task.delegationId);+ expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(runtime.closeSession).not.toHaveBeenCalled();+ } finally { runtime.dispose(); vi.useRealTimers(); }+ });++ it.each([false, true, 'auto'] as const)('removes timed-out delegation queue entries without dropping unrelated input (retry clone: %s)', async cloned => {+ await seedPair();+ vi.useFakeTimers();+ let execution: { instanceId: string; generation: number } | null = { instanceId: 'native', generation: 1 };+ const queueSnapshots = new Map<string, AgentInputQueuedMessage[]>();+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution, queueSnapshots });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Expire queued work.', timeoutMs: 1000 });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Delegated follow-up.' });+ await runtime.dispatch({ targetSessionId: task.childSessionId, message: 'Keep direct user input.', clientId: 'direct-user-input' });+ expect(runtime.coordinator!.getQueueControlSnapshot(task.childSessionId).pendingQueue).toHaveLength(2);+ if (cloned) {+ const item = runtime.coordinator!.getQueueControlSnapshot(task.childSessionId).pendingQueue[0];+ runtime.coordinator!.remove(task.childSessionId, item.clientId);+ runtime.coordinator!.enqueue(task.childSessionId, {+ ...item, clientId: 'random-retry-clone',+ supersedesUserClientId: cloned === 'auto' ? undefined : item.clientId,+ retrySourceClientId: cloned === 'auto' ? item.clientId : undefined,+ chatMessage: { ...item.chatMessage, clientId: 'random-retry-clone' },+ });+ }+ execution = null;+ runtime.advance(1000);+ await vi.advanceTimersByTimeAsync(1000);+ expect(runtime.coordinator!.getQueueControlSnapshot(task.childSessionId).pendingQueue.map(item => item.clientId))+ .toEqual(['direct-user-input']);+ expect(queueSnapshots.get(task.childSessionId)?.map(item => item.clientId)).toEqual(['direct-user-input']);+ expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(runtime.closeSession).not.toHaveBeenCalled();+ } finally { runtime.dispose(); vi.useRealTimers(); }+ });++ it('timeout still aborts the native execution bound to the delegation receipt', async () => {+ await seedPair();+ vi.useFakeTimers();+ const runtime = createDelegationRuntime({ readSessionExecution: () => ({ instanceId: 'native', generation: 1 }) });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Stop on deadline.', timeoutMs: 1000 });+ if (!task.ok) throw new Error('missing task');+ runtime.advance(1000);+ await vi.advanceTimersByTimeAsync(1000);+ expect(runtime.abortSession).toHaveBeenCalledExactlyOnceWith(task.childSessionId);+ expect(runtime.closeSession).toHaveBeenCalledExactlyOnceWith(task.childSessionId);+ } finally { runtime.dispose(); vi.useRealTimers(); }+ });++ it('does not reuse the prior answer for a tool-only continuation without an assistant message', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'First answer.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.settleChild(task.childSessionId, 'Previous answer must not be repeated.');+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Tool-only continuation.' });+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution, resultText: '', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: null });+ } finally { runtime.dispose(); }+ });++ it('settles the accepted delegated receipt when a direct turn starts during artifact reads', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ let release!: () => void;+ let entered!: () => void;+ const collecting = new Promise<void>(resolve => { entered = resolve; });+ const barrier = new Promise<void>(resolve => { release = resolve; });+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution,+ collectArtifacts: async () => { entered(); await barrier; return []; } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original work.' });+ if (!task.ok) throw new Error('missing task');+ const original = runtime.delegation.settleSession({ childSessionId: task.childSessionId,+ outcome: 'done', execution, resultText: 'Original result.', hadPendingInputAtTerminal: false });+ await collecting;+ execution = { instanceId: 'native', generation: 2 };+ const direct = runtime.delegation.settleSession({ childSessionId: task.childSessionId,+ outcome: 'done', execution, resultText: 'Unrelated direct result.', hadPendingInputAtTerminal: false });+ release();+ await Promise.all([original, direct]);+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Original result.' });+ } finally { release(); runtime.dispose(); }+ });++ it('recovers only the terminal event assistant message after a direct next turn has replied', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Recover original result.' });+ if (!task.ok) throw new Error('missing task');+ const insert = h.sqlite!.prepare('INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)');+ insert.run('original-result-id', 'original-result-client', task.childSessionId, 'assistant', 'Original transcript.', 20000);+ insert.run('direct-result-id', 'direct-result-client', task.childSessionId, 'assistant', 'Unrelated transcript.', 30000);+ const originalExecution = execution;+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution: originalExecution,+ resultMessageClientId: 'original-result-client', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Original transcript.' });+ } finally { runtime.dispose(); }+ });++ it('does not commit a terminal result after its durable execution receipt changes during reads', async () => {+ await seedPair();+ const execution = { instanceId: 'native', generation: 1 };+ let delegationId = '';+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution,+ collectArtifacts: async () => {+ h.sqlite!.prepare("UPDATE bot_delegations SET permission_snapshot_json = json_set(permission_snapshot_json, '$.taskExecution.generation', 2) WHERE id = ?").run(delegationId);+ return [];+ } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Changing receipt.' });+ if (!task.ok) throw new Error('missing task');+ delegationId = task.delegationId;+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Superseded result.', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(delegationId))+ .toEqual({ status: 'running', result_summary: null });+ } finally { runtime.dispose(); }+ });++ it('does not adopt an ordinary user message queued before the delegated terminal event', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Delegated objective.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Delegated answer.', hadPendingInputAtTerminal: true, pendingInputClientIds: ['ordinary-user-input'] });+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.acceptQueuedSessionInput(task.childSessionId, 'ordinary-user-input');+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Unrelated answer.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Delegated answer.' });+ } finally { runtime.dispose(); }+ });++ it.each(['direct', 'delegated-looking'] as const)('does not publish an invalid direct terminal boundary for %s queued input while the original result is pending', async kind => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ let release!: () => void;+ let entered!: () => void;+ const barrier = new Promise<void>(resolve => { release = resolve; });+ const collecting = new Promise<void>(resolve => { entered = resolve; });+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution,+ collectArtifacts: async () => { entered(); await barrier; return []; } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original objective.' });+ if (!task.ok) throw new Error('missing task');+ const original = runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Original answer.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ await collecting;+ execution = { instanceId: 'native', generation: 2 };+ const clientId = kind === 'direct' ? 'next-direct-input' : `bot-delegation-interject:${task.delegationId}:queued`;+ const direct = runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Direct answer.', hadPendingInputAtTerminal: true, pendingInputClientIds: [clientId] });+ execution = { instanceId: 'native', generation: 3 };+ if (kind === 'delegated-looking') {+ // A declined owned boundary must remain rejected on subsequent attempts.+ for (let retry = 0; retry < 2; retry++) {+ await expect(runtime.delegation.acceptQueuedSessionInput(task.childSessionId, clientId))+ .rejects.toThrow('Delegated queue boundary validation was declined');+ }+ await expect(runtime.delegation.acceptQueuedSessionInput(task.childSessionId, 'retry-clone', clientId))+ .rejects.toThrow('Delegated queue boundary validation was declined');+ } else {+ await expect(runtime.delegation.acceptQueuedSessionInput(task.childSessionId, clientId)).resolves.toBeUndefined();+ }+ expect(h.sqlite!.prepare("SELECT json_extract(permission_snapshot_json, '$.taskExecution.generation') AS generation FROM bot_delegations WHERE id = ?").get(task.delegationId))+ .toEqual({ generation: 1 });+ release();+ await Promise.all([original, direct]);+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Original answer.' });+ } finally { release(); runtime.dispose(); }+ });++ it('adopts only input queued at the delegated terminal boundary', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Queued work.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ hadPendingInputAtTerminal: true, pendingInputClientIds: [`bot-delegation-interject:${task.delegationId}:owned`] });+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.acceptQueuedSessionInput(task.childSessionId, 'unrelated-input');+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Unrelated.', pendingInputClientIds: [`bot-delegation-interject:${task.delegationId}:owned`], hadPendingInputAtTerminal: true });+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'running' } });+ await runtime.delegation.acceptQueuedSessionInput(task.childSessionId, `bot-delegation-interject:${task.delegationId}:owned`);+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Queued result.', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Queued result.' });+ } finally { runtime.dispose(); }+ });++ it('keeps a supplement queued after an empty terminal snapshot tracked until its result', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots: new Map(), readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original work.' });+ if (!task.ok) throw new Error('missing task');+ // The terminal adapter captured [] before this supplement obtained the task lock.+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Late supplement.' });+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Original result.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'running' } });+ execution = { instanceId: 'native', generation: 2 };+ await runtime.settleChild(task.childSessionId, 'Original turn ended.');+ await vi.waitFor(() => expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(2));+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Late supplement result.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Late supplement result.' });+ } finally { runtime.dispose(); }+ });++ it.each([false, true])('rejects late owned input after an empty stale snapshot (settled: %s)', async settled => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots: new Map(), readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original work.' });+ if (!task.ok) throw new Error('missing task');+ execution = { instanceId: 'native', generation: 2 };+ const stale = runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Unrelated direct result.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Late supplement.' });+ if (settled) await stale;+ const clientId = runtime.dispatch.mock.calls.find(([input]) => input.clientId?.startsWith('bot-delegation-interject:'))![0].clientId!;+ execution = { instanceId: 'native', generation: 3 };+ await expect(runtime.delegation.acceptQueuedSessionInput(task.childSessionId, clientId))+ .rejects.toThrow('Delegated queued input has no verified execution boundary');+ await expect(runtime.delegation.acceptQueuedSessionInput(task.childSessionId, 'retry-clone', clientId))+ .rejects.toThrow('Delegated queued input has no verified execution boundary');+ await expect(runtime.delegation.acceptQueuedSessionInput(task.childSessionId, 'ordinary-direct-input')).resolves.toBeUndefined();+ await stale;+ expect(h.sqlite!.prepare("SELECT status, json_extract(permission_snapshot_json, '$.taskExecution.generation') AS generation FROM bot_delegations WHERE id = ?").get(task.delegationId))+ .toEqual({ status: 'running', generation: 1 });+ } finally { runtime.dispose(); }+ });++ it('rejects a supplement acceptance if its delegated run has already ended', async () => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots: new Map(),+ readSessionExecution: () => ({ instanceId: 'native', generation: 1 }) });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Work.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Queued supplement.' });+ const accepted = runtime.dispatch.mock.calls.find(([input]) => input.clientId?.startsWith('bot-delegation-interject:'))![0].onAccepted!;+ h.sqlite!.prepare("UPDATE bot_delegations SET status = 'cancelled' WHERE id = ?").run(task.delegationId);+ await expect(accepted()).rejects.toThrow('Delegated execution receipt was not committed');+ } finally { runtime.dispose(); }+ });++ it.each([false, true])('revalidates a retry clone after transient boundary read failure (receipt changed: %s)', async changed => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Queued work.' });+ if (!task.ok) throw new Error('missing task');+ const clientId = `bot-delegation-interject:${task.delegationId}:pending`;+ const failingRead = vi.spyOn(h.db!, 'select').mockImplementationOnce(() => { throw new Error('temporary database failure'); });+ const terminal = runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ pendingInputClientIds: [clientId], hadPendingInputAtTerminal: true });+ const firstAcceptance = runtime.delegation.acceptQueuedSessionInput(task.childSessionId, clientId);+ const attempts = await Promise.allSettled([terminal, firstAcceptance]);+ expect(attempts.every(result => result.status === 'rejected')).toBe(true);+ failingRead.mockRestore();+ execution = { instanceId: 'native', generation: 2 };+ if (changed) h.sqlite!.prepare("UPDATE bot_delegations SET permission_snapshot_json = json_set(permission_snapshot_json, '$.taskExecution.generation', 3) WHERE id = ?").run(task.delegationId);+ const retry = runtime.delegation.acceptQueuedSessionInput(task.childSessionId, 'retry-clone', clientId);+ if (changed) {+ await expect(retry).rejects.toThrow('Delegated queue boundary validation was declined');+ expect(h.sqlite!.prepare("SELECT json_extract(permission_snapshot_json, '$.taskExecution.generation') FROM bot_delegations WHERE id = ?").pluck().get(task.delegationId)).toBe(3);+ } else {+ await retry;+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Retry result.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Retry result.' });+ }+ } finally { vi.restoreAllMocks(); runtime.dispose(); }+ });++ it('awaits terminal receipt validation when queue acceptance overtakes settlement', async () => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Queued follow-up.' });+ if (!task.ok) throw new Error('missing task');+ const clientId = `bot-delegation-interject:${task.delegationId}:racing`;+ // Do not await settlement: simulate the already-scheduled queue drain.+ const terminal = runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ pendingInputClientIds: [clientId], hadPendingInputAtTerminal: true });+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.acceptQueuedSessionInput(task.childSessionId, clientId);+ await terminal;+ runtime.delegation.confirmQueuedSessionInputDispatched(task.childSessionId, clientId);+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Follow-up result.', pendingInputClientIds: [], hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Follow-up result.' });+ } finally { runtime.dispose(); }+ });++ it.each([false, true])('retains accepted but undispatched input for retry (cloned: %s)', async cloned => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Retry queued work.' });+ if (!task.ok) throw new Error('missing task');+ const originalId = `bot-delegation-interject:${task.delegationId}:retry`;+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ hadPendingInputAtTerminal: true, pendingInputClientIds: [originalId] });+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.acceptQueuedSessionInput(task.childSessionId, originalId);+ // No dispatch receipt: native reservation was cancelled after acceptance.+ execution = { instanceId: 'replacement-native', generation: 1 };+ const retryId = cloned ? 'manual-retry-clone' : originalId;+ await runtime.delegation.acceptQueuedSessionInput(task.childSessionId, retryId, cloned ? originalId : undefined);+ runtime.delegation.confirmQueuedSessionInputDispatched(task.childSessionId, retryId);+ const dispatchedExecution = execution;+ execution = { instanceId: 'replacement-native', generation: 2 };+ // A consumed boundary cannot be used to attach a later direct execution.+ // Reusing an owned ID now explicitly rejects instead of silently ignoring it.+ if (cloned) await runtime.delegation.acceptQueuedSessionInput(task.childSessionId, retryId);+ else await expect(runtime.delegation.acceptQueuedSessionInput(task.childSessionId, retryId))+ .rejects.toThrow('Delegated queued input has no verified execution boundary');+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution: dispatchedExecution,+ resultText: 'Retried result.', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Retried result.' });+ } finally { runtime.dispose(); }+ });++ it.each(['FAIL', 'IGNORE'] as const)('retains a queued execution boundary when receipt persistence returns %s', async failure => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Durable queue adoption.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ hadPendingInputAtTerminal: true, pendingInputClientIds: [`bot-delegation-interject:${task.delegationId}:retry`] });+ execution = { instanceId: 'native', generation: 2 };+ const raise = failure === 'FAIL' ? "RAISE(FAIL, 'fixture receipt unavailable')" : 'RAISE(IGNORE)';+ h.sqlite!.exec(`CREATE TEMP TRIGGER fail_execution_receipt BEFORE UPDATE OF permission_snapshot_json ON bot_delegations+ WHEN json_extract(NEW.permission_snapshot_json, '$.taskExecution.generation') = 2+ BEGIN SELECT ${raise}; END`);+ await expect(runtime.delegation.acceptQueuedSessionInput(task.childSessionId, `bot-delegation-interject:${task.delegationId}:retry`)).rejects.toThrow();+ h.sqlite!.exec('DROP TRIGGER fail_execution_receipt');+ await runtime.delegation.acceptQueuedSessionInput(task.childSessionId, `bot-delegation-interject:${task.delegationId}:retry`);+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Retry adopted.', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Retry adopted.' });+ } finally { h.sqlite!.exec('DROP TRIGGER IF EXISTS fail_execution_receipt'); runtime.dispose(); }+ });++ it('enqueues a delegated resume even when an unrelated direct input is already queued', async () => {+ await seedPair();+ const queueSnapshots = new Map<string, AgentInputQueuedMessage[]>();+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Resume delegated objective.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ await runtime.settleChild(task.childSessionId, 'Paused.');+ await runtime.dispatch({ targetSessionId: task.childSessionId, message: 'Unrelated direct input.', clientId: 'ordinary-paused-input' });+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' });+ expect(runtime.dispatch.mock.calls.some(([input]) => input.clientId?.startsWith(`bot-delegation-unpause:${task.delegationId}:`))).toBe(true);+ expect(runtime.coordinator!.getQueueControlSnapshot(task.childSessionId).pendingQueue.some(input => input.clientId.startsWith(`bot-delegation-unpause:${task.delegationId}:`))).toBe(true);+ } finally { runtime.dispose(); }+ });++ it.each(['retry-saved-terminal', 'missing-terminal', 'saved-terminal', 'expired-saved-terminal', 'user-before-restore', 'edit-before-restore', 'text-before-restore', 'content-before-restore', 'merge-before-restore'] as const)('restores an owned supplement with %s', async scenario => {+ await seedPair();+ const queueSnapshots = new Map<string, AgentInputQueuedMessage[]>();+ const before = createDelegationRuntime({ taskControl: true, queueSnapshots,+ readSessionExecution: () => ({ instanceId: 'before-restart', generation: 1 }) });+ let after: ReturnType<typeof createDelegationRuntime> | undefined;+ try {+ const task = await before.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Original work.' });+ if (!task.ok) throw new Error('missing task');+ if (scenario === 'retry-saved-terminal' || scenario === 'saved-terminal' || scenario === 'expired-saved-terminal') {+ // The native terminal receipt is durable, but settlement was interrupted.+ h.sqlite!.exec("CREATE TEMP TRIGGER fail_terminal_commit BEFORE UPDATE OF status ON bot_delegations WHEN NEW.status = 'completed' BEGIN SELECT RAISE(FAIL, 'fixture restart'); END");+ await expect(before.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done',+ execution: { instanceId: 'before-restart', generation: 1 }, resultText: 'Earlier result.',+ hadPendingInputAtTerminal: false })).rejects.toThrow();+ h.sqlite!.exec('DROP TRIGGER fail_terminal_commit');+ }+ await before.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Queued supplement.' });+ if (scenario === 'merge-before-restore') await before.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Second supplement.' });+ h.sqlite!.prepare('UPDATE sessions SET last_turn_ended_at = 10000 WHERE id = ?').run(task.childSessionId);+ before.dispose();+ if (scenario === 'retry-saved-terminal') {+ queueSnapshots.set(task.childSessionId, queueSnapshots.get(task.childSessionId)!.map(item => ({+ ...item, clientId: 'random-retry-clone', supersedesUserClientId: item.clientId,+ chatMessage: { ...item.chatMessage, clientId: 'random-retry-clone' },+ })));+ }+ const execution = { instanceId: 'after-restart', generation: 1 };+ after = createDelegationRuntime({ taskControl: true, queueSnapshots, startTime: scenario === 'expired-saved-terminal' ? 2_000_000 : 11000,+ readSessionExecution: () => execution });+ if (scenario.endsWith('before-restore')) {+ await after.coordinator!.ensureQueueRestored(task.childSessionId);+ const queued = after.coordinator!.getQueueControlSnapshot(task.childSessionId).pendingQueue;+ const item = queued[0];+ const edited = { ...item, text: 'Edited supplement.', persistedContent: 'Edited supplement.',+ chatMessage: { ...item.chatMessage, content: 'Edited supplement.' } };+ if (scenario === 'edit-before-restore') {+ expect(after.coordinator!.replaceQueuedMessage(task.childSessionId, item.clientId, edited)).toBe(true);+ } else if (scenario === 'text-before-restore') {+ after.coordinator!.updateText(task.childSessionId, item.clientId, 'Edited supplement.');+ } else if (scenario === 'content-before-restore') {+ expect(after.coordinator!.updateContentWithResult(task.childSessionId, item.clientId, edited).updated).toBe(true);+ } else if (scenario === 'merge-before-restore') {+ expect(after.coordinator!.mergeQueuedMessagesAtomically(task.childSessionId, queued.map(q => q.clientId), () => edited).merged).toBe(true);+ }+ after.coordinator!.resume(task.childSessionId);+ } else {+ await after.delegation.restore();+ }+ if (scenario === 'expired-saved-terminal') {+ expect(await after.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'timed-out' } });+ expect(after.started.some(turn => turn.sessionId === task.childSessionId)).toBe(false);+ return;+ }+ await vi.waitFor(() => expect(after!.started).toHaveLength(1));+ expect(after.started[0].sessionId).toBe(task.childSessionId);+ if (scenario.endsWith('before-restore')) await after.delegation.restore();+ expect(after.dispatch).not.toHaveBeenCalled(); // Resume the saved input, never replay initial dispatch.+ await after.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Supplement result.', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Supplement result.' });+ } finally { before.dispose(); after?.dispose(); }+ });++ it.each([false, true])('binds automatic retry provenance without hiding the original input (cold: %s)', async cold => {+ await seedPair();+ let execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Retry delegated work.' });+ if (!task.ok) throw new Error('missing task');+ execution = { instanceId: 'native', generation: 2 };+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Supplement', idempotencyKey: 'auto-source' });+ const source = runtime.dispatch.mock.calls.at(-1)![0].clientId!;+ execution = { instanceId: 'native', generation: 3 };+ if (!cold) await expect(runtime.delegation.acceptQueuedSessionInput(task.childSessionId, 'unknown-clone', undefined, false,+ `bot-delegation-interject:${task.delegationId}:not-accepted`)).rejects.toThrow('no accepted delegation receipt');+ await runtime.delegation.acceptQueuedSessionInput(task.childSessionId, 'auto-clone', undefined, cold, source);+ runtime.delegation.confirmQueuedSessionInputDispatched(task.childSessionId, 'auto-clone');+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Automatic retry result.', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Automatic retry result.' });+ } finally { runtime.dispose(); }+ });++ it('binds a cold-restored retry clone through its original delegated input', async () => {+ await seedPair();+ const before = createDelegationRuntime({ readSessionExecution: () => ({ instanceId: 'before-restart', generation: 1 }) });+ let after: ReturnType<typeof createDelegationRuntime> | undefined;+ try {+ const task = await before.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Retry saved supplement.' });+ if (!task.ok) throw new Error('missing task');+ const originalId = `bot-delegation-interject:${task.delegationId}:retry`;+ await before.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done',+ execution: { instanceId: 'before-restart', generation: 1 },+ hadPendingInputAtTerminal: true, pendingInputClientIds: [originalId] });+ before.dispose();+ const execution = { instanceId: 'after-restart', generation: 1 };+ after = createDelegationRuntime({ readSessionExecution: () => execution });+ await after.delegation.acceptQueuedSessionInput(task.childSessionId, 'random-retry-clone', originalId, true);+ after.delegation.confirmQueuedSessionInputDispatched(task.childSessionId, 'random-retry-clone');+ await after.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Retried supplement completed.', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Retried supplement completed.' });+ } finally { before.dispose(); after?.dispose(); }+ });++ it('binds a restored explicit resume queue to the new native execution', async () => {+ await seedPair();+ const queueSnapshots = new Map<string, AgentInputQueuedMessage[]>();+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots,+ readSessionExecution: () => ({ instanceId: 'before-restart', generation: 1 }) });+ let restored: ReturnType<typeof createDelegationRuntime> | undefined;+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Resume exactly once.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ await runtime.settleChild(task.childSessionId, 'Stopped.');+ runtime.advance(1000);+ const fault = loseResumeCommitReceipt(true);+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' });+ fault.mockRestore();+ runtime.dispose();+ const execution = { instanceId: 'after-restart', generation: 1 };+ restored = createDelegationRuntime({ taskControl: true, queueSnapshots, startTime: 11000,+ readSessionExecution: () => execution });+ await restored.delegation.restore();+ await vi.waitFor(() => expect(restored!.started).toHaveLength(1));+ await restored.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution,+ resultText: 'Resumed result.', hadPendingInputAtTerminal: false });+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'completed', result_summary: 'Resumed result.' });+ } finally { runtime.dispose(); restored?.dispose(); }+ });++ it('ignores the prior terminal event while a continuation is queued before native reservation', async () => {+ await seedPair();+ let unavailable = false;+ const execution = { instanceId: 'native', generation: 1 };+ const runtime = createDelegationRuntime({ readSessionExecution: () => execution, transientUnavailable: () => unavailable });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'First run.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.settleChild(task.childSessionId, 'First result.');+ unavailable = true;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Continue.' }))+ .toMatchObject({ ok: true, queued: true });+ // Still generation 1: checking only the live native identity is insufficient.+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'done', execution, resultText: 'Old duplicate.' });+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'queued' } });+ } finally { runtime.dispose(); }+ });++ it('rechecks explicit archive inside the continuation transaction', async () => {+ await seedPair();+ let childId = '';+ const originalTx = h.tx!;+ h.tx = async (name, args) => {+ if (name === 'bots.reopenDelegation') h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run(childId);+ return originalTx(name, args);+ };+ const runtime = createDelegationRuntime();+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.settleChild(task.childSessionId, 'Done.');+ childId = task.childSessionId;+ const before = runtime.started.length;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Continue.' }))+ .toMatchObject({ ok: false, errorCode: 'SESSION_TASK_STATE_CHANGED' });+ expect(runtime.started).toHaveLength(before);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'completed', session_status: 'archived' } });+ } finally { h.tx = originalTx; runtime.dispose(); }+ });+it('binds a prepared worktree before first dispatch and rejects unavailable isolation', async () => {await seedPair();const workspace = join(h.userDataDir, 'task-project-worktree');@@ -4036,7 +4995,7 @@ describe('Bot Session task end-to-end runtime', () => {} finally { unavailable.dispose(); }});- it('commits the worktree snapshot for each continuation and leaves no child when that transaction fails', async () => {+ it('keeps the same worktree owner and Session across continuations, including a failed transaction', async () => {await seedPair();const workspace = join(h.userDataDir, 'continued-worktree');mkdirSync(workspace, { recursive: true });@@ -4070,7 +5029,7 @@ describe('Bot Session task end-to-end runtime', () => {const previous = owner;const resumed = await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Continue.' });expect(resumed).toMatchObject({ ok: true, resumed: true });- expect(owner).not.toBe(previous);+ expect(owner).toBe(previous);expect(h.sqlite!.prepare('SELECT working_dir AS cwd, worktree_path AS path FROM sessions WHERE id = ?').get(owner)).toEqual({ cwd: normalizeWorkingDirForStorage(workspace), path: workspace });expect(runtime.started.at(-1)?.sessionId).toBe(owner);@@ -4868,7 +5827,14 @@ describe('Bot Session task end-to-end runtime', () => {);expect(continued).toMatchObject({ ok: true, resumed: true });if (!continued.ok || !continued.childSessionId) return;- expect(continued.childSessionId).not.toBe(started.childSessionId);+ expect(continued.childSessionId).toBe(started.childSessionId);+ expect(await runtime.delegation.listDelegations('session-1')).toMatchObject({+ delegations: [expect.objectContaining({ id: started.delegationId, childSessionId: started.childSessionId, status: 'running' })],+ });+ expect(runtime.started.filter(turn => turn.sessionId === started.childSessionId)).toHaveLength(2);+ expect(runtime.dispatch.mock.calls.at(-1)?.[0].clientId).toBe(`bot-delegation-start:${started.delegationId}:2`);+ expect(h.sqlite!.prepare('SELECT content FROM messages WHERE session_id = ? AND role = ?').all(started.childSessionId, 'assistant'))+ .toContainEqual({ content: '第一版结果。' });await runtime.settleChild(continued.childSessionId, '第二版结果,含风险清单。');const receipts = h.sqlite!.prepare(@@ -5388,9 +6354,10 @@ describe('Bot Session task end-to-end runtime', () => {}});- it('recovers a completed child result when the app restores active tasks', async () => {+ it.each([[10_000, 'active'], [2_000_000, 'active'], [10_000, 'archived'], [2_000_000, 'archived']] as const)('recovers the durable terminal at time %s with Session %s', async (startTime, sessionStatus) => {await seedPair();- const beforeRestart = createDelegationRuntime();+ const execution = { instanceId: 'before-restart', generation: 1 };+ const beforeRestart = createDelegationRuntime({ readSessionExecution: () => execution });const started = await beforeRestart.delegation.startSessionTask({callerSessionId: 'session-1',objective: '应用重启后也要收到结果。',@@ -5415,11 +6382,22 @@ describe('Bot Session task end-to-end runtime', () => {SET active_turn_started_at = ?, last_turn_ended_at = ?WHERE id = ?`,).run(10_000, 20_000, started.childSessionId);+ // Crash after recording the native terminal event, before terminal settlement.+ h.sqlite!.exec("CREATE TEMP TRIGGER fail_terminal_commit BEFORE UPDATE OF status ON bot_delegations WHEN NEW.status = 'completed' BEGIN SELECT RAISE(FAIL, 'fixture restart'); END");+ await expect(beforeRestart.delegation.settleSession({ childSessionId: started.childSessionId, outcome: 'done', execution,+ resultMessageClientId: 'restored-answer-client', hadPendingInputAtTerminal: false })).rejects.toThrow();+ h.sqlite!.exec('DROP TRIGGER fail_terminal_commit');+ h.sqlite!.prepare('INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)')+ .run('later-direct-answer', 'later-direct-answer-client', started.childSessionId, 'assistant', 'Unrelated direct answer.', 40000);+ h.sqlite!.prepare('UPDATE sessions SET active_turn_started_at = 30000, last_turn_ended_at = 40000 WHERE id = ?').run(started.childSessionId);beforeRestart.dispose();- const afterRestart = createDelegationRuntime();+ h.sqlite!.prepare('UPDATE sessions SET status = ? WHERE id = ?').run(sessionStatus, started.childSessionId);+ const afterRestart = createDelegationRuntime({ startTime });try {await afterRestart.delegation.restore();+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').pluck().get(started.childSessionId)).toBe(sessionStatus);+ expect(afterRestart.started.some(turn => turn.sessionId === started.childSessionId)).toBe(false);await expect(afterRestart.delegation.getSessionTask('session-1', started.delegationId),).resolves.toMatchObject({@@ -5432,6 +6410,24 @@ describe('Bot Session task end-to-end runtime', () => {}});+ it('leaves an unverified restart result unresolved instead of adopting a later direct turn', async () => {+ await seedPair();+ const before = createDelegationRuntime({ readSessionExecution: () => ({ instanceId: 'old-native', generation: 1 }) });+ const task = await before.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Lost original callback.' });+ if (!task.ok) throw new Error('missing task');+ h.sqlite!.prepare('INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)')+ .run('unrelated-result', 'unrelated-result-client', task.childSessionId, 'assistant', 'Direct turn answer.', 40000);+ h.sqlite!.prepare('UPDATE sessions SET active_turn_started_at = 30000, last_turn_ended_at = 40000 WHERE id = ?').run(task.childSessionId);+ before.dispose();+ const after = createDelegationRuntime();+ try {+ await after.delegation.restore();+ expect(h.sqlite!.prepare('SELECT status, result_summary FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'running', result_summary: null });+ expect(after.started).toHaveLength(0);+ } finally { after.dispose(); }+ });+it('re-delivers a terminal result whose durable completion wake is still pending', async () => {await seedPair();const beforeRestart = createDelegationRuntime();diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex f7bb759019..4b1dbd9e57 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -732,7 +732,7 @@ function insertBotSession(db: Database.Database, s: Record<string, unknown>): vofunction botsFinishDelegation(db: Database.Database,args: unknown,-): { id: string; parentSessionId: string | null; childSessionId: string | null; status: string } | null {+): { id: string; parentSessionId: string | null; childSessionId: string | null; targetBotId: string | null; runSequence: number; status: string } | null {const p = asRecord(args, 'bots.finishDelegation args');return db.transaction(() => {const values: unknown[] = [@@ -743,22 +743,28 @@ function botsFinishDelegation(if (p.tokensUsed !== undefined) values.push(expectNumber(p.tokensUsed, 'tokensUsed'));const completedAt = expectNumber(p.completedAt, 'completedAt');values.push(completedAt, completedAt, expectString(p.delegationId, 'delegationId'));+ let receiptGuard = '';+ if (p.expectedRunSequence !== undefined) {+ receiptGuard += ' AND run_sequence = ?';+ values.push(expectNumber(p.expectedRunSequence, 'expectedRunSequence'));+ }+ if (p.expectedExecution !== undefined) {+ const receipt = asRecord(p.expectedExecution, 'expectedExecution');+ receiptGuard += " AND json_extract(permission_snapshot_json, '$.taskExecution.runSequence') = run_sequence AND json_extract(permission_snapshot_json, '$.taskExecution.instanceId') = ? AND json_extract(permission_snapshot_json, '$.taskExecution.generation') = ?";+ values.push(expectString(receipt.instanceId, 'instanceId'), expectNumber(receipt.generation, 'generation'));+ }const row = db.prepare(`UPDATE bot_delegations SET status = ?, result_summary = ?, output_artifacts_json = ?, last_error = ?${tokenSet}, pending_interaction_json = NULL, completed_at = ?, completion_delivered_at = NULL, updated_at = ?- WHERE id = ? AND status IN ('queued','running','waiting')- RETURNING id, parent_session_id AS parentSessionId, child_session_id AS childSessionId, status`)+ WHERE id = ? AND status IN ('queued','running','waiting') ${receiptGuard}+ RETURNING id, parent_session_id AS parentSessionId, child_session_id AS childSessionId, target_bot_id AS targetBotId, run_sequence AS runSequence, status`).get(...values) as- | { id: string; parentSessionId: string | null; childSessionId: string | null; status: string }+ | { id: string; parentSessionId: string | null; childSessionId: string | null; targetBotId: string | null; runSequence: number; status: string }| undefined;if (!row) return null;- if (row.childSessionId) {- // The delegation terminal transition owns its child task's terminal- // archive: `sessions.setStatus` refuses `source = 'bot'` rows on purpose- // (generic UI archive must not bypass Bot lifecycle bookkeeping), so the- // archive has to happen in this very transaction. Doing it anywhere else- // (a follow-up generic write that can also be swallowed) leaves the- // child task `active` forever and the guardian reports a supervision- // anomaly (PR #2829 QA).+ if (row.childSessionId && row.targetBotId !== null) {+ // Only legacy Bot-to-Bot execution containers have this archive lifecycle.+ // An independent Session (target_bot_id IS NULL) outlives a turn, including+ // failure/cancellation: visibility and explicit archive belong to its user.db.prepare(`UPDATE sessions SET status = 'archived', updated_at = ?WHERE id = ? AND status = 'active'`).run(completedAt, row.childSessionId);@@ -868,13 +874,14 @@ function botsReopenDelegation(return db.transaction(() => {const current = db.prepare(`SELECT requesting_bot_id AS requestingBotId,target_bot_id AS targetBotId, target_profile_version AS targetProfileVersion,- parent_session_id AS parentSessionId, status+ parent_session_id AS parentSessionId, child_session_id AS childSessionId, statusFROM bot_delegations WHERE id = ?`).get(delegationId) as| {requestingBotId: string;targetBotId: string | null;targetProfileVersion: number | null;parentSessionId: string | null;+ childSessionId: string | null;status: string;}| undefined;@@ -892,9 +899,20 @@ function botsReopenDelegation(.get(requestingBotId, delegationId) as { count: number };if (count.count >= maxActiveChildren) throw new Error('BOT_DELEGATION_CONCURRENCY_LIMIT');- const session = asRecord(p.session, 'session');- insertBotSession(db, session);const childSessionId = expectString(p.childSessionId, 'childSessionId');+ if (targetBotId === null) {+ // Recheck in the transaction, after any asynchronous worktree lookup.+ // Never resurrect an explicitly archived/deleted task or replace history.+ const child = db.prepare('SELECT status FROM sessions WHERE id = ?').get(childSessionId) as+ { status: string } | undefined;+ if (current.childSessionId !== childSessionId || child?.status !== 'active') {+ return { reopened: false, previousParentSessionId: current.parentSessionId };+ }+ db.prepare('UPDATE sessions SET parent_session_id = ?, updated_at = ? WHERE id = ?')+ .run(expectString(p.parentSessionId, 'parentSessionId'), reopenedAt, childSessionId);+ } else {+ insertBotSession(db, asRecord(p.session, 'session'));+ }if (p.worktreePath != null) {db.prepare('UPDATE sessions SET worktree_path = ? WHERE id = ?').run(expectString(p.worktreePath, 'worktreePath'), childSessionId);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 00ba093103..1f0c731cbc 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -3505,6 +3505,7 @@ describe('AgentInputCoordinator send transaction', () => {const second = h.supersedeRetriedUserTurn.mock.calls[1]?.[1];expect(second?.supersededUserClientId).toBe(firstClone);expect(second?.retryUserClientId).not.toBe(firstClone);+ expect(h.onDispatchedUserTurn.mock.calls[2]?.[1]?.retrySourceClientId).toBe('q-first');});it('does not supersede when the retry dispatch fails before the clone is persisted', async () => {@@ -10966,7 +10967,7 @@ describe('AgentInputCoordinator replaceQueuedMessage(Orca lead 排队消息修const sid = 'replace-after-clear';await h.coordinator.ensureQueueRestored(sid);h.setRunning(true);- h.coordinator.enqueue(sid, makeItem('q-1', 'before'));+ h.coordinator.enqueue(sid, { ...makeItem('q-1', 'before'), retrySourceClientId: 'original-retry-source' });await flush();const projected = h.coordinator.getProjection(sid).pendingQueue[0];@@ -10984,6 +10985,7 @@ describe('AgentInputCoordinator replaceQueuedMessage(Orca lead 排队消息修clientId: 'q-1',text: 'after',hostAcceptedAtMs: acceptedAtMs,+ retrySourceClientId: 'original-retry-source',});const restarted = createHarness();@@ -11566,6 +11568,7 @@ describe('AgentInputCoordinator 中断自动续跑', () => {expect.objectContaining({autoResume: true,autoResumeInfo: TAKEOVER_INFO,+ retrySourceClientId: 'q-first',supersedesUserClientId: undefined,}),);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.tsindex eb65afaa6a..5746064c70 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts@@ -1383,6 +1383,7 @@ describe('Bot adapters in the shared event pipeline', () => {await microtasks();expect(h.deps.botDelegationServiceHolder.settleSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({childSessionId: 'task', outcome: 'error', resultText: result,+ execution: { instanceId: h.session.instanceId, generation: 4 },error: 'Pi reached the model output limit.',}));h.deps.autoResumeBookkeeping.consumeFailedTurnCompletionTail.mockReturnValue(true);@@ -1408,6 +1409,21 @@ describe('Bot adapters in the shared event pipeline', () => {}));});+ it('preserves retry ownership in the terminal queue snapshot', async () => {+ const h = harness();+ h.deps.agentInputCoordinatorHolder.getQueueControlSnapshot.mockReturnValue({ pendingQueue: [+ { clientId: 'retry-clone', supersedesUserClientId: 'bot-delegation-interject:task:original' },+ { clientId: 'auto-clone', retrySourceClientId: 'bot-delegation-interject:task:auto' },+ { clientId: 'direct-input' },+ ] });+ h.emit(event('done', { result: 'prior result' }));+ await microtasks();+ expect(h.deps.botDelegationServiceHolder.settleSession).toHaveBeenCalledWith(expect.objectContaining({+ pendingInputClientIds: ['retry-clone', 'bot-delegation-interject:task:original', 'auto-clone', 'bot-delegation-interject:task:auto', 'direct-input'],+ }));+ await h.dispose();+ });+it('carries a pending follow-up into task settlement and remembers compact boundaries without rebuilding early', async () => {const h = harness();h.emit(event('compact_boundary'));diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex c2d4e6f97e..7307917d83 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -494,6 +494,7 @@ export interface AgentInputCoordinatorDeps {onAcceptedQueuedMessage?: (sessionId: string,item: AgentInputQueuedMessage,+ restoredFromSnapshot?: boolean,) => void | Promise<void>;/*** Awaited only after vendor dispatch is irreversible (`accepted=true`).@@ -1037,6 +1038,7 @@ export class AgentInputCoordinator {* emit 会因"未恢复"跳过持久化,旧快照删不掉,下次打开会话又诈尸。*/private readonly restoredQueueSessions = new Set<string>();+ private readonly restoredQueueItems = new WeakSet<AgentInputQueuedMessage>();private readonly restoreAttempted = new Set<string>();private readonly queueRestorePromises = new Map<string, Promise<void>>();private readonly lastQueueSnapshotJson = new Map<string, string>();@@ -1348,6 +1350,7 @@ export class AgentInputCoordinator {state.activeTurn === null &&state.steeringQueueClientIds.length === 0 &&!this.deps.isTurnRunning(sessionId);+ for (const item of restored) this.restoredQueueItems.add(item);state.pendingQueue = [...restored, ...state.pendingQueue];if (wasQuiet) {state.queuePaused = true;@@ -2815,6 +2818,7 @@ export class AgentInputCoordinator {// retry-supersede 只属于零产出克隆重发。续跑分支的原消息是真实历史,// 不取代;展开继承的旧值若留着,落库后会把本轮"有产出失败"的 error 行// 一并误藏(窗口从更早的行一直铺到本条)。+ retrySourceClientId: recovery.item.retrySourceClientId ?? recovery.item.supersedesUserClientId ?? recovery.item.clientId,supersedesUserClientId: undefined,// 自动恢复不是计划批准:保留原 Plan/权限选项,不能因隐藏 CONTINUE// 降到 Full access。人工 Retry 仍沿用既有合成 UI 动作策略。@@ -2878,6 +2882,7 @@ export class AgentInputCoordinator {autoResumeInfo: opts?.auto ? (previousAutoResumeInfo ?? undefined) : undefined,// 自动 clone 自身会被 renderer 隐藏,不能再软删原始可见 user 行;人工 Retry// 才用可见克隆取代旧行。显式覆盖也避免继承上一轮的隐藏标记。+ retrySourceClientId: recovery.item.retrySourceClientId ?? recovery.item.supersedesUserClientId ?? recovery.item.clientId,supersedesUserClientId: opts?.auto ? undefined : recovery.item.clientId,chatMessage: {...(retryItem ?? recovery.item).chatMessage,@@ -3008,9 +3013,9 @@ export class AgentInputCoordinator {delete updated.sessionReferencesRequireTrustedSnapshot;delete updated.trustedSessionReferenceContexts;}- return finalizeUpdatedMessage && newText !== entry.text+ return this.preserveRestoredQueueProvenance(entry, finalizeUpdatedMessage && newText !== entry.text? finalizeUpdatedMessage(updated)- : updated;+ : updated);});this.emit(sessionId);return this.getProjection(sessionId);@@ -3061,14 +3066,23 @@ export class AgentInputCoordinator {|| updated.sessionRefs !== current.sessionRefs|| updated.agentReferences !== current.agentReferences;const nextQueue = [...state.pendingQueue];- nextQueue[index] = finalizeUpdatedMessage && authorizationContentChanged+ nextQueue[index] = this.preserveRestoredQueueProvenance(current, finalizeUpdatedMessage && authorizationContentChanged? finalizeUpdatedMessage(updated)- : updated;+ : updated);state.pendingQueue = nextQueue;this.emit(sessionId);return { projection: this.getProjection(sessionId), updated: true };}+ private preserveRestoredQueueProvenance(current: AgentInputQueuedMessage, replacement: AgentInputQueuedMessage): AgentInputQueuedMessage {+ if (current.clientId === replacement.clientId) {+ if (this.restoredQueueItems.has(current)) this.restoredQueueItems.add(replacement);+ // Editing content cannot erase or forge the host's stable retry lineage.+ replacement.retrySourceClientId = current.retrySourceClientId;+ }+ return replacement;+ }+/*** 整条排队消息原位替换(main 侧受信调用方专用;Orca lead 与会话控制面共用)。* 与 updateText / updateContent 的差别:替换体由调用方@@ -3099,7 +3113,7 @@ export class AgentInputCoordinator {if (current.hostAcceptedAtMs === undefined) delete replacement.hostAcceptedAtMs;else replacement.hostAcceptedAtMs = current.hostAcceptedAtMs;const nextQueue = [...state.pendingQueue];- nextQueue[index] = replacement;+ nextQueue[index] = this.preserveRestoredQueueProvenance(current, replacement);state.pendingQueue = nextQueue;this.emit(sessionId);return true;@@ -3154,7 +3168,7 @@ export class AgentInputCoordinator {const removed = presentTargets.slice(1);state.pendingQueue = [...state.pendingQueue.slice(0, firstIndex),- replacement,+ this.preserveRestoredQueueProvenance(survivor, replacement),...state.pendingQueue.slice(firstIndex + presentTargets.length),];const removedIds = new Set(removed.map((item) => item.clientId));@@ -4503,7 +4517,11 @@ export class AgentInputCoordinator {// host 把排队 orca 消息的 accepted 副作用挂在这个 hook 上(置 running /// autoBridgePending), 必须 await 完才能放行 vendor turn —— fire-and-forget// 会让快 worker 在状态可见前结束 turn, 桥接被 turn-end handler 误跳过。- await this.deps.onAcceptedQueuedMessage?.(sessionId, head);+ if (this.restoredQueueItems.has(head)) {+ await this.deps.onAcceptedQueuedMessage?.(sessionId, head, true);+ } else {+ await this.deps.onAcceptedQueuedMessage?.(sessionId, head);+ }if (!this.isActiveTurnCurrent(sessionId, active)) {throw new Error('[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch',diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex 07ea4a4d6f..7bc540fac2 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -1,4 +1,5 @@import { existsSync, statSync } from 'node:fs';+import type { AgentInputCoordinator } from './agent-input-coordinator.js';import path from 'node:path';import { createHash, randomUUID } from 'node:crypto';@@ -75,16 +76,50 @@ type DispatchResult =}| { ok: false; errorCode: string; message: string };+export interface DelegationExecutionReceipt {+ instanceId: string;+ generation: number;+}++function isDelegationQueuedInput(delegationId: string, clientId: string): boolean {+ return ['bot-delegation-start', 'bot-delegation-resume', 'bot-delegation-unpause', 'bot-delegation-interject']+ .some(kind => clientId === `${kind}:${delegationId}` || clientId.startsWith(`${kind}:${delegationId}:`));+}++/** Withdraw only the expired delegation's pending messages, including cold queues. */+export async function discardDelegationQueuedInputs(+ queue: Pick<AgentInputCoordinator, 'ensureQueueRestored' | 'getQueueControlSnapshot' | 'remove'>,+ sessionId: string,+ delegationId: string,+ flush: (sessionId: string) => Promise<void>,+): Promise<void> {+ await queue.ensureQueueRestored(sessionId);+ for (const item of queue.getQueueControlSnapshot(sessionId).pendingQueue) {+ if (isDelegationQueuedInput(delegationId, item.clientId)+ || (item.supersedesUserClientId && isDelegationQueuedInput(delegationId, item.supersedesUserClientId))+ || (item.retrySourceClientId && isDelegationQueuedInput(delegationId, item.retrySourceClientId))) {+ queue.remove(sessionId, item.clientId);+ }+ }+ await flush(sessionId);+}+export interface BotDelegationServiceDeps {+ /** Native reservation identity, including replacement Session instances. */+ readSessionExecution?: (sessionId: string) => DelegationExecutionReceipt | null;+ /** Non-expiring native-close fence shared with the Session send boundary. */+ withSessionLock?: (sessionId: string, operation: () => Promise<void>) => Promise<void>;dispatch: (params: {targetSessionId: string;message: string;persistedContent?: string;clientId?: string;- onAccepted?: () => void | Promise<void>;+ /** true only for a persisted-message dedupe hit, not native acceptance. */+ onAccepted?: (replayed?: boolean) => void | Promise<void>;dispatcherSessionId?: string;}) => Promise<DispatchResult>;abortSession: (sessionId: string) => Promise<void>;+ discardDelegationQueuedInputs?: (sessionId: string, delegationId: string) => Promise<void>;taskControl?: {steer(params: { callerSessionId: string; targetSessionId: string; message: string; queuedMessageId?: string }): Promise<SessionSteerResult>;stop(params: { targetSessionId: string }): Promise<SessionStopResult>;@@ -132,9 +167,10 @@ export interface BotDelegationServiceDeps {*/resolveInteraction?: (requestId: string, decision: InteractionDecision) => boolean;/** 子任务这一路改过的文件;缺省不采集交付物。 */- collectArtifacts?: (sessionId: string) => Promise<BotDelegationArtifact[]>;+ collectArtifacts?: (sessionId: string, inputClientIds: string[]) => Promise<BotDelegationArtifact[]>;/** Pending follow-up input must run before this Session task can become terminal. */hasPendingInput?: (sessionId: string) => boolean;+ readPendingInputClientIds?: (sessionId: string) => string[];/** The active Bot route may differ from its canonical row after a profile switch/fallback. */readCallerRuntime?: (sessionId: string) => (Pick<typeof sessions.$inferSelect,@@ -393,15 +429,164 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {cleanupRetryTimers.delete(delegationId);};+ const sameExecution = (sessionId: string, expected: DelegationExecutionReceipt | null | undefined): boolean => {+ if (!deps.readSessionExecution) return true;+ const current = deps.readSessionExecution(sessionId);+ return !!expected && current?.instanceId === expected.instanceId && current.generation === expected.generation;+ };++ const matchesDelegatedExecution = (row: DelegationRow, allowIdle = false): boolean => {+ if (!deps.readSessionExecution) return true;+ if (!row.childSessionId) return false;+ const current = deps.readSessionExecution(row.childSessionId);+ if (!current) return allowIdle;+ const receipt = parseRecord(row.permissionSnapshotJson).taskExecution as+ (DelegationExecutionReceipt & { runSequence: number }) | undefined;+ return receipt?.runSequence === row.runSequence && receipt.instanceId === current.instanceId+ && receipt.generation === current.generation;+ };++ const controlDelegatedExecution = async (row: DelegationRow, operation: () => Promise<void>, allowIdle = false): Promise<boolean> => {+ if (!row.childSessionId || !matchesDelegatedExecution(row, allowIdle)) return false;+ let applied = false;+ const guarded = async () => {+ if (!matchesDelegatedExecution(row, allowIdle)) return;+ await operation();+ applied = true;+ };+ if (deps.withSessionLock) await deps.withSessionLock(row.childSessionId, guarded);+ else await guarded();+ return applied;+ };++ // Store only a native turn actually accepted for this delegation run. A later+ // direct Session turn must never replace this receipt merely by becoming live.+ const executionSnapshot = (row: DelegationRow, clientId?: string,+ execution = row.childSessionId && deps.readSessionExecution?.(row.childSessionId), originalClientId = clientId) => {+ const snapshot = execution+ ? sql`json_set(${botDelegations.permissionSnapshotJson}, '$.taskExecution', json(${JSON.stringify({ ...execution, runSequence: row.runSequence, ...(clientId ? { clientId } : {}) })}))`+ : botDelegations.permissionSnapshotJson;+ if (!clientId) return snapshot;+ const inputIds = sql`json_insert(COALESCE(json_extract(${botDelegations.permissionSnapshotJson}, '$.taskAcceptedInputIds'), '[]'), '$[#]', ${clientId})`;+ const withAlias = originalClientId && originalClientId !== clientId+ ? sql`json_insert(${inputIds}, '$[#]', ${originalClientId})` : inputIds;+ return sql`json_set(${snapshot}, '$.taskAcceptedInputIds', ${withAlias})`;+ };++ const acceptExecution = async (row: DelegationRow, clientId?: string, originalClientId = clientId): Promise<void> => {+ if (!deps.readSessionExecution) return;+ const [accepted] = await getDbClient().drizzle.update(botDelegations).set({+ permissionSnapshotJson: executionSnapshot(row, clientId, undefined, originalClientId),+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence),+ inArray(botDelegations.status, ['queued', 'running', 'waiting'])))+ .returning({ id: botDelegations.id });+ if (!accepted) throw new Error('Delegated execution receipt was not committed');+ };++ const readAcceptedInputIds = (row: DelegationRow): string[] => {+ const ids = parseRecord(row.permissionSnapshotJson).taskAcceptedInputIds;+ return Array.isArray(ids) ? [...new Set(ids.filter((id): id is string => typeof id === 'string'))] : [];+ };++ // Message persistence precedes native acceptance. Each task input needs its+ // own receipt; another turn's receipt cannot prove it was delivered.+ const dispatchTrackedInput = async (+ row: DelegationRow,+ input: { clientId: string; message: string; persistedContent?: string; dispatcherSessionId?: string },+ retryAttempt = false,+ ): Promise<{ result: DispatchResult; row: DelegationRow; clientId: string }> => {+ const db = getDbClient().drizzle;+ const retry = parseRecord(row.permissionSnapshotJson).taskRecoveryRetry as+ { runSequence: number; originalClientId: string; clientId: string } | undefined;+ const clientId = retry?.runSequence === row.runSequence && retry.originalClientId === input.clientId+ ? retry.clientId : input.clientId;+ let replayed = false;+ let acceptedThisAttempt = false;+ const result = await deps.dispatch({ ...input, clientId, targetSessionId: row.childSessionId!,+ onAccepted: async persisted => {+ if (persisted) { replayed = true; return; }+ await acceptExecution(row, clientId, input.clientId);+ acceptedThisAttempt = true;+ },+ });+ if (!result.ok && acceptedThisAttempt) {+ // Native acceptance may still be cancelled before vendor dispatch. Only+ // undo this input's receipt; never replace a later run or another input.+ const previous = parseRecord(row.permissionSnapshotJson).taskExecution;+ const restored = previous+ ? sql`json_set(${botDelegations.permissionSnapshotJson}, '$.taskExecution', json(${JSON.stringify(previous)}))`+ : sql`json_remove(${botDelegations.permissionSnapshotJson}, '$.taskExecution')`;+ await db.update(botDelegations).set({+ permissionSnapshotJson: sql`json_set(${restored}, '$.taskAcceptedInputIds',+ (SELECT json_group_array(value) FROM json_each(COALESCE(json_extract(${botDelegations.permissionSnapshotJson}, '$.taskAcceptedInputIds'), '[]'))+ WHERE value NOT IN (${clientId}, ${input.clientId})))`,+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence),+ sql`json_extract(${botDelegations.permissionSnapshotJson}, '$.taskExecution.clientId') = ${clientId}`,+ inArray(botDelegations.status, [...ACTIVE_DELEGATION_STATUSES])));+ }+ const [current] = await db.select().from(botDelegations).where(eq(botDelegations.id, row.id)).limit(1);+ if (!current || current.runSequence !== row.runSequence || !isActiveDelegation(current.status as DelegationStatus)) {+ return { clientId, row, result: { ok: false, errorCode: 'TASK_CHANGED', message: 'Task changed during recovery' } };+ }+ if (!result.ok || !replayed) return { clientId, result, row: current };+ const receipt = parseRecord(current.permissionSnapshotJson).taskExecution as+ (DelegationExecutionReceipt & { runSequence: number; clientId?: string }) | undefined;+ if (readAcceptedInputIds(current).includes(input.clientId) || readAcceptedInputIds(current).includes(clientId)+ || (receipt?.runSequence === row.runSequence && receipt.clientId === clientId)) return { clientId, result, row: current };+ if (current.permissionSnapshotJson !== row.permissionSnapshotJson) {+ return { clientId, row: current, result: { ok: false, errorCode: 'TASK_CHANGED', message: 'Recovery state changed before retry' } };+ }+ const next = { runSequence: row.runSequence, originalClientId: input.clientId, clientId: `${input.clientId}:retry:${createId()}` };+ const [saved] = await db.update(botDelegations).set({+ permissionSnapshotJson: sql`json_set(${botDelegations.permissionSnapshotJson}, '$.taskRecoveryRetry', json(${JSON.stringify(next)}))`,+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence),+ eq(botDelegations.permissionSnapshotJson, current.permissionSnapshotJson),+ inArray(botDelegations.status, [...ACTIVE_DELEGATION_STATUSES]))).returning();+ if (!saved) return { clientId, row: current, result: { ok: false, errorCode: 'TASK_CHANGED', message: 'Task changed before recovery retry' } };+ if (retryAttempt) return { clientId, row: saved, result: { ok: false, errorCode: 'TEMPORARILY_UNAVAILABLE', message: 'Recovery input has not reached native acceptance' } };+ const validation = await validateDispatchPlan(saved);+ if (!validation.ok) return { clientId, row: saved, result: validation };+ return dispatchTrackedInput(saved, input, true);+ };+const cleanupChildSession = async (delegationId: string,childSessionId: string,abortChild: boolean,+ runSequence: number,+ execution?: DelegationExecutionReceipt | null,attempt = 0,): Promise<void> => {try {- if (abortChild) await deps.abortSession(childSessionId);- await deps.closeSession?.(childSessionId);+ const [current] = await getDbClient().drizzle.select({ completedAt: botDelegations.completedAt, runSequence: botDelegations.runSequence,+ permissionSnapshotJson: botDelegations.permissionSnapshotJson, targetBotId: botDelegations.targetBotId })+ .from(botDelegations).where(and(eq(botDelegations.id, delegationId),+ eq(botDelegations.childSessionId, childSessionId))).limit(1);+ if (current?.completedAt == null || current.runSequence !== runSequence) return;+ const receipt = parseRecord(current.permissionSnapshotJson).taskExecution as+ (DelegationExecutionReceipt & { runSequence: number }) | undefined;+ execution = execution === undefined+ ? (receipt?.runSequence === runSequence ? receipt+ : current.targetBotId !== null ? deps.readSessionExecution?.(childSessionId) ?? null : null)+ : execution;+ // Queue ownership does not require a live native instance. Remove only this+ // delegation's inputs, even if a direct turn now owns the Session.+ await deps.discardDelegationQueuedInputs?.(childSessionId, delegationId);+ // Stale retries must not even acquire the close fence: it rejects queued sends.+ if (!sameExecution(childSessionId, execution)) {+ clearCleanupRetryTimer(delegationId);+ return;+ }+ const cleanup = async () => {+ if (!sameExecution(childSessionId, execution)) return;+ if (abortChild) await deps.abortSession(childSessionId);+ if (!sameExecution(childSessionId, execution)) return;+ await deps.closeSession?.(childSessionId);+ };+ // Direct user sends do not change runSequence. Serialize the native+ // identity check and cleanup with their reservation boundary as well.+ if (deps.withSessionLock) await deps.withSessionLock(childSessionId, cleanup);+ else await cleanup();clearCleanupRetryTimer(delegationId);} catch (error) {log.warn('Session task cleanup failed; scheduling retry', {@@ -414,7 +599,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const delay = Math.min(MAX_RETRY_DELAY_MS, 1_000 * 2 ** Math.min(attempt, 6));const timer = setTimeout(() => {cleanupRetryTimers.delete(delegationId);- void cleanupChildSession(delegationId, childSessionId, abortChild, attempt + 1);+ void withTaskOperation(delegationId, () => cleanupChildSession(delegationId, childSessionId, abortChild, runSequence, execution, attempt + 1));}, delay);timer.unref?.();cleanupRetryTimers.set(delegationId, timer);@@ -818,6 +1003,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {lastError?: string | null;tokensUsed?: number;abortChild?: boolean;+ expectedRunSequence?: number;+ expectedExecution?: DelegationExecutionReceipt;}): Promise<{id: string;parentSessionId: string | null;@@ -835,6 +1022,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {lastError: params.lastError?.slice(0, 4_000) ?? null,...(typeof params.tokensUsed === 'number' ? { tokensUsed: params.tokensUsed } : {}),completedAt: at,+ expectedRunSequence: params.expectedRunSequence,+ expectedExecution: params.expectedExecution,},);if (updated) {@@ -850,21 +1039,23 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {pendingInteraction: null,});if (updated.childSessionId) {- // 子任务归档由 bots.finishDelegation 在同一事务内完成(见该 tx op 的注释),- // 不再另走通用 sessions.setStatus —— 那条通道对 source='bot' 的行会拒单,- // 归档失败也不会被吞掉:任何失败都会让整个终态事务回滚并往上抛。- await cleanupChildSession(- params.delegationId,- updated.childSessionId,- params.abortChild === true,- );+ // A normal turn boundary must not close the independent Session or its+ // background work. Explicit cancellation/timeout still stops execution.+ if (params.abortChild || params.status === 'cancelled' || updated.targetBotId !== null) {+ await cleanupChildSession(+ params.delegationId,+ updated.childSessionId,+ params.abortChild === true,+ updated.runSequence,+ );+ }holdTaskInput(updated.childSessionId, false);}}return updated;};- const readLatestAssistantText = async (sessionId: string): Promise<string | null> => {+ const readLatestAssistantText = async (sessionId: string, messageClientId?: string, startedAt?: number): Promise<string | null> => {const db = getDbClient().drizzle;const [latest] = await db.select({ content: messages.content })@@ -873,6 +1064,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {and(eq(messages.sessionId, sessionId),eq(messages.role, 'assistant'),+ ...(messageClientId ? [eq(messages.clientId, messageClientId)] : []),+ ...(startedAt !== undefined ? [sql`${messages.createdAt} >= ${startedAt}`] : []),isNull(messages.rewindAt),// 任务卡锚点(空正文)与插话留痕也是 assistant 行,但它们是这个任务**自己// 派活**留下的注解,不是它交出的答复。嵌套委派下不排除会直接选错:上一层@@ -1238,7 +1431,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {* 去程投递失败到无法自愈时的收口:委派立刻变成 `failed`,并把人话原因送回发起方。** 单独抽出来是因为这条路径有三件事必须一起发生,缺一件就退化成「静默挂起」:- * 收口 delegation 行(任务卡据此翻终态)、中止并归档子任务、把失败当作一次结果+ * 收口 delegation 行(任务卡据此翻终态)、停止失败执行但保留 Session、把失败当作一次结果* 回传(发起方的对话里必须出现这句话,而不是只在日志里)。*/async function failDelegationDispatch(@@ -1296,17 +1489,24 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {await failDelegationDispatch(row, 'CALLER_PERMISSION_UNAVAILABLE: 伙伴权限已变更,任务未启动');return { ok: false, status: 'failed' };}+ const retryReceipt = parseRecord(row.permissionSnapshotJson).taskDispatchRetry as+ { runSequence: number; clientId: string } | undefined;+ const startClientId = `bot-delegation-start:${row.id}${row.runSequence > 1 ? `:${row.runSequence}` : ''}`;+ const clientId = retryReceipt?.runSequence === row.runSequence ? retryReceipt.clientId : startClientId;+ let persistedReplay = false;const dispatched = await deps.dispatch({targetSessionId: row.childSessionId,message: buildDelegationPrompt(row),persistedContent: row.objective,- clientId: `bot-delegation-start:${row.id}`,- onAccepted: async () => {+ clientId,+ onAccepted: async replayed => {+ if (replayed) { persistedReplay = true; return; }const acceptedAt = now();const [accepted] = await db.update(botDelegations)- .set({ status: 'running', acceptedAt, lastError: null, updatedAt: acceptedAt })- .where(and(eq(botDelegations.id, row.id), eq(botDelegations.status, 'queued')))+ .set({ status: 'running', acceptedAt, lastError: null, updatedAt: acceptedAt,+ permissionSnapshotJson: executionSnapshot(row, clientId) })+ .where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence), eq(botDelegations.status, 'queued'))).returning({id: botDelegations.id,parentSessionId: botDelegations.parentSessionId,@@ -1324,12 +1524,30 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}},});+ if (dispatched.ok && persistedReplay) {+ // A user row can survive a crash before native acceptance. Keep confirmed+ // runs idempotent, but give an unaccepted start a durable retry identity.+ // CAS prevents recovery from replacing a receipt accepted concurrently.+ const [retrying] = await db.update(botDelegations).set({+ permissionSnapshotJson: sql`json_set(${botDelegations.permissionSnapshotJson}, '$.taskDispatchRetry', json(${JSON.stringify({+ runSequence: row.runSequence, clientId: `${startClientId}:retry:${createId()}`,+ })}))`,+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence),+ eq(botDelegations.status, 'queued'), eq(botDelegations.permissionSnapshotJson, row.permissionSnapshotJson),+ sql`COALESCE(json_extract(${botDelegations.permissionSnapshotJson}, '$.taskExecution.runSequence'), 0) != ${row.runSequence}`))+ .returning({ id: botDelegations.id });+ if (retrying) return attemptDispatch(row.id, attempt + 1, isCreationPermissionCurrent, resumingPause);+ }if (dispatched.ok) {const [current] = await db- .select({ status: botDelegations.status })+ .select({ status: botDelegations.status, permissionSnapshotJson: botDelegations.permissionSnapshotJson }).from(botDelegations).where(eq(botDelegations.id, row.id)).limit(1);+ if (persistedReplay && current?.status === 'queued'+ && (parseRecord(current.permissionSnapshotJson).taskExecution as { runSequence?: number } | undefined)?.runSequence !== row.runSequence) {+ scheduleDispatchRetry(row.id, attempt, isCreationPermissionCurrent);+ }return { ok: true, status: current?.status === 'running' ? 'running' : 'queued' };}// 去程没送出去。**不能**一律留在 queued 然后永远重试下去:没登录、子任务已归档@@ -1401,11 +1619,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {});}const deadlineAt = readDeadline(effectiveSnapshot);- if (deadlineAt !== null && deadlineAt <= now()) {- await timeoutDelegation(row.id);- return;- }- if (deadlineAt !== null && row.status !== 'waiting') scheduleTimeout(row.id, deadlineAt);if (!row.childSessionId) {const lastError = '应用重启后找不到这项后台任务的执行会话。';const changed = await updateTerminal({@@ -1417,13 +1630,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {return;}const resumedAt = parseRecord(row.permissionSnapshotJson).taskResumedAt;- if (typeof resumedAt === 'number' && deps.taskControl) {- await deps.taskControl.restoreInput(row.childSessionId);- if (deps.hasPendingInput?.(row.childSessionId)) {- await deps.taskControl.resumeInput(row.childSessionId);- return;- }- }const [child] = await db.select({status: sessions.status,@@ -1433,6 +1639,28 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.from(sessions).where(eq(sessions.id, row.childSessionId)).limit(1);++ // Restore without releasing input: pending work still owns the original+ // deadline, while a verified completed result only needs durable replay.+ if (child && child.status !== 'deleted') await deps.taskControl?.restoreInput(row.childSessionId);+ const hasOwnedPendingInput = hasPendingDelegationInput(row);++ const snapshot = parseRecord(row.permissionSnapshotJson);+ const acceptedExecution = snapshot.taskExecution as (DelegationExecutionReceipt & { runSequence: number }) | undefined;+ const terminal = snapshot.taskTerminal as {+ runSequence: number; execution: DelegationExecutionReceipt; outcome: 'done' | 'error';+ resultText?: string; resultMessageClientId?: string; error?: string;+ } | undefined;+ if (child && child.status !== 'deleted' && !hasOwnedPendingInput && acceptedExecution && terminal?.execution && terminal.runSequence === row.runSequence+ && acceptedExecution.runSequence === row.runSequence+ && terminal.execution.instanceId === acceptedExecution.instanceId+ && terminal.execution.generation === acceptedExecution.generation+ && (terminal.outcome === 'done' || terminal.outcome === 'error')) {+ await settleSessionUnserialized({ childSessionId: row.childSessionId, ...terminal,+ expectedRunSequence: row.runSequence, hadPendingInputAtTerminal: false });+ return;+ }+if (!child || child.status !== 'active') {const lastError = child? '应用重启后这项后台任务的执行会话已结束。'@@ -1446,12 +1674,35 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {return;}+ if (deadlineAt !== null && deadlineAt <= now()) {+ await timeoutDelegation(row.id);+ return;+ }+ if (deadlineAt !== null && row.status !== 'waiting') scheduleTimeout(row.id, deadlineAt);++ // A user-released cold turn is already executing; do not duplicate it.+ if (deps.readSessionExecution?.(row.childSessionId) && deps.taskControl?.isActive(row.childSessionId)) {+ scheduleResumeRetry(row.id, attempt);+ return;+ }+ if (hasOwnedPendingInput && deps.taskControl) {+ prepareQueuedResume(row);+ await deps.taskControl.resumeInput(row.childSessionId);+ return;+ }+if (child.activeTurnStartedAt !== null&& child.lastTurnEndedAt !== null&& child.lastTurnEndedAt >= Math.max(child.activeTurnStartedAt, typeof resumedAt === 'number' ? resumedAt : 0)) {- const resultText = await readLatestAssistantText(row.childSessionId);+ if (row.targetBotId === null) {+ // Session-wide timestamps can belong to a later direct turn. Without a+ // matching durable terminal receipt, leave the delegation unresolved.+ log.warn('Session task restart result has no verified execution receipt', { delegationId: row.id });+ return;+ }+ const resultText = await readLatestAssistantText(row.childSessionId, undefined, child.activeTurnStartedAt);if (resultText) {await settleSessionUnserialized({childSessionId: row.childSessionId,@@ -1495,12 +1746,16 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {`Task ID: ${row.id}`,`Objective:\n${row.objective}`,].join('\n\n');- const dispatched = await deps.dispatch({- targetSessionId: row.childSessionId,+ const recovered = await dispatchTrackedInput(row, {message,persistedContent: row.objective,clientId,});+ const dispatched = recovered.result;+ if (!dispatched.ok && dispatched.errorCode === 'TASK_CHANGED') {+ scheduleResumeRetry(row.id, attempt);+ return;+ }if (dispatched.ok) {clearRetryTimer(row.id);const resumedAt = now();@@ -1508,7 +1763,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.update(botDelegations).set({status: 'running',- permissionSnapshotJson: effectiveSnapshot,+ permissionSnapshotJson: sql`json_patch(${effectiveSnapshot}, json_object('taskExecution', json_extract(${botDelegations.permissionSnapshotJson}, '$.taskExecution'), 'taskRecoveryRetry', json_extract(${botDelegations.permissionSnapshotJson}, '$.taskRecoveryRetry'), 'taskAcceptedInputIds', json_extract(${botDelegations.permissionSnapshotJson}, '$.taskAcceptedInputIds')))`,pendingInteractionJson: null,lastError: null,updatedAt: resumedAt,@@ -2091,6 +2346,13 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {return cancelled;};+ const finishCancelledDelegation = async (row: DelegationRow) => {+ const changed = await cancelDelegationTree(row, 'Cancelled by the requesting Bot.', true, true);+ if (!changed) return { ok: false as const, errorCode: 'ALREADY_TERMINAL' as const, message: '后台任务已由另一操作结束' };+ return { ok: true as const, delegationId: row.id, childSessionId: row.childSessionId,+ control: { state: 'terminal', queue_held: false, stop_status: deps.taskControl ? 'stopped' : 'unknown' } };+ };+const cancelDelegation = async (callerSessionId: string,delegationId: string,@@ -2118,6 +2380,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {message: `后台任务已结束(${row.status})`,};}+ if (!matchesDelegatedExecution(row)) return finishCancelledDelegation(row);if (row.childSessionId) {if (deps.taskControl) {// Commit intent before changing the input/timer boundary. A failed write@@ -2133,7 +2396,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {try {// A successful stop response means the active process has actually// accepted cancellation, not merely that the card changed color.- await deps.abortSession(row.childSessionId);+ await controlDelegatedExecution(row, () => deps.abortSession(row.childSessionId!));} catch (error) {log.warn('Session task stop was not accepted by the child runtime', {delegationId,@@ -2147,21 +2410,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}}- if (row.childSessionId && deps.taskControl?.isActive(row.childSessionId)) {+ if (row.childSessionId && matchesDelegatedExecution(row) && deps.taskControl?.isActive(row.childSessionId)) {return { ok: true, delegationId, childSessionId: row.childSessionId,control: { state: 'cancelling', queue_held: true, stop_status: 'unconfirmed' } };}- const changed = await cancelDelegationTree(- row,- 'Cancelled by the requesting Bot.',- true,- true,- );- if (!changed) {- return { ok: false, errorCode: 'ALREADY_TERMINAL', message: '后台任务已由另一操作结束' };- }- return { ok: true, delegationId, childSessionId: row.childSessionId,- control: { state: 'terminal', queue_held: false, stop_status: deps.taskControl ? 'stopped' : 'unknown' } };+ return finishCancelledDelegation(row);};/**@@ -2238,13 +2491,13 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const token = (idempotencyToken ?? createId()).replace(/[^A-Za-z0-9_-]/g, '').slice(0, 64)|| createId();const requesterName = await requesterDisplayName(caller.botId);- const dispatched = await deps.dispatch({- targetSessionId: row.childSessionId,+ const recovered = await dispatchTrackedInput(row, {dispatcherSessionId: callerSessionId,message: [`[来自 ${requesterName} 的补充]`, trimmed].join('\n\n'),persistedContent: [`[来自 ${requesterName} 的补充]`, trimmed].join('\n\n'),- clientId: BOT_DELEGATION_CLIENT_ID.interjection(delegationId, token),+ clientId: BOT_DELEGATION_CLIENT_ID.interjection(delegationId, row.runSequence > 1 ? `${row.runSequence}:${token}` : token),});+ const dispatched = recovered.result;if (!dispatched?.ok) {return {ok: false,@@ -2280,13 +2533,13 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {delegationId,childSessionId: row.childSessionId,queued: dispatched.wakeKind === 'queued',- queuedMessageId: BOT_DELEGATION_CLIENT_ID.interjection(delegationId, token),+ queuedMessageId: recovered.clientId,};};/**- * 已结束任务收到继续消息时会另起一条执行 Session,但复用原任务 id。旧 Session- * 已归档,新 Session 重新进入 queued;卡片、停止、状态查询与后续结果仍指向同一任务。+ * Continue in the same visible Session, preserving history, worktree ownership+ * and callback targets. An archived/deleted Session needs explicit restoration.*/const reopenTerminalDelegation = async (callerSessionId: string,@@ -2324,6 +2577,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const db = getDbClient().drizzle;const [oldChild] = await db.select({+ status: sessions.status,title: sessions.title,workingDir: sessions.workingDir,worktreePath: sessions.worktreePath,@@ -2353,6 +2607,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}+ if (oldChild.status !== 'active') {+ return { ok: false, errorCode: oldChild.status === 'deleted' ? 'DELETED' : 'ARCHIVED',+ message: oldChild.status === 'deleted' ? 'The Session was deleted and cannot be continued.' : 'Restore the existing Session before continuing this task.' };+ }+await deps.reconcileWorktree?.(row.childSessionId);const worktreePath = deps.getWorktree?.(row.childSessionId)?.path ?? oldChild.worktreePath;const reopenedAt = now();@@ -2369,18 +2628,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {row.resultSummary ? `Previous result:\n${row.resultSummary.slice(0, 4_000)}` : '',`Requester follow-up:\n${trimmed}`,].filter(Boolean).join('\n\n').slice(0, MAX_OBJECTIVE_CHARS);- const childSessionId = resolveBusinessSessionId(undefined);+ const childSessionId = row.childSessionId;try {clearCompletionRetryTimer(row.id);await completionInFlight.get(row.id)?.catch(() => undefined);- await ensureProjectGitInitialized({- workingDir: oldChild.workingDir,- workspaceKind: oldChild.workspaceKind ?? 'dialogue',- remoteHostId: null,- sessionId: childSessionId,- autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,- source: 'bot-delegation',- });const commitReopen = () => getDbClient().tx('bots.reopenDelegation', {maxActiveChildren,delegationId: row.id,@@ -2389,7 +2640,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {parentSessionId: callerSessionId,childSessionId,objective: continuationObjective,- permissionSnapshotJson: JSON.stringify(nextPlan),+ permissionSnapshotJson: JSON.stringify({ ...nextPlan, taskAcceptedInputIds: [] }),targetBotId: null,targetProfileVersion: null,session: {@@ -2413,13 +2664,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {reopenedAt,worktreePath,});- if (worktreePath && !deps.withTransferredWorktree) {- throw new Error('Task worktree transfer is unavailable');- }- const reopened = worktreePath- ? await deps.withTransferredWorktree!(row.childSessionId, childSessionId, worktreePath, commitReopen,- { delegationId: row.id, requestingBotId: callerBotId })- : await commitReopen();+ const reopened = await commitReopen();if (!reopened.reopened) {await deliverCompletion({...row,@@ -2435,7 +2680,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {message: '后台任务状态刚刚发生变化,请重新查看后再继续',};}- deps.broadcastSessionCreated?.(childSessionId);+ clearCleanupRetryTimer(row.id);emitChanged({delegationId: row.id,parentSessionId: callerSessionId,@@ -2448,7 +2693,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {parentSessionId: callerSessionId,childSessionId,objective: continuationObjective,- permissionSnapshotJson: JSON.stringify(nextPlan),+ permissionSnapshotJson: JSON.stringify({ ...nextPlan, taskAcceptedInputIds: [] }),createdAt: reopenedAt,};if (reopened.previousParentSessionId !== callerSessionId) {@@ -2632,7 +2877,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}const [child] = row.childSessionId? await getDbClient().drizzle- .select({ title: sessions.title, workingDir: sessions.workingDir, workspaceKind: sessions.workspaceKind })+ .select({ title: sessions.title, status: sessions.status, workingDir: sessions.workingDir, workspaceKind: sessions.workspaceKind }).from(sessions).where(eq(sessions.id, row.childSessionId)).limit(1)@@ -2668,6 +2913,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {task: {task_id: row.id,session_id: row.childSessionId,+ session_status: child?.status ?? null,status: sessionTaskViewStatus(row),control: taskControlView(row),working_dir: child?.workingDir ?? null,@@ -2727,6 +2973,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const control = deps.taskControl;const pending = pendingInteractions.get(row.id);if (pending) pending.raisedAt = row.updatedAt;+ prepareQueuedResume(row);holdTaskInput(row.childSessionId, false);if (pending?.decisionApplied) {// Native settlement callbacks are serialized behind this operation. Apply@@ -2783,11 +3030,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {holdTaskInput(row.childSessionId, true);await control.restoreInput(row.childSessionId);const resumedAt = now();- const snapshot = parseRecord(extendDeadlineSnapshot(row.permissionSnapshotJson,- Math.max(0, resumedAt - pause.pausedAt)) ?? row.permissionSnapshotJson);- delete snapshot.taskPause;- snapshot.taskResumedAt = resumedAt;- snapshot.taskResume = { token: pause.token, text: text?.trim() ?? '' };let status: DelegationStatus = pending ? 'waiting' : pause.previousStatus === 'queued' ? 'queued' : 'running';// Enqueue behind the held boundary before clearing the durable pause.@@ -2796,19 +3038,30 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const dispatched = await attemptDispatch(row.id, 0, undefined, true);if (!dispatched.ok) throw new Error('Initial task dispatch has not been accepted');status = dispatched.status === 'running' ? 'running' : 'queued';+ const [acceptedRow] = await getDbClient().drizzle.select().from(botDelegations)+ .where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence))).limit(1);+ if (!acceptedRow || readTaskPause(acceptedRow)?.token !== pause.token) throw new Error('Task changed during initial acceptance');+ row = acceptedRow;}- if (!pending && (text || (pause.previousStatus !== 'queued' && !deps.hasPendingInput?.(row.childSessionId)))) {- const dispatched = await deps.dispatch({ targetSessionId: row.childSessionId,+ if (!pending && (text || (pause.previousStatus !== 'queued' && !hasPendingDelegationInput(row)))) {+ const recovered = await dispatchTrackedInput(row, {message: text?.trim() || 'Continue from the existing task history after the requested pause. Check what has already completed; do not replay the original request or repeat completed actions.',clientId: `bot-delegation-unpause:${row.id}:${pause.token}`,});- if (!dispatched.ok) throw new Error(dispatched.message);+ if (!recovered.result.ok) throw new Error(recovered.result.message);+ row = recovered.row;}- await control.flushInput(row.childSessionId);+ await control.flushInput(row.childSessionId!);} catch (error) {// The durable pause and token remain intact for an idempotent retry.return { ok: false as const, errorCode: 'RESUME_FAILED', message: error instanceof Error ? error.message : String(error) };}+ const snapshot = parseRecord(extendDeadlineSnapshot(row.permissionSnapshotJson,+ Math.max(0, resumedAt - pause.pausedAt)) ?? row.permissionSnapshotJson);+ delete snapshot.taskPause;+ delete snapshot.taskTerminal;+ snapshot.taskResumedAt = resumedAt;+ snapshot.taskResume = { token: pause.token, text: text?.trim() ?? '' };// Keep the input barrier until the durable transition and continuation enqueue are complete.try {const [resumed] = await getDbClient().drizzle.update(botDelegations).set({ status,@@ -2903,11 +3156,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {errorCode: 'UNSUPPORTED_CAPABILITY', message: 'Task control is unavailable in this runtime' };if (!isActiveDelegation(row.status as DelegationStatus)) return { ok: false as const,errorCode: 'ALREADY_TERMINAL', message: 'Task is already terminal' };+ if (!matchesDelegatedExecution(row, true)) return finishCancelledDelegation(row);const existingPause = readTaskPause(row);if (existingPause && mode === 'request-stop') return { ok: true as const, childSessionId: row.childSessionId,control: taskControlView(row) };if (mode === 'request-stop') {- const result = await control.stop({ targetSessionId: row.childSessionId });+ let result: Awaited<ReturnType<typeof control.stop>> = { ok: true, status: 'no-active-turn' };+ const applied = await controlDelegatedExecution(row, async () => { result = await control.stop({ targetSessionId: row.childSessionId! }); }, true);+ if (!applied) return finishCancelledDelegation(row);if (result.ok) {await getDbClient().drizzle.update(botDelegations).set({permissionSnapshotJson: JSON.stringify({ ...parseRecord(row.permissionSnapshotJson),@@ -2939,10 +3195,19 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}persisted = true;await control.waitForInputBoundary(row.childSessionId);- // Existing interaction wait is already a safe pause; keep its resolver for resume.- const result = (pending && pause.interactionOnly) || !control.isActive(row.childSessionId)- ? { ok: true as const, status: 'no-active-turn' as const }- : await control.stop({ targetSessionId: row.childSessionId });+ // Keep both native stop and its recovery/goal side effects under the same+ // reservation fence. A new direct turn must never inherit this pause.+ let result: Awaited<ReturnType<typeof control.stop>> = { ok: true, status: 'no-active-turn' };+ const applied = await controlDelegatedExecution(row, async () => {+ result = (pending && pause.interactionOnly) || !control.isActive(row.childSessionId!)+ ? { ok: true, status: 'no-active-turn' }+ : await control.stop({ targetSessionId: row.childSessionId! });+ if (result.ok) {+ await control.preparePause(row.childSessionId!);+ await control.flushInput(row.childSessionId!);+ }+ }, true);+ if (!applied) return finishCancelledDelegation(row);if (!result.ok) {if (!existingPause) {await getDbClient().drizzle.update(botDelegations).set({ permissionSnapshotJson: row.permissionSnapshotJson,@@ -2952,10 +3217,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}return result;}- await control.preparePause(row.childSessionId);- // Confirm the retained queue is durable before acknowledging the pause.- // A failed write keeps the pause/token for retry, just like uncertain stop.- await control.flushInput(row.childSessionId);clearTimer(row.id);clearRetryTimer(row.id);clearInteractionRetryTimer(row.id);@@ -2975,6 +3236,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const settleSessionUnserialized = async (params: {childSessionId: string;outcome: 'done' | 'error';+ execution?: DelegationExecutionReceipt | null;+ expectedRunSequence?: number;+ resultMessageClientId?: string;+ pendingInputClientIds?: string[];resultText?: string;error?: string;/** Captured synchronously at the terminal boundary, before queue drain can start the next turn. */@@ -2989,12 +3254,53 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.where(eq(botDelegations.childSessionId, params.childSessionId)).orderBy(desc(botDelegations.createdAt)).limit(1);+ if (params.expectedRunSequence !== undefined && row?.runSequence !== params.expectedRunSequence) return;+ const acceptedExecution = row && parseRecord(row.permissionSnapshotJson).taskExecution as+ (DelegationExecutionReceipt & { runSequence: number }) | undefined;+ if (params.execution !== undefined && (!params.execution || !acceptedExecution+ || acceptedExecution.runSequence !== row?.runSequence+ || acceptedExecution.instanceId !== params.execution.instanceId+ || acceptedExecution.generation !== params.execution.generation || row?.acceptedAt == null)) return;if (row && parseRecord(row.permissionSnapshotJson).taskCancelRequested === true && isActiveDelegation(row.status as DelegationStatus)) {if (!deps.taskControl?.isActive(params.childSessionId)) await cancelDelegationTree(row, 'Cancelled by the requesting Bot.', true, true);return;}- if (params.hadPendingInputAtTerminal || deps.hasPendingInput?.(params.childSessionId)) return;if (!row || readTaskPause(row) || !ACTIVE_DELEGATION_STATUSES.includes(row.status as (typeof ACTIVE_DELEGATION_STATUSES)[number])) return;+ // message_session_task can enqueue after the event snapshot but before this+ // task operation. Include those accepted inputs before publishing completion.+ const liveOwnedIds = (deps.readPendingInputClientIds?.(params.childSessionId) ?? [])+ .filter(clientId => isDelegationQueuedInput(row.id, clientId));+ if (liveOwnedIds.length) {+ const existing = pendingExecutionInputs.get(params.childSessionId);+ if (existing && existing.runSequence === row.runSequence) {+ pendingExecutionInputs.set(params.childSessionId, { ...existing,+ clientIds: [...new Set([...existing.clientIds, ...liveOwnedIds])] });+ } else if (acceptedExecution) {+ pendingExecutionInputs.set(params.childSessionId, {+ execution: acceptedExecution, clientIds: liveOwnedIds, runSequence: row.runSequence,+ });+ }+ return;+ }+ const ownedPendingInputIds = params.pendingInputClientIds?.filter(clientId => isDelegationQueuedInput(row.id, clientId));+ // Live terminal boundary validation is awaited separately by queue acceptance.+ // Do not overwrite a receipt already adopted while settlement was reading.+ if (ownedPendingInputIds?.length) return;+ // Native terminal events always provide the queue snapshot. Direct user+ // input in that snapshot cannot defer or take over this delegation's result.+ if (ownedPendingInputIds === undefined && params.hadPendingInputAtTerminal) return;+ if (params.execution) {+ const [recorded] = await db.update(botDelegations).set({+ permissionSnapshotJson: sql`json_set(${botDelegations.permissionSnapshotJson}, '$.taskTerminal', json(${JSON.stringify({+ runSequence: row.runSequence, execution: params.execution, outcome: params.outcome,+ resultText: params.resultText?.slice(0, MAX_RESULT_CHARS), resultMessageClientId: params.resultMessageClientId, error: params.error?.slice(0, 4000),+ })}))`,+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence),+ eq(botDelegations.permissionSnapshotJson, row.permissionSnapshotJson),+ inArray(botDelegations.status, [...ACTIVE_DELEGATION_STATUSES])))+ .returning({ id: botDelegations.id });+ if (!recorded) return;+ }const [child] = await db.select({ tokensUsed: sessions.totalTokenUsage }).from(sessions)@@ -3007,12 +3313,12 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {// done.result 不是字符串时(部分 Pi / 订阅档位只把终答写进消息行)不能把空结果// 当成「对方什么都没说」——发起方会被叫醒,但手里是一段没 Result 的废话墙。const recoveredText = params.resultText?.trim()- || (params.outcome === 'done'- ? ((await readLatestAssistantText(params.childSessionId))?.trim() ?? '')+ || (params.outcome === 'done' && (params.execution === undefined || params.resultMessageClientId)+ ? ((await readLatestAssistantText(params.childSessionId, params.resultMessageClientId))?.trim() ?? ''): '');const resultSummary = recoveredText.slice(0, MAX_RESULT_CHARS) || null;const artifacts = params.outcome === 'done' && deps.collectArtifacts- ? (await deps.collectArtifacts(params.childSessionId).catch((error) => {+ ? (await deps.collectArtifacts(params.childSessionId, readAcceptedInputIds(row)).catch((error) => {log.warn('failed to collect Session task artifacts', {delegationId: row.id,childSessionId: params.childSessionId,@@ -3021,6 +3327,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {return [];})).filter((artifact) => artifact.status !== 'deleted').slice(0, MAX_ARTIFACTS): [];+ // The transaction checks the durable receipt again after asynchronous reads.const changed = await updateTerminal({delegationId: row.id,status,@@ -3028,6 +3335,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {outputArtifactsJson: JSON.stringify(artifacts),lastError,tokensUsed,+ expectedRunSequence: row.runSequence,+ expectedExecution: params.execution ?? undefined,});if (!changed) return;await deliverCompletion({@@ -3039,20 +3348,208 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {});};+ const pendingExecutionInputs = new Map<string, {+ execution: DelegationExecutionReceipt | null; clientIds: string[]; runSequence?: number; acceptedClientId?: string;+ }>();++ const hasPendingDelegationInput = (row: DelegationRow): boolean => {+ if (!row.childSessionId) return false;+ return deps.readPendingInputClientIds+ ? deps.readPendingInputClientIds(row.childSessionId).some(clientId => isDelegationQueuedInput(row.id, clientId))+ : deps.hasPendingInput?.(row.childSessionId) === true;+ };++ const prepareQueuedResume = (row: DelegationRow): void => {+ if (!row.childSessionId) return;+ const clientIds = (deps.readPendingInputClientIds?.(row.childSessionId) ?? [])+ .filter(clientId => isDelegationQueuedInput(row.id, clientId));+ if (!clientIds.length) return;+ pendingExecutionInputs.set(row.childSessionId, {+ execution: (parseRecord(row.permissionSnapshotJson).taskExecution as DelegationExecutionReceipt | undefined) ?? null,+ clientIds, runSequence: row.runSequence,+ });+ };++ type BoundaryValidation = {+ promise: Promise<string[]>;+ revalidate: () => Promise<string[]>;+ failed: boolean;+ };+ const pendingBoundaryValidations = new Map<string, Map<string, BoundaryValidation>>();+ const trackBoundaryValidation = (promise: Promise<string[]>, revalidate: () => Promise<string[]>): BoundaryValidation => {+ const entry = { promise, revalidate, failed: false };+ // A database exception is retryable; a resolved list of declined IDs is not.+ void promise.catch(() => { entry.failed = true; });+ return entry;+ };++ const validateTerminalQueueBoundary = async (params: Parameters<typeof settleSessionUnserialized>[0]): Promise<string[]> => {+ if (!params.execution || !params.pendingInputClientIds?.length) return [];+ const [row] = await getDbClient().drizzle.select().from(botDelegations)+ .where(eq(botDelegations.childSessionId, params.childSessionId)).limit(1);+ if (!row) return [];+ // Start/restart/unpause have their own native acceptance callback. A prior+ // direct terminal cannot grant or deny that independent dispatch boundary.+ const clientIds = params.pendingInputClientIds.filter(id =>+ id.startsWith(`bot-delegation-interject:${row.id}:`));+ if (!isActiveDelegation(row.status as DelegationStatus) || readTaskPause(row)+ || row.acceptedAt == null || parseRecord(row.permissionSnapshotJson).taskCancelRequested === true) return clientIds;+ const receipt = parseRecord(row.permissionSnapshotJson).taskExecution as+ (DelegationExecutionReceipt & { runSequence: number }) | undefined;+ if (receipt?.runSequence !== row.runSequence || receipt.instanceId !== params.execution.instanceId+ || receipt.generation !== params.execution.generation) return clientIds;+ if (clientIds.length) pendingExecutionInputs.set(params.childSessionId, {+ execution: params.execution, clientIds, runSequence: row.runSequence,+ });+ return [];+ };+const settleSession = async (params: Parameters<typeof settleSessionUnserialized>[0]) => {+ // Publish an awaitable validation before the first database await. Queue drain+ // is already scheduled by the synchronous event adapter at this point.+ if (params.execution && params.pendingInputClientIds?.length) {+ const originalBoundary = { ...params, execution: { ...params.execution }, pendingInputClientIds: [...params.pendingInputClientIds] };+ const revalidate = () => validateTerminalQueueBoundary(originalBoundary);+ const validation = revalidate();+ let pending = pendingBoundaryValidations.get(params.childSessionId);+ if (!pending) pendingBoundaryValidations.set(params.childSessionId, pending = new Map());+ for (const id of params.pendingInputClientIds) {+ const previous = pending.get(id);+ const gate = previous ? previous.promise.catch(() => undefined).then(() => validation) : validation;+ pending.set(id, trackBoundaryValidation(gate, revalidate));+ }+ await validation;+ }+ params = { ...params, hadPendingInputAtTerminal: params.hadPendingInputAtTerminal ?? deps.hasPendingInput?.(params.childSessionId) };if (heldSessionIds.has(params.childSessionId)) {// Do not await an operation queued behind Stop: native abort may itself await this callback.const [held] = await getDbClient().drizzle.select().from(botDelegations).where(eq(botDelegations.childSessionId, params.childSessionId)).limit(1);if (held && parseRecord(held.permissionSnapshotJson).taskCancelRequested === true) {- void withTaskOperation(held.id, () => settleSessionUnserialized(params)).catch(error =>+ void withTaskOperation(held.id, () => settleSessionUnserialized({ ...params, expectedRunSequence: held.runSequence })).catch(error =>log.warn('Task cancellation confirmation failed', { delegationId: held.id, error: String(error) }));}return;}- const [row] = await getDbClient().drizzle.select({ id: botDelegations.id }).from(botDelegations)+ const [row] = await getDbClient().drizzle.select({ id: botDelegations.id, runSequence: botDelegations.runSequence }).from(botDelegations).where(eq(botDelegations.childSessionId, params.childSessionId)).limit(1);- if (row) await withTaskOperation(row.id, () => settleSessionUnserialized(params));+ if (row) await withTaskOperation(row.id, () => settleSessionUnserialized({ ...params, expectedRunSequence: row.runSequence }));+ };++ // Only delegation-owned entries from a validated terminal/resume boundary+ // can adopt a new receipt. Ordinary direct Session input remains independent.+ const acceptQueuedSessionInput = async (childSessionId: string, clientId: string, supersedesClientId?: string, restoredFromSnapshot = false, retrySourceClientId?: string): Promise<void> => {+ supersedesClientId = retrySourceClientId ?? supersedesClientId;+ const validations = pendingBoundaryValidations.get(childSessionId);+ const validationId = validations?.has(clientId) ? clientId : supersedesClientId ?? clientId;+ let validation = validations?.get(validationId);+ if (validation?.failed) {+ // Keep the original event receipt and ownership IDs, not the current live+ // generation. A retry must prove that boundary again after SQLite recovers.+ validation = trackBoundaryValidation(validation.revalidate(), validation.revalidate);+ validations!.set(validationId, validation);+ }+ const declinedIds = validation ? await validation.promise : [];+ let boundary = pendingExecutionInputs.get(childSessionId);+ const hasVerifiedBoundary = boundary?.clientIds.includes(clientId)+ || (supersedesClientId !== undefined && boundary?.clientIds.includes(supersedesClientId));+ if (declinedIds.includes(validationId) && !hasVerifiedBoundary) {+ // Retain the negative receipt: retrying must not turn rejection into success.+ throw new Error('Delegated queue boundary validation was declined');+ }+ if (validation) {+ if (validations?.get(validationId) === validation) validations.delete(validationId);+ if (!validations?.size) pendingBoundaryValidations.delete(childSessionId);+ }+ if (!boundary && (restoredFromSnapshot || retrySourceClientId)) {+ // Queue restoration can be released by the user before Bot restore runs.+ // A host retry can also rebuild it from an input accepted by this run;+ // retry lineage is separate from renderer message replacement.+ const [restored] = await getDbClient().drizzle.select().from(botDelegations)+ .where(eq(botDelegations.childSessionId, childSessionId)).limit(1);+ if (!restored || (!isDelegationQueuedInput(restored.id, clientId)+ && (!supersedesClientId || !isDelegationQueuedInput(restored.id, supersedesClientId)))) return;+ const receipt = parseRecord(restored.permissionSnapshotJson).taskExecution as+ (DelegationExecutionReceipt & { runSequence: number }) | undefined;+ if (!isActiveDelegation(restored.status as DelegationStatus) || readTaskPause(restored)+ || parseRecord(restored.permissionSnapshotJson).taskCancelRequested === true+ || (receipt && receipt.runSequence !== restored.runSequence)) {+ throw new Error('Restored delegated input no longer belongs to an executable run');+ }+ if (retrySourceClientId && !readAcceptedInputIds(restored).includes(retrySourceClientId)) {+ throw new Error('Retry source has no accepted delegation receipt');+ }+ boundary = pendingExecutionInputs.get(childSessionId);+ if (!boundary) {+ boundary = { execution: receipt ?? null, clientIds: [clientId], runSequence: restored.runSequence };+ pendingExecutionInputs.set(childSessionId, boundary);+ }+ }+ if (!boundary || (!boundary.clientIds.includes(clientId)+ && (!supersedesClientId || !boundary.clientIds.includes(supersedesClientId)))) {+ // A supplement can arrive after an empty terminal snapshot, including a+ // stale terminal that cannot publish a boundary. Check at dispatch itself;+ // absence from the in-memory maps is not permission to run owned input.+ const [owner] = await getDbClient().drizzle.select().from(botDelegations)+ .where(eq(botDelegations.childSessionId, childSessionId)).limit(1);+ if (!owner || (!isDelegationQueuedInput(owner.id, clientId)+ && (!supersedesClientId || !isDelegationQueuedInput(owner.id, supersedesClientId)))) return;+ // Terminal validation may have completed during the ownership read.+ boundary = pendingExecutionInputs.get(childSessionId);+ if (!boundary || (!boundary.clientIds.includes(clientId)+ && (!supersedesClientId || !boundary.clientIds.includes(supersedesClientId)))) {+ const receipt = parseRecord(owner.permissionSnapshotJson).taskExecution as+ (DelegationExecutionReceipt & { runSequence: number }) | undefined;+ const current = deps.readSessionExecution?.(childSessionId);+ // A live onAccepted callback may already have durably bound this dispatch.+ if (isActiveDelegation(owner.status as DelegationStatus) && current && receipt+ && receipt.runSequence === owner.runSequence && receipt.instanceId === current.instanceId+ && receipt.generation === current.generation) return;+ throw new Error('Delegated queued input has no verified execution boundary');+ }+ }+ const execution = deps.readSessionExecution?.(childSessionId);+ if (!execution) throw new Error('Delegated queued input has no native execution receipt');+ const db = getDbClient().drizzle;+ const [row] = await db.select().from(botDelegations)+ .where(eq(botDelegations.childSessionId, childSessionId)).limit(1);+ if (!row || !isActiveDelegation(row.status as DelegationStatus)+ || (boundary.runSequence !== undefined && boundary.runSequence !== row.runSequence)) {+ throw new Error('Delegated queued input no longer belongs to an active run');+ }+ const matchesAccepted = (snapshot: string): boolean => {+ const accepted = parseRecord(snapshot).taskExecution as (DelegationExecutionReceipt & { runSequence: number }) | undefined;+ return accepted?.runSequence === row.runSequence && accepted.instanceId === execution.instanceId+ && accepted.generation === execution.generation;+ };+ if (!matchesAccepted(row.permissionSnapshotJson)) {+ const receiptGuard = boundary.execution+ ? and(+ sql`json_extract(${botDelegations.permissionSnapshotJson}, '$.taskExecution.runSequence') = ${row.runSequence}`,+ sql`json_extract(${botDelegations.permissionSnapshotJson}, '$.taskExecution.instanceId') = ${boundary.execution.instanceId}`,+ sql`json_extract(${botDelegations.permissionSnapshotJson}, '$.taskExecution.generation') = ${boundary.execution.generation}`)+ : sql`json_extract(${botDelegations.permissionSnapshotJson}, '$.taskExecution') IS NULL`;+ const [accepted] = await db.update(botDelegations).set({+ permissionSnapshotJson: executionSnapshot(row, clientId, execution),+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence),+ receiptGuard,+ inArray(botDelegations.status, ['running', 'waiting'])))+ .returning({ id: botDelegations.id });+ if (!accepted) throw new Error('Delegated queued execution receipt was not committed');+ }+ // Acceptance can still roll back before vendor dispatch. Retain the boundary+ // and its durable CAS predecessor so a retry can reserve another generation.+ if (pendingExecutionInputs.get(childSessionId) === boundary) pendingExecutionInputs.set(childSessionId, {+ ...boundary, execution, acceptedClientId: clientId,+ clientIds: boundary.clientIds.includes(clientId) ? boundary.clientIds : [...boundary.clientIds, clientId],+ });+ };++ const confirmQueuedSessionInputDispatched = (childSessionId: string, clientId: string): void => {+ // A fast terminal event may already have installed the next queue boundary.+ if (pendingExecutionInputs.get(childSessionId)?.acceptedClientId === clientId) {+ pendingExecutionInputs.delete(childSessionId);+ }};const restore = async (): Promise<void> => {@@ -3097,9 +3594,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (parseRecord(row.permissionSnapshotJson).taskCancelRequested === true) {if (row.childSessionId) {holdTaskInput(row.childSessionId, true);- await deps.abortSession(row.childSessionId);+ await controlDelegatedExecution(row, () => deps.abortSession(row.childSessionId!));}- if (!row.childSessionId || !deps.taskControl?.isActive(row.childSessionId)) {+ if (!row.childSessionId || !matchesDelegatedExecution(row) || !deps.taskControl?.isActive(row.childSessionId)) {await cancelDelegationTree(row, 'Cancelled by the requesting Bot.', true, true);}return;@@ -3136,6 +3633,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const dispose = (): void => {unregisterParentCancellation();+ pendingExecutionInputs.clear();+ pendingBoundaryValidations.clear();for (const timer of timers.values()) clearTimeout(timer);timers.clear();for (const timer of retryTimers.values()) clearTimeout(timer);@@ -3170,6 +3669,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {cancelDelegationsForParentSession,cancelDelegationsForBot,settleSession,+ acceptQueuedSessionInput,+ confirmQueuedSessionInputDispatched,handleInteractionStart,handleInteractionEnd,restore,diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 0be37965b6..4ee252d759 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -413,6 +413,7 @@ import {import { createAgentResourceSettingsIpc } from './agent-resource-settings-ipc.js';import {createBotDelegationService,+ discardDelegationQueuedInputs,type BotDelegationService,} from './botDelegationService.js';import {@@ -9266,7 +9267,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)persistedContent?: string;clientId?: string;files?: AgentInputQueuedMessage['files'];- onAccepted?: () => void | Promise<void>;+ onAccepted?: (replayed?: boolean) => void | Promise<void>;onAcceptedRollback?: () => void | Promise<void>;}) => {if (params.clientId && params.authorizationGuard) {@@ -9302,7 +9303,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return { ok: false as const, errorCode: 'AGENT_NOT_READY' as const, message: 'Previous welcome acceptance is unconfirmed; retry is required.' };}if (persisted && !params.toolsDisabled) {- await params.onAccepted?.();+ await params.onAccepted?.(true);return {ok: true as const,targetSessionId: params.targetSessionId,@@ -9369,7 +9370,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)queuedMessageId: clientId,};}- return sendToSessionInternal(params);+ return sendToSessionInternal({ ...params, onAccepted: () => params.onAccepted?.() });};setBotInvitationWelcomeDispatch(dispatchBotSessionMessage);@@ -9453,6 +9454,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)setBotRemoteMessageService(botDirectMessageServiceHolder);botDelegationServiceHolder?.dispose();botDelegationServiceHolder = createBotDelegationService({+ readSessionExecution: id => {+ const session = maker.getSession(id);+ return session ? { instanceId: session.instanceId, generation: session.getTurnGeneration() } : null;+ },+ // Native close cannot be cancelled by the ordinary send-lock watchdog.+ withSessionLock: withSessionRestartLock,taskControl: {steer: (params) => sessionControlService.steerSession(params),stop: (params) => sessionControlService.stopSessionTurn(params),@@ -9527,6 +9534,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)onAccepted,dispatcherSessionId,}),+ discardDelegationQueuedInputs: (sessionId, delegationId) =>+ discardDelegationQueuedInputs(inputCoordinator, sessionId, delegationId, awaitAgentInputQueueSnapshotPersistence),abortSession: (async (sessionId) => {await inputCoordinator.ensureQueueRestored(sessionId);resetAutomaticRecoveryForExplicitStop(sessionId);@@ -9543,9 +9552,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)resolveInteraction: resolvePendingInteraction,hasPendingInput: (sessionId) =>inputCoordinator.getQueueControlSnapshot(sessionId).pendingQueue.length > 0,- collectArtifacts: async (sessionId) => {+ readPendingInputClientIds: (sessionId) =>+ inputCoordinator.getQueueControlSnapshot(sessionId).pendingQueue.flatMap(item => [item.clientId, ...(item.supersedesUserClientId ? [item.supersedesUserClientId] : []), ...(item.retrySourceClientId ? [item.retrySourceClientId] : [])]),+ collectArtifacts: async (sessionId, inputClientIds) => {await waitForTurnChangeSetSeal(sessionId);- const changeSets = await listTurnChangeSets(sessionId);+ const acceptedInputs = new Set(inputClientIds);+ const changeSets = (await listTurnChangeSets(sessionId)).filter(changeSet => acceptedInputs.has(changeSet.anchorClientId));const byPath = new Map<string, {path: string;absolutePath: string;@@ -13736,12 +13748,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 可见行),理由与踩过的坑记在 helper 的注释里。supersedeRetriedUserTurn,getLastAssistantTranscriptUuid,- onAcceptedQueuedMessage: (sessionId, item): Promise<void> | undefined => {+ onAcceptedQueuedMessage: async (sessionId, item, restoredFromSnapshot): Promise<void> => {// 已派发 → 该项不会再走 discard,释放 scheduler 的 discard 监听防泄漏。schedulerQueuedPromptDiscardWatchers.delete(item.clientId);// 返回 promise 让 coordinator 在 onPersisted 链路里 await —— worker 运行态与// pending auto-bridge 副作用必须先于 turn 启动完成;失败仍吞错落日志,不拦派发。- return orcaInterAgentDispatcher.runQueuedOrcaInterAgentAcceptedCallback(sessionId, item);+ await orcaInterAgentDispatcher.runQueuedOrcaInterAgentAcceptedCallback(sessionId, item);+ await botDelegationServiceHolder?.acceptQueuedSessionInput(sessionId, item.clientId, item.supersedesUserClientId, restoredFromSnapshot, item.retrySourceClientId);},onUserMessagePersisting: (sessionId, item) => {markQueuedAttachmentPersistenceStarted(sessionId, item.clientId);@@ -13760,6 +13773,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)settleQueuedAttachmentPersistenceFailure(sessionId, item.clientId, opts.retainForRetry);},onDispatchedUserTurn: async (sessionId, item, preVendorDispatchAt): Promise<void> => {+ botDelegationServiceHolder?.confirmQueuedSessionInputDispatched(sessionId, item.clientId);welcomeDispatchReceipts.settle(sessionId, item.clientId, true);const attemptToken = autoResumeAttemptToken(item);if (diff --git a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.tsindex e3baeffe78..0afec7c5d4 100644--- a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts+++ b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts@@ -451,17 +451,22 @@ export function finishSessionTerminalEvent(})) {// Capture before queue-drain microtasks can promote the follow-up turn.- const botDelegationHadPendingInputAtTerminal =- (deps.agentInputCoordinatorHolder?.getQueueControlSnapshot(session.id).pendingQueue.length ?? 0) > 0;+ const botDelegationPendingInputClientIds =+ deps.agentInputCoordinatorHolder?.getQueueControlSnapshot(session.id).pendingQueue.flatMap(item => [item.clientId, ...(item.supersedesUserClientId ? [item.supersedesUserClientId] : []), ...(item.retrySourceClientId ? [item.retrySourceClientId] : [])]) ?? [];void (async () => {try {const doneData = event.data as { result?: unknown; message?: unknown; reason?: unknown } | null;await deps.botDelegationServiceHolder?.settleSession({childSessionId: session.id,+ execution: typeof event.sessionTurnGeneration === 'number'+ ? { instanceId: event.sessionInstanceId ?? session.instanceId, generation: event.sessionTurnGeneration }+ : null,outcome: isTerminalTurnErrorEvent(event) ? 'error' : 'done',resultText: typeof doneData?.result === 'string' ? doneData.result : '',error: [doneData?.message, doneData?.reason].find((value): value is string => typeof value === 'string' && value.length > 0),- hadPendingInputAtTerminal: botDelegationHadPendingInputAtTerminal,+ hadPendingInputAtTerminal: botDelegationPendingInputClientIds.length > 0,+ pendingInputClientIds: botDelegationPendingInputClientIds,+ resultMessageClientId: turnAssistantPersistId,});} catch (error) {deps.log.warn('Bot delegation terminal settlement failed', {diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.tsindex 80f1fd2af8..ef103847aa 100644--- a/apps/desktop/src/shared/agentInputQueue.ts+++ b/apps/desktop/src/shared/agentInputQueue.ts@@ -338,6 +338,8 @@ export interface AgentInputQueuedMessage {* 旧队列快照缺省该字段(undefined = 不软删),向后兼容。*/supersedesUserClientId?: string;+ /** Stable retry provenance; unlike supersedes, never hides a user message. */+ retrySourceClientId?: string;}export type AgentInputDelivery = 'turn' | 'steer';diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 11dcea625f..82607ae9da 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -228,6 +228,12 @@ Session 任务遵守同一套机制与呈现契约:- **统一状态机**:`queued → running ⇄ waiting → completed | failed | cancelled`。`waiting`表示子任务正在等权限、答案、计划确认或显式恢复;显式暂停另有持久控制标记,`check_session_task` 返回 `control` 区分暂停与交互等待,不把它们误报成执行超时。+- **执行结束与归档分离**:`completed` 只表示本次委派执行正常返回,不证明用户目标已全部+ 完成;等待 CI、后台测试或外部反馈不等于归档。独立任务在正常返回、失败、超时或取消后+ 保留原 Session 的可见状态;正常返回不关闭运行句柄或后台工作,取消与超时仍停止执行。+ 归档/删除沿用用户显式操作,不依据 PR 是否存在或 GitHub 状态自动决定。+ `check_session_task.session_status` 单独返回实际 Session 的 active/archived/deleted 状态,+ 与执行 `status`、暂停/取消 `control` 分别解读;终态恢复只补投回执,不重跑已结束执行。- **显式暂停恢复**:暂停先锁住输入,旧轮终态不交付完成回执;重启只恢复锁,不自动执行。恢复保留同一任务 ID、执行 Session 和历史,有队列先消费队列,无队列才投一次去重续接指令。旧轮停止未确认时拒绝恢复,禁止与迟到中断竞争;计时只补回实际等待时长。@@ -259,10 +265,42 @@ Session 任务遵守同一套机制与呈现契约:- 项目执行显式传 `working_dir`,可用 `use_worktree=true` 在启动前复用现有 worktree 管理器完成独立分支、目录与 Session 绑定;失败不得落回共享目录。只在 Shell 中新建 worktree不会修改任务登记或运行时 cwd;`check_session_task` 返回实际登记目录与项目归属。- 终态续接复用既有目录和分支,并将 worktree 管理器归属及数据库快照迁到新执行任务;- 迁移先在原登记保存持久意图,提交后按数据库实际归属完成登记。提交回执丢失不盲目回滚,- 重启、派发和续接重试会对账;数据库不可读或归属冲突时保留意图与目录,只阻止受影响执行,- 不接管他人归属、不回收工作成果。+ 终态续接复用原 Session、完整历史、目录和分支,worktree 归属不迁移;每轮有独立的+ 投递与完成回执,重试不重放上一轮。终态事件携带原 Session 实例与执行代次,旧轮迟到事件+ 不得结算新轮。受理时将执行身份持久绑定至委派轮次,结果读取后仍按该回执原子收口,+ 不以已变化的当前执行替代原回执;结束前已排队的补充在受理后更新回执。+ 首次取消、请求停止及暂停须在 Session 执行锁内核验持久回执;身份不符时只收口旧委派+ 并撤销其队列,不停止新执行。超时与取消的清理及重试也以保存的回执核对身份,不能中止用户从任务列表+ 直接开启的新执行;没有原生实例时仍须撤销该委派的排队输入,不清除无关输入。+ 本轮无 assistant 消息且终态无文本时结果保持为空,不复用前轮答复。+ 自动重试、连续重试及冷恢复保留稳定输入来源;该来源独立于用于隐藏旧用户消息的替代标记,+ 队列编辑、终态扫描与清理均不得丢失。重试受理须核对本轮已受理输入凭据后再更新执行身份。+ 只将委派自身投递的队列项视为续接;普通直接输入不延后委派结果,也不改写其执行身份。+ 数据库异常不等于身份校验拒绝:须保留原终态回执与输入归属供重试重新核验,+ 不能缓存失败 Promise 使后续重试永久失败;身份不符的拒绝仍不可绕过。+ 终态须先通过持久轮次与执行回执核验,才能登记这些续接项;第一次异步读取前登记+ 可等待的校验,队列受理须等校验结束,不能抢在边界就绪前派发。自有输入校验未通过且+ 无已验证边界时须拒绝派发,重复受理不得绕过拒绝;普通输入不受此限制。结算持有任务操作锁时+ 还须核对实时自有队列,不能遗漏终态快照之后收到的补充;受理回执更新未命中须拒绝派发。+ 消息已落库而启动轮次尚无受理回执时,恢复须以持久重试身份重新派发,保留原消息;+ 条件更新须保护并发受理与轮次,不重投已有本轮回执的执行。+ 消息幂等命中不属于原生受理,不重新采样当前执行或覆盖已存回执。start/restart/unpause+ 的独立受理不由前序直接终态批准或拒绝;其自身原生受理仍须持久绑定执行身份。+ 空快照后的迟到补充也须在派发入口核验:既无已验证边界、又无本次派发的持久回执时拒绝,+ 不能因旧终态已被忽略或内存校验记录不存在而放行。+ 排队续接的受理回执提交成功且宿主确认实际派发后才释放衔接记录;受理后未派发须保留+ 重试更新回执的依据。冷恢复队列先于委派恢复被用户放行时,受理入口按宿主快照来源+ 与持久委派身份补建衔接,不得无回执派发。编辑、整条替换及合并保留原条目的恢复来源,+ 不因对象替换丢失,也不由调用方补造。写入失败或条件更新未命中须拒绝派发,+ 保留重试依据。重启时先恢复委派自有排队输入,存在补充时先续接,不能先回放旧终态;+ 无此输入才按已保存的终态回执与委派执行身份补交结果;该已完成结果的回放优先于恢复时+ 的超时判断,未完成执行与排队补充仍遵守原截止时间。只有 Session 级+ 时间戳而无轮次证据时,先恢复委派自有的排队补充并登记衔接回执;无此输入才保留未决,+ 不拿后续直接执行的答复结算或重放已结束工作。+ 已归档但未删除的 Session 可补交已验证的持久终态(须无待处理委派输入),仅投递结果,+ 不恢复 active、不启动执行;缺失或已删除的 Session 不走这条结果回放。+ 已归档或删除的 Session 不因伙伴补充、回调或重启+ 自动恢复或创建替身;旧版自动归档的记录也须经显式恢复后才能续接。- 补充输入返回 `queued_message_id`;`check_session_task` 返回调用 Session 自己投递的队列,可按消息 ID 查询 queued / consuming / dispatched / not-found / unavailable。队列恢复失败时保留任务状态和结果,单独返回 `queue_error=QUEUE_UNAVAILABLE`;无法核实的消息不能报 not-found。