Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 补齐后台任务控制、停止确认与自投队列管理 (#4323)
Chris Zhang4fad02bc19c4
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex c9a776f6a0..5a2eb1a77e 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -383,7 +383,7 @@ describe('maker:event hot path ordering', () => {);expect(source).toContain('out.push({ request: entry.request, persistId: entry.persistId });');expect(source).toContain(- 'taken.push({ requestId, request: entry.request, resolve: entry.resolve });',+ 'taken.push({ requestId, request: entry.request, resolve:',);});diff --git a/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts b/apps/desktop/src/main/__tests__/permissionInteractionPause.test.tsnew file mode 100644index 0000000000..6a5bdafd1b--- /dev/null+++ b/apps/desktop/src/main/__tests__/permissionInteractionPause.test.ts@@ -0,0 +1,229 @@+import { readFileSync } from 'node:fs';+import ts from 'typescript';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';++// Execute the production listener and control adapter without booting Electron.+const source = readFileSync(new URL('../maker-ipc/register.ts', import.meta.url), 'utf8');+const ast = ts.createSourceFile('register.ts', source, ts.ScriptTarget.ES2022, true);+const names = new Set([+ 'installDesktopInteractionListener', 'clearPendingInteraction',+ 'schedulePendingPermissionTimeout', 'setPendingInteractionTimeoutsPaused',+ 'resolvePendingInteraction', 'defaultDecisionForPending',+ 'cleanupPendingAgentInteractionsForSession', 'takePendingInteractionsForSession',+]);+const functions = ast.statements.filter((node) => ts.isFunctionDeclaration(node)+ && node.name && names.has(node.name.text)).map(node => node.getText(ast).replace(/^export /, ''));+let holdInputSource = '';+function visit(node: ts.Node): void {+ if (ts.isPropertyAssignment(node) && node.name.getText(ast) === 'holdInput') {+ holdInputSource = node.initializer.getText(ast);+ }+ ts.forEachChild(node, visit);+}+visit(ast);+if (!holdInputSource) throw new Error('Task holdInput adapter missing');+const compiled = ts.transpileModule(`${functions.join('\n')}+return { install: installDesktopInteractionListener, hold: ${holdInputSource},+ answer: resolvePendingInteraction, cleanup: cleanupPendingAgentInteractionsForSession,+ take: takePendingInteractionsForSession };`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+}).outputText;+const MINUTE = 60_000;++function harness() {+ const held = new Set<string>();+ const coordinator = {+ isExecutionPaused: (id: string) => held.has(id),+ setExecutionPaused: (id: string, value: boolean) => { if (value) held.add(id); else held.delete(id); },+ onInteractionResolved: vi.fn(),+ };+ const listeners = new Map<string, (request: InteractionRequest) => Promise<InteractionDecision>>();+ const entries = new Map();+ const dismiss = vi.fn();+ const deps = {+ pendingInteractionResolvers: entries,+ agentInputCoordinatorHolder: coordinator, inputCoordinator: coordinator,+ PERMISSION_INTERACTION_TIMEOUT_MS: 10 * MINUTE,+ installDesktopInteractionHandler: (session: { id: string }, handler: (request: InteractionRequest) => Promise<InteractionDecision>) => listeners.set(session.id, handler),+ shouldNotifyAgentIslandForSession: () => false,+ flushAssistantBlock: vi.fn(), onInteractionMessage: vi.fn(),+ redactToolInputForUntrustedBoundary: (_tool: string, input: unknown) => input,+ broadcastToAllWindows: vi.fn(),+ MAKER_PUSH: { INTERACTION_REQUEST: 'request', INTERACTION_DISMISSED: 'dismissed' },+ handleAgentIslandInteractionAfterBroadcast: vi.fn(), handleAgentIslandInteractionDismissed: vi.fn(),+ dismissRendererInteraction: dismiss, persistInteractionDecision: vi.fn(),+ goalAskAnswerObserver: null, ghostSetupInteractionBridge: { cleanupForSession: vi.fn() },+ };+ const runtime = new Function(...Object.keys(deps), compiled)(...Object.values(deps)) as {+ install: (session: { id: string }) => void;+ hold: (id: string, held: boolean) => string[];+ answer: (id: string, decision: InteractionDecision) => boolean;+ cleanup: (id: string, reason: string) => void;+ take: (id: string) => Array<{ resolve: (decision: InteractionDecision) => void }>;+ };+ const request = (id = 'permission', sessionId = 'task', kind: InteractionRequest['kind'] = 'permission') => {+ runtime.install({ id: sessionId });+ const settled = vi.fn();+ const promise = listeners.get(sessionId)!({ kind, requestId: id, toolName: 'Shell', input: {} } as InteractionRequest);+ void promise.then(settled);+ return { promise, settled };+ };+ return { ...runtime, request, entries, dismiss };+}++beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(0); });+afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });++describe('permission timeout follows the task pause lifecycle', () => {+ it('keeps the permission pending across its original deadline and resumes only the remaining budget', async () => {+ const h = harness();+ const p = h.request();+ await vi.advanceTimersByTimeAsync(3 * MINUTE);+ h.hold('task', true);+ expect(h.answer('permission', { kind: 'permission', behavior: 'allow' })).toBe(false);+ await vi.advanceTimersByTimeAsync(30 * MINUTE);+ expect(p.settled).not.toHaveBeenCalled();+ expect(h.entries.has('permission')).toBe(true);+ h.hold('task', false);+ await vi.advanceTimersByTimeAsync(7 * MINUTE - 1);+ expect(p.settled).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(p.settled).toHaveBeenCalledExactlyOnceWith({ kind: 'permission', behavior: 'deny', reason: 'timeout' });+ expect(h.answer('permission', { kind: 'permission', behavior: 'allow' })).toBe(false);+ expect(h.dismiss).toHaveBeenCalledTimes(1);+ });++ it('does not reset or consume the remaining budget on repeated pause/resume', async () => {+ const h = harness();+ const p = h.request();+ await vi.advanceTimersByTimeAsync(4 * MINUTE);+ h.hold('task', true);+ await vi.advanceTimersByTimeAsync(20 * MINUTE);+ h.hold('task', true);+ h.hold('task', false);+ await vi.advanceTimersByTimeAsync(2 * MINUTE);+ h.hold('task', false);+ h.hold('task', true);+ await vi.advanceTimersByTimeAsync(20 * MINUTE);+ h.hold('task', false);+ await vi.advanceTimersByTimeAsync(4 * MINUTE - 1);+ expect(p.settled).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(p.settled).toHaveBeenCalledTimes(1);+ });++ it('holds permissions raised after pause and leaves another task safety timeout running', async () => {+ const h = harness();+ h.hold('task', true);+ const paused = h.request();+ const other = h.request('other-permission', 'other-task');+ await vi.advanceTimersByTimeAsync(20 * MINUTE);+ expect(paused.settled).not.toHaveBeenCalled();+ expect(other.settled).toHaveBeenCalledExactlyOnceWith({ kind: 'permission', behavior: 'deny', reason: 'timeout' });+ h.hold('task', false);+ await vi.advanceTimersByTimeAsync(10 * MINUTE);+ expect(paused.settled).toHaveBeenCalledTimes(1);+ });++ it.each(['session_aborted', 'session_closed'])('cleans up a paused permission once on %s without resurrecting its timer', async reason => {+ const h = harness();+ const p = h.request();+ h.hold('task', true);+ h.cleanup('task', reason);+ h.cleanup('task', reason);+ h.hold('task', false);+ await vi.advanceTimersByTimeAsync(20 * MINUTE);+ expect(p.settled).toHaveBeenCalledExactlyOnceWith({ kind: 'permission', behavior: 'deny', reason });+ expect(h.entries.size).toBe(0);+ expect(h.dismiss).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('accepts one answer after resume and cancels the remaining timeout', async () => {+ const h = harness();+ const p = h.request();+ h.hold('task', true);+ await vi.advanceTimersByTimeAsync(20 * MINUTE);+ h.hold('task', false);+ expect(h.answer('permission', { kind: 'permission', behavior: 'allow' })).toBe(true);+ expect(h.answer('permission', { kind: 'permission', behavior: 'deny' })).toBe(false);+ await vi.advanceTimersByTimeAsync(20 * MINUTE);+ expect(p.settled).toHaveBeenCalledExactlyOnceWith({ kind: 'permission', behavior: 'allow' });+ expect(h.dismiss).toHaveBeenCalledTimes(1);+ });++ it.each(['permission', 'ask_user_question', 'plan_review'] as const)('defers a migrated %s answer until resume and ignores duplicates', async kind => {+ const h = harness();+ const p = h.request(kind, 'task', kind);+ const [taken] = h.take('task');+ expect(h.take('task')).toEqual([]);+ h.hold('task', true);+ const answer: InteractionDecision = kind === 'ask_user_question'+ ? { kind, answers: { choice: 'yes' } }+ : { kind, behavior: 'allow' };+ taken.resolve(answer);+ taken.resolve({ kind: 'permission', behavior: 'deny' });+ await vi.advanceTimersByTimeAsync(30 * MINUTE);+ expect(p.settled).not.toHaveBeenCalled();+ expect(h.entries.size).toBe(1);+ expect(h.hold('task', false)).toEqual([kind]);+ expect(h.hold('task', false)).toEqual([]);+ await p.promise;+ expect(p.settled).toHaveBeenCalledExactlyOnceWith(answer);+ taken.resolve(answer);+ expect(h.entries.size).toBe(0);+ });++ it.each(['session_aborted', 'session_closed'])('cancels a deferred migrated answer on %s', async reason => {+ const h = harness();+ const p = h.request();+ const [taken] = h.take('task');+ h.hold('task', true);+ taken.resolve({ kind: 'permission', behavior: 'allow' });+ h.cleanup('task', reason);+ h.cleanup('task', reason);+ h.hold('task', false);+ taken.resolve({ kind: 'permission', behavior: 'allow' });+ await vi.advanceTimersByTimeAsync(30 * MINUTE);+ expect(p.settled).toHaveBeenCalledExactlyOnceWith({ kind: 'permission', behavior: 'deny', reason });+ expect(h.entries.size).toBe(0);+ });++ it('defers the migrated channel safety timeout until resume', async () => {+ const h = harness();+ const p = h.request();+ const [taken] = h.take('task');+ h.hold('task', true);+ taken.resolve({ kind: 'permission', behavior: 'deny', reason: 'timeout' });+ await vi.advanceTimersByTimeAsync(30 * MINUTE);+ expect(p.settled).not.toHaveBeenCalled();+ h.hold('task', false);+ await p.promise;+ expect(p.settled).toHaveBeenCalledExactlyOnceWith({ kind: 'permission', behavior: 'deny', reason: 'timeout' });+ });++ it('keeps transferred permissions out of the Desktop timer lifecycle', async () => {+ const h = harness();+ const p = h.request();+ h.hold('task', true);+ const [taken] = h.take('task');+ h.hold('task', false);+ await vi.advanceTimersByTimeAsync(20 * MINUTE);+ expect(p.settled).not.toHaveBeenCalled();+ taken.resolve({ kind: 'permission', behavior: 'allow' });+ await p.promise;+ expect(p.settled).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(['ask_user_question', 'plan_review'] as const)('does not add a timeout to %s when resumed', async kind => {+ const h = harness();+ const p = h.request(kind, 'task', kind);+ h.hold('task', true);+ h.hold('task', false);+ await vi.advanceTimersByTimeAsync(60 * MINUTE);+ expect(p.settled).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/apps/desktop/src/main/__tests__/worktreeSessionTransfer.test.ts b/apps/desktop/src/main/__tests__/worktreeSessionTransfer.test.tsnew file mode 100644index 0000000000..5294da64b3--- /dev/null+++ b/apps/desktop/src/main/__tests__/worktreeSessionTransfer.test.ts@@ -0,0 +1,184 @@+import Database from 'better-sqlite3';+import { mkdtempSync, readFileSync, writeFileSync, renameSync, rmSync, mkdirSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { WorktreeMeta } from '../worktree/types';++const fixture = vi.hoisted(() => ({ db: null as Database.Database | null, unavailable: false }));+vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({+ queryOne: async (sql: string, params: unknown[]) => {+ if (fixture.unavailable) throw new Error('fixture DB unavailable');+ return fixture.db!.prepare(sql).get(...params);+ },+ readLocalWorktreeReferences: async () => [],+}) }));+vi.mock('../localDb/ipc/sessions', () => ({ setWorktreePathInDb: async (id: string, value: string) => {+ if (fixture.unavailable) throw new Error('fixture DB unavailable');+ fixture.db!.prepare('UPDATE sessions SET worktree_path = ? WHERE id = ?').run(value, id);+} }));+vi.mock('../worktree/runtimeLeases', () => ({+ readWorktreeRuntimePaths: async () => new Set(),+ acquireWorktreeRuntimeLease: async () => {}, releaseWorktreeRuntimeLease: async () => {},+}));++let root: string;+let meta: WorktreeMeta;+let manager: typeof import('../worktree/WorktreeManager');+let store: typeof import('../worktree/worktreeStore');+const identity = { delegationId: 'delegation', requestingBotId: 'owner-bot' };+const intent = () => ({ ...meta, pendingSessionTransfer: { ...identity, sessionId: 'next' } });++async function reopenStorage() {+ fixture.db?.close();+ fixture.db = new Database(path.join(root, 'sessions.sqlite'));+ vi.resetModules();+ store = await import('../worktree/worktreeStore');+ // Real atomic disk snapshots, with no in-memory state surviving reopenStorage.+ const registry = path.join(root, 'worktrees.json');+ store._setStoreForTests({+ get: (key: string, fallback: unknown) => JSON.parse(readFileSync(registry, 'utf8'))[key] ?? fallback,+ set: (key: string, value: unknown) => {+ const data = JSON.parse(readFileSync(registry, 'utf8'));+ data[key] = value;+ writeFileSync(`${registry}.tmp`, JSON.stringify(data));+ renameSync(`${registry}.tmp`, registry);+ },+ } as never);+ manager = await import('../worktree/WorktreeManager');+}++function commitChild(next = 'next') {+ fixture.db!.transaction(() => {+ fixture.db!.prepare('INSERT INTO sessions VALUES (?, ?)').run(next, meta.path);+ fixture.db!.prepare('UPDATE bot_delegations SET child_session_id = ? WHERE id = ?').run(next, identity.delegationId);+ })();+ return { reopened: true };+}++beforeEach(async () => {+ root = mkdtempSync(path.join(os.tmpdir(), 'cindy-worktree-transfer-'));+ fixture.unavailable = false;+ writeFileSync(path.join(root, 'worktrees.json'), '{}');+ await reopenStorage();+ fixture.db!.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, worktree_path TEXT); CREATE TABLE bot_delegations (id TEXT PRIMARY KEY, child_session_id TEXT, requesting_bot_id TEXT)');+ meta = { sessionId: 'previous', name: 'task', path: path.join(root, '.cindy-worktrees', 'task'),+ baseRepo: root, branch: 'cindy/task', sourceBranch: 'main', createdAt: '2026-09-12T00:00:00.000Z', generation: 'generation-1' };+ mkdirSync(meta.path, { recursive: true });+ writeFileSync(path.join(meta.path, 'user-work.txt'), 'keep my changes');+ fixture.db!.prepare('INSERT INTO sessions VALUES (?, ?)').run(meta.sessionId, meta.path);+ fixture.db!.prepare('INSERT INTO bot_delegations VALUES (?, ?, ?)').run(identity.delegationId, meta.sessionId, identity.requestingBotId);+ await store.set(meta.sessionId, meta);+});+afterEach(() => {+ fixture.db?.close(); fixture.db = null;+ rmSync(root, { recursive: true, force: true });+});++describe('durable task worktree transfer', () => {+ it('journals before commit and preserves the branch and files through repeated continuations', async () => {+ await manager.withTransferredSession('previous', 'next', meta.path, async () => {+ expect(store.get('previous')).toEqual(intent());+ expect(store.get('next')).toBeNull();+ return commitChild();+ }, identity);+ await manager.removeWorktreeForSession('previous');+ expect(store.get('next')).toEqual({ ...meta, sessionId: 'next' });+ await manager.withTransferredSession('next', 'again', meta.path, async () => commitChild('again'), identity);+ expect(store.get('previous')).toBeNull();+ expect(store.get('next')).toBeNull();+ expect(store.get('again')).toEqual({ ...meta, sessionId: 'again' });+ expect(readFileSync(path.join(meta.path, 'user-work.txt'), 'utf8')).toBe('keep my changes');+ });++ it.each(['throw', 'cas'] as const)('retains the old owner after confirmed %s failure', async failure => {+ const op = manager.withTransferredSession('previous', 'next', meta.path, async () => {+ if (failure === 'throw') throw new Error('fixture commit failed');+ return { reopened: false };+ }, identity);+ if (failure === 'throw') await expect(op).rejects.toThrow('fixture commit failed');+ else expect(await op).toEqual({ reopened: false });+ expect(store.get('previous')).toEqual(meta);+ expect(store.get('next')).toBeNull();+ });++ it('recovers a process exit after the registry write and before the DB commit, then retries once', async () => {+ // Persist exactly the production pre-commit checkpoint; no catch/finally runs.+ await store.replace('previous', 'previous', intent(), meta);+ await reopenStorage();+ await manager.reconcileSessionTransfer('previous');+ expect(store.get('previous')).toEqual(meta);+ await manager.withTransferredSession('previous', 'next', meta.path, async () => commitChild(), identity);+ await reopenStorage();+ await manager.reconcileSessionTransfer('next');+ expect(store.get('next')).toEqual({ ...meta, sessionId: 'next' });+ expect(fixture.db!.prepare('SELECT COUNT(*) AS count FROM sessions').get()).toEqual({ count: 2 });+ });++ it('recovers an uncommitted transfer when the old display snapshot was never available', async () => {+ await store.replace('previous', 'previous', intent(), meta);+ fixture.db!.prepare('UPDATE sessions SET worktree_path = NULL WHERE id = ?').run('previous');+ await reopenStorage();+ await manager.reconcileSessionTransfer('previous');+ expect(store.get('previous')).toEqual(meta);+ expect(store.get('next')).toBeNull();+ });++ it('rejects a missing or occupied owner before executing the DB transaction', async () => {+ const commit = vi.fn(async () => commitChild());+ await expect(manager.withTransferredSession('missing', 'next', meta.path, commit, identity)).rejects.toThrow('ownership changed');+ await store.set('next', { ...meta, sessionId: 'next', path: path.join(root, 'other') });+ await expect(manager.withTransferredSession('previous', 'next', meta.path, commit, identity)).rejects.toThrow('ownership changed');+ expect(commit).not.toHaveBeenCalled();+ expect(store.get('previous')).toEqual(meta);+ });++ it('finishes committed ownership when the worker commit receipt is lost', async () => {+ await expect(manager.withTransferredSession('previous', 'next', meta.path, async () => {+ commitChild();+ throw new Error('fixture lost receipt');+ }, identity)).rejects.toThrow('fixture lost receipt');+ expect(store.get('previous')).toBeNull();+ expect(store.get('next')).toEqual({ ...meta, sessionId: 'next' });+ await reopenStorage();+ await manager.reconcileSessionTransfer('next');+ expect(store.get('next')?.sessionId).toBe('next');+ });++ it.each([false, true])('preserves uncertain outcomes until restart readback (committed: %s)', async committed => {+ await expect(manager.withTransferredSession('previous', 'next', meta.path, async () => {+ if (committed) commitChild();+ fixture.unavailable = true;+ throw new Error('fixture worker exited');+ }, identity)).rejects.toThrow('fixture worker exited');+ expect(store.get('previous')).toEqual(intent());+ // Both ordinary recycling and precreation compensation preserve the journal/files.+ await manager.removeWorktreeForSession('previous', { canRemove: async () => true });+ await manager.removeWorktreeForSession('previous', { preserveDirty: true, canRemove: async () => true });+ expect(readFileSync(path.join(meta.path, 'user-work.txt'), 'utf8')).toBe('keep my changes');+ fixture.unavailable = false;+ await reopenStorage();+ await manager.reconcileSessionTransfer(committed ? 'next' : 'previous');+ await manager.reconcileSessionTransfer(committed ? 'next' : 'previous');+ expect(store.get(committed ? 'next' : 'previous')).toEqual({ ...meta, sessionId: committed ? 'next' : 'previous' });+ });++ it.each(['owner', 'target', 'path-owner', 'generation'] as const)('never steals conflicting %s ownership during recovery', async conflict => {+ await store.replace('previous', 'previous', intent(), meta);+ commitChild();+ if (conflict === 'owner') fixture.db!.prepare('UPDATE bot_delegations SET requesting_bot_id = ?').run('other-bot');+ if (conflict === 'target') await store.set('next', { ...meta, sessionId: 'next', path: path.join(root, 'other') });+ if (conflict === 'path-owner') await store.set('other', { ...meta, sessionId: 'other' });+ if (conflict === 'generation') {+ const originalReplace = store.replace;+ const replace = vi.spyOn(store, 'replace');+ replace.mockImplementationOnce(async (...args) => {+ await store.set('previous', { ...intent(), generation: 'replacement-generation' });+ return originalReplace(...args);+ });+ }+ await expect(manager.reconcileSessionTransfer('next')).rejects.toThrow('ownership changed');+ expect(store.get('previous')?.pendingSessionTransfer).toEqual(intent().pendingSessionTransfer);+ expect(readFileSync(path.join(meta.path, 'user-work.txt'), 'utf8')).toBe('keep my changes');+ });+});diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 9e2f8e914f..a5bc598d2e 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -714,6 +714,7 @@ export interface BotsCreateDelegationArgs {}export interface BotsReopenDelegationArgs {+ worktreePath?: string | null;maxActiveChildren: number;delegationId: string;requestingBotId: string;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex da70efd71c..b4b822dee7 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -1,6 +1,10 @@import { getSelectedNewMakerRoute, setNewMakerDraftCache } from '../../../maker-host/newMakerDefaultsCache';import { setModelVisibilityMirror } from '../../../maker-host/model-visibility-mirror';import Database from 'better-sqlite3';+import { AgentInputCoordinator } from '../../../maker-ipc/agent-input-coordinator';+import { createSessionQueueControlService } from '../../../maker-ipc/sessionQueueControl';+import { authorizeSessionQueueItem, rebuildSessionQueueItem } from '../../../maker-ipc/sessionControlService';+import type { AgentInputQueuedMessage } from '../../../../shared/agentInputQueue';import type { ProviderView } from '@cindy/model-providers';import { createHash } from 'node:crypto';import { join, resolve } from 'node:path';@@ -9,6 +13,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'nodeimport { drizzle } from 'drizzle-orm/better-sqlite3';import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';import { BOT_TEMPLATE_PRESET_IDENTITIES } from '../../../../shared/botTemplatePreset';+import { normalizeWorkingDirForStorage } from '../../../../shared/workingDir';import { createBotModelRouteReconciler } from '../../../maker-ipc/botModelRouteReconciler';import type { BotModelRoute } from '../../../../shared/botModelChain';import type { AgentKind } from '@cindy/maker-core';@@ -3235,6 +3240,17 @@ describe('Bot Session task end-to-end runtime', () => {}function createDelegationRuntime(options: {+ getWorktree?: Parameters<typeof createBotDelegationService>[0]['getWorktree'];+ withTransferredWorktree?: Parameters<typeof createBotDelegationService>[0]['withTransferredWorktree'];+ prepareWorktree?: Parameters<typeof createBotDelegationService>[0]['prepareWorktree'];+ taskQueue?: Parameters<typeof createBotDelegationService>[0]['taskQueue'];+ taskControl?: boolean;+ queueSnapshots?: Map<string, AgentInputQueuedMessage[]>;+ onNativeStarted?: (sessionId: string) => void;+ appliedOnResume?: () => string[];+ reconcileWorktree?: Parameters<typeof createBotDelegationService>[0]['reconcileWorktree'];+ stopUnsupported?: boolean;+ steerUnsupported?: boolean;readCallerRuntime?: Parameters<typeof createBotDelegationService>[0]['readCallerRuntime'];readCallerPermission?: Parameters<typeof createBotDelegationService>[0]['readCallerPermission'];accountReady?: () => boolean;@@ -3248,6 +3264,7 @@ describe('Bot Session task end-to-end runtime', () => {const accountReady = options.accountReady ?? (() => true);const started: StartedTurn[] = [];const pendingTurns: Array<{ sessionId: string; queued: boolean }> = [];+ const heldInputs = new Set<string>();const changed: Array<{ delegationId: string; status: string }> = [];let currentTime = options.startTime ?? 10_000;let seq = 0;@@ -3291,8 +3308,9 @@ describe('Bot Session task end-to-end runtime', () => {* dispatchBotSessionMessage → sendToSessionInternal)。判据顺序刻意与真机一致:* 任何一条在真机上会挡住会话启动的门,这里也必须挡住。*/- const dispatch = vi.fn(async (params: {+ const dispatchDirect = vi.fn(async (params: {targetSessionId: string;+ dispatcherSessionId?: string;message: string;persistedContent?: string;clientId?: string;@@ -3363,6 +3381,8 @@ describe('Bot Session task end-to-end runtime', () => {'user',params.persistedContent ?? params.message,);+ 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);await params.onAccepted?.();h.sqlite!.prepare('UPDATE sessions SET active_turn_started_at = ? WHERE id = ?').run(currentTime, params.targetSessionId);@@ -3374,8 +3394,86 @@ describe('Bot Session task end-to-end runtime', () => {};});- const abortSession = vi.fn(async () => undefined);+ // Use the production coordinator for resume durability tests. The normal+ // dispatch fixture above deliberately models only the native send boundary.+ const acceptedCallbacks = new Map<string, () => void | Promise<void>>();+ const coordinator = options.queueSnapshots ? new AgentInputCoordinator({+ isTurnRunning: id => pendingTurns.some(turn => turn.sessionId === id && !turn.queued),+ hasPendingInteraction: () => false,+ getAgentKind: () => 'pi',+ getSdkSessionId: async () => undefined,+ emitProjection: () => undefined,+ steerToAgent: async () => undefined,+ abortSession: async () => undefined,+ persistQueueSnapshot: (id, items) => { options.queueSnapshots!.set(id, structuredClone(items)); },+ loadQueueSnapshot: async id => options.queueSnapshots!.get(id) ?? [],+ getPersistedClientIds: async (id, ids) => new Set(ids.filter(clientId => hasMessage(id, clientId))),+ sendToAgent: async (id, _message, _opts, sendOpts) => {+ const persisted = sendOpts.persistUserMessage;+ if (!persisted) throw new Error('Missing coordinator user row');+ writeMessage(id, persisted.clientId, 'user', persisted.content);+ await persisted.onPersisted?.();+ const row = readSession(id)!;+ started.push({ sessionId: id, ...row });+ h.sqlite!.prepare('UPDATE sessions SET active_turn_started_at = ? WHERE id = ?').run(currentTime, id);+ pendingTurns.push({ sessionId: id, queued: false });+ options.onNativeStarted?.(id);+ return { kind: 'session-dispatch', source: 'fixture-native-turn', dispatched: true };+ },+ onAcceptedQueuedMessage: async (_id, item) => { await acceptedCallbacks.get(item.clientId)?.(); },+ }) : undefined;+ const dispatch = vi.fn(async (params: Parameters<typeof dispatchDirect>[0]) => {+ if (coordinator) {+ await coordinator.ensureQueueRestored(params.targetSessionId);+ // Same admission decision as sendToSessionInternal, before any native+ // send or persisted client-ID receipt exists.+ if (coordinator.shouldQueueNewTurn(params.targetSessionId)) {+ const clientId = params.clientId ?? `queued-${++seq}`;+ if (params.onAccepted) acceptedCallbacks.set(clientId, params.onAccepted);+ coordinator.enqueue(params.targetSessionId, {+ clientId, text: params.message, persistedContent: params.persistedContent ?? params.message,+ model: 'grok-4.5', effort: 'high', permissionMode: 'default', workingDir: h.userDataDir,+ chatMessage: { clientId, role: 'user', content: params.message,+ isStreaming: false, createdAt: new Date(currentTime).toISOString() },+ createOpts: { agentKind: 'pi', workingDir: h.userDataDir, model: 'grok-4.5',+ permissionMode: 'default', userPrompt: '', makerMemoryEnabled: false, displayReasoning: 'summarized' },+ });+ return { ok: true as const, targetSessionId: params.targetSessionId, wakeKind: 'queued' as const };+ }+ }+ return dispatchDirect(params);+ });++ const abortSession = vi.fn(async (id: string): Promise<void> => { coordinator?.stop(id); });+ const steer = vi.fn<NonNullable<Parameters<typeof createBotDelegationService>[0]['taskControl']>['steer']>(async () => options.steerUnsupported+ ? { ok: false as const, errorCode: 'UNSUPPORTED_CAPABILITY' as const, message: 'No same-turn steer' }+ : { ok: true as const, queuedMessageId: 'steered-message' });+ const stopTurn = vi.fn(async () => options.stopUnsupported+ ? { ok: false as const, errorCode: 'UNSUPPORTED_CAPABILITY' as const, message: 'No graceful stop' }+ : { ok: true as const, status: 'requested' as const });+ const waitForInputBoundary = vi.fn(async () => undefined);+ const preparePause = vi.fn(async () => undefined);+ const flushInput = vi.fn(async (): Promise<void> => undefined);const delegation = createBotDelegationService({+ prepareWorktree: options.prepareWorktree,+ getWorktree: options.getWorktree,+ reconcileWorktree: options.reconcileWorktree,+ withTransferredWorktree: options.withTransferredWorktree,+ taskQueue: options.taskQueue,+ ...(options.taskControl ? { taskControl: {+ steer, stop: stopTurn,+ isActive: (id: string) => pendingTurns.some((turn) => turn.sessionId === id && !turn.queued),+ holdInput: (id: string, held: boolean) => {+ if (held) heldInputs.add(id); else heldInputs.delete(id);+ coordinator?.setExecutionPaused(id, held);+ return held ? [] : options.appliedOnResume?.() ?? [];+ },+ waitForInputBoundary,+ preparePause,+ restoreInput: async id => { await coordinator?.ensureQueueRestored(id); },+ flushInput,+ resumeInput: async id => { coordinator?.resume(id); },+ } } : {}),readCallerRuntime: options.readCallerRuntime,readCallerPermission: options.readCallerPermission,dispatch,@@ -3383,7 +3481,7 @@ describe('Bot Session task end-to-end runtime', () => {closeSession: vi.fn(async () => undefined),broadcastSessionCreated: vi.fn(),resolveInteraction: options.resolveInteraction,- hasPendingInput: (sessionId) => pendingTurns.some(+ hasPendingInput: (sessionId) => coordinator?.hasPendingQueuedWork(sessionId) || pendingTurns.some((turn) => turn.sessionId === sessionId && turn.queued,),onChanged: (payload) => {@@ -3422,6 +3520,7 @@ describe('Bot Session task end-to-end runtime', () => {`UPDATE sessions SET total_token_usage = total_token_usage + 100,last_turn_ended_at = ? WHERE id = ?`,).run(currentTime, sessionId);+ coordinator?.onTurnEvent(sessionId, 'done');await delegation.settleSession({childSessionId: sessionId,outcome: 'done',@@ -3430,7 +3529,8 @@ describe('Bot Session task end-to-end runtime', () => {};return {- delegation,+ delegation, coordinator,+ heldInputs, steer, stopTurn, waitForInputBoundary, preparePause, flushInput,dispatch,abortSession,started,@@ -3439,6 +3539,7 @@ describe('Bot Session task end-to-end runtime', () => {settleChild,dispose: () => {delegation.dispose();+ if (coordinator) for (const id of options.queueSnapshots!.keys()) coordinator.setExecutionPaused(id, true);},advance: (ms: number) => {currentTime += ms;@@ -3800,6 +3901,840 @@ describe('Bot Session task end-to-end runtime', () => {}});+ it('binds a prepared worktree before first dispatch and rejects unavailable isolation', async () => {+ await seedPair();+ const workspace = join(h.userDataDir, 'task-project-worktree');+ mkdirSync(workspace, { recursive: true });+ const runtime = createDelegationRuntime({ prepareWorktree: async () => ({ ok: true, sessionId: 'worktree-session', workingDir: workspace }) });+ try {+ const result = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Edit this project.', workingDir: h.userDataDir, useWorktree: true });+ expect(result).toMatchObject({ ok: true, childSessionId: 'worktree-session' });+ if (!result.ok) throw new Error('missing task');+ expect(await runtime.delegation.getSessionTask('session-1', result.delegationId))+ .toMatchObject({ task: { working_dir: normalizeWorkingDirForStorage(workspace), workspace_kind: 'project' } });+ expect(runtime.started[0].sessionId).toBe('worktree-session');+ expect(h.sqlite!.prepare('SELECT worktree_path AS path FROM sessions WHERE id = ?').get('worktree-session')).toEqual({ path: workspace });+ } finally { runtime.dispose(); }+ const unavailable = createDelegationRuntime();+ try {+ expect(await unavailable.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Edit.', workingDir: workspace, useWorktree: true }))+ .toMatchObject({ ok: false, errorCode: 'WORKTREE_UNAVAILABLE' });+ expect(unavailable.started).toHaveLength(0);+ } finally { unavailable.dispose(); }+ });++ it('commits the worktree snapshot for each continuation and leaves no child when that transaction fails', async () => {+ await seedPair();+ const workspace = join(h.userDataDir, 'continued-worktree');+ mkdirSync(workspace, { recursive: true });+ let owner = 'worktree-first';+ const runtime = createDelegationRuntime({+ prepareWorktree: async () => ({ ok: true, sessionId: owner, workingDir: workspace }),+ getWorktree: id => id === owner ? { path: workspace } : null,+ withTransferredWorktree: async (previous, next, worktreePath, commit) => {+ expect(previous).toBe(owner);+ expect(worktreePath).toBe(workspace);+ const result = await commit();+ if (result.reopened) owner = next;+ return result;+ },+ });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Preserve files.', workingDir: h.userDataDir, useWorktree: true });+ if (!task.ok) throw new Error('task failed');+ await runtime.settleChild(owner, 'First result.');+ // The manager remains authoritative even if the display snapshot is absent.+ h.sqlite!.prepare('UPDATE sessions SET worktree_path = NULL WHERE id = ?').run(owner);+ h.sqlite!.exec("CREATE TEMP TRIGGER fail_reopen_binding BEFORE UPDATE OF worktree_path ON sessions BEGIN SELECT RAISE(FAIL, 'fixture transfer failure'); END");+ const before = h.sqlite!.prepare('SELECT COUNT(*) AS count FROM sessions').get();+ const startedBeforeFailure = runtime.started.length;+ await expect(runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'Continue.' })).rejects.toThrow('fixture transfer failure');+ expect(h.sqlite!.prepare('SELECT COUNT(*) AS count FROM sessions').get()).toEqual(before);+ expect(runtime.started).toHaveLength(startedBeforeFailure);+ expect(owner).toBe('worktree-first');+ h.sqlite!.exec('DROP TRIGGER fail_reopen_binding');+ for (let round = 0; round < 2; round++) {+ 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(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);+ await runtime.settleChild(owner, 'Next result.');+ }+ } finally {+ h.sqlite!.exec('DROP TRIGGER IF EXISTS fail_reopen_binding');+ runtime.dispose();+ }+ });++ it('still publishes and dispatches a committed worktree task when its display snapshot fails', async () => {+ await seedPair();+ const runtime = createDelegationRuntime({ prepareWorktree: async () => ({ ok: true,+ sessionId: 'snapshot-failure-session', workingDir: h.userDataDir }) });+ h.sqlite!.exec("CREATE TEMP TRIGGER fail_worktree_snapshot BEFORE UPDATE OF worktree_path ON sessions BEGIN SELECT RAISE(FAIL, 'fixture snapshot unavailable'); END");+ try {+ const result = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1',+ objective: 'Continue despite an unavailable display snapshot.', workingDir: h.userDataDir, useWorktree: true });+ expect(result).toMatchObject({ ok: true, childSessionId: 'snapshot-failure-session' });+ if (!result.ok) throw new Error('task failed');+ expect(runtime.started.map(turn => turn.sessionId)).toEqual(['snapshot-failure-session']);+ expect(await runtime.delegation.getSessionTask('session-1', result.delegationId))+ .toMatchObject({ task: { status: 'running', working_dir: normalizeWorkingDirForStorage(h.userDataDir) } });+ await runtime.settleChild(result.childSessionId, 'Finished.');+ expect(await runtime.delegation.getSessionTask('session-1', result.delegationId))+ .toMatchObject({ task: { status: 'completed' } });+ } finally { h.sqlite!.exec('DROP TRIGGER fail_worktree_snapshot'); runtime.dispose(); }+ });++ it.each(['running', 'queued', 'paused'] as const)('preserves the %s input and timers when cancellation intent cannot be persisted', async (state) => {+ await seedPair();+ vi.useFakeTimers();+ let unavailable = state === 'queued';+ const runtime = createDelegationRuntime({ taskControl: true, transientUnavailable: () => unavailable });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish safely.', timeoutMs: 10_000 });+ if (!task.ok) throw new Error('task failed');+ if (state === 'paused') await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ const before = await runtime.delegation.getSessionTask('session-1', task.delegationId);+ h.sqlite!.exec("CREATE TEMP TRIGGER fail_cancel_intent BEFORE UPDATE OF permission_snapshot_json ON bot_delegations WHEN json_extract(NEW.permission_snapshot_json, '$.taskCancelRequested') = 1 BEGIN SELECT RAISE(FAIL, 'fixture cancel unavailable'); END");+ await expect(runtime.delegation.stopSessionTask('session-1', task.delegationId)).rejects.toThrow();+ h.sqlite!.exec('DROP TRIGGER fail_cancel_intent');+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(state === 'paused');+ expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toEqual(before);+ if (state === 'queued') {+ unavailable = false;+ runtime.advance(1_000);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(runtime.started.map(turn => turn.sessionId)).toContain(task.childSessionId);+ }+ runtime.advance(10_000);+ await vi.advanceTimersByTimeAsync(10_000);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: state === 'paused' ? 'waiting' : 'timed-out' } });+ } finally {+ h.sqlite!.exec('DROP TRIGGER IF EXISTS fail_cancel_intent');+ runtime.dispose();+ vi.useRealTimers();+ }+ });++ it.each(['running', 'completed', 'failed'] as const)('retains %s status and receipts when queue restoration fails', async (state) => {+ await seedPair();+ const inspect = vi.fn(async () => { throw new Error('Task queue restoration is incomplete'); });+ const runtime = createDelegationRuntime({ taskControl: true, taskQueue: {+ inspect, update: vi.fn(), cancel: vi.fn(),+ } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish safely.' });+ if (!task.ok) throw new Error('task failed');+ const sent = await runtime.delegation.messageSessionTask('session-1', task.delegationId,+ { kind: 'message', text: 'additional requirement', idempotencyKey: 'receipt' });+ if (!sent.ok || !('queuedMessageId' in sent)) throw new Error('missing receipt');+ if (state !== 'running') h.sqlite!.prepare('UPDATE bot_delegations SET status = ?, result_summary = ?, last_error = ? WHERE id = ?')+ .run(state, 'Saved result', state === 'failed' ? 'FIXTURE: Saved error' : null, task.delegationId);+ for (const messageId of [undefined, 'missing', sent.queuedMessageId]) {+ const result = await runtime.delegation.getSessionTask('session-1', task.delegationId, messageId);+ expect(result).toMatchObject({ ok: true, task: { status: state, queue: null, queue_error: 'QUEUE_UNAVAILABLE' } });+ if (!result.ok) throw new Error('missing task');+ if (state !== 'running') expect(result.task.result).toBe('Saved result');+ if (state === 'failed') expect(result.task.error).toBe('Saved error');+ expect(result.task.message_receipt).toEqual(messageId ? {+ queued_message_id: messageId, state: messageId === sent.queuedMessageId ? 'dispatched' : 'unavailable',+ } : undefined);+ }+ } finally { runtime.dispose(); }+ });++ it('keeps steer IDs stable and reuses persisted receipts after runtime replacement', async () => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish safely.' });+ if (!task.ok) throw new Error('task failed');+ const input = { kind: 'message' as const, text: 'urgent', mode: 'steer' as const, idempotencyKey: 'retry:完整/key' };+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, input);+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, input);+ const calls = runtime.steer.mock.calls;+ const id = calls[0][0].queuedMessageId;+ if (!id) throw new Error('missing stable ID');+ expect(id).toEqual(expect.stringMatching(/^bot-task-steer:[a-f0-9]{64}$/));+ expect(calls[1][0].queuedMessageId).toBe(id);+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { ...input, idempotencyKey: 'retry完整key' });+ expect(calls[2][0].queuedMessageId).not.toBe(id);+ h.sqlite!.prepare('INSERT INTO messages (id, client_id, session_id, role, content, created_at, agent_meta) VALUES (?, ?, ?, ?, ?, ?, ?)')+ .run('accepted-steer', id, task.childSessionId, 'user', input.text, 10_000,+ JSON.stringify({ origin: { kind: 'session', senderSessionId: 'session-1' } }));+ const restored = createDelegationRuntime({ taskControl: true });+ try {+ expect(await restored.delegation.messageSessionTask('session-1', task.delegationId, input))+ .toMatchObject({ ok: true, delivery: 'same-turn', queuedMessageId: id });+ expect(restored.steer).not.toHaveBeenCalled();+ expect(restored.started).toHaveLength(0);+ expect(await restored.delegation.messageSessionTask('session-2', task.delegationId, input))+ .toMatchObject({ ok: false, errorCode: 'NOT_A_BOT_SESSION' });+ } finally { restored.dispose(); }+ } finally { runtime.dispose(); }+ });++ it.each(['waitForInputBoundary', 'stopTurn', 'preparePause', 'flushInput'] as const)('retries an uncertain pause after %s fails', async (stage) => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish safely.' });+ if (!task.ok) throw new Error('task failed');+ runtime[stage].mockRejectedValueOnce(new Error('transient fixture failure'));+ expect(await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause'))+ .toMatchObject({ ok: false, errorCode: 'PAUSE_UNCONFIRMED' });+ const before = await runtime.delegation.getSessionTask('session-1', task.delegationId);+ runtime.advance(1_000);+ expect(await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause'))+ .toMatchObject({ ok: true, control: { state: 'pausing' } });+ expect(runtime[stage]).toHaveBeenCalledTimes(2);+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(true);+ await runtime.settleChild(task.childSessionId, 'Stopped.');+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: true });+ const after = await runtime.delegation.getSessionTask('session-1', task.delegationId);+ if (!before.ok || !after.ok) throw new Error('missing task');+ expect(after.task.deadline_at).toBe(before.task.deadline_at! + 1_000);+ } finally { runtime.dispose(); }+ });++ it('does not acknowledge pause until the retained input snapshot has finished writing', async () => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true });+ let release!: () => void;+ const persisted = new Promise<void>(resolve => { release = resolve; });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Retain the supplement.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'queued supplement' });+ runtime.flushInput.mockImplementationOnce(() => persisted);+ let acknowledged = false;+ const paused = runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause')+ .then(result => { acknowledged = true; return result; });+ await vi.waitFor(() => expect(runtime.flushInput).toHaveBeenCalledWith(task.childSessionId));+ expect(acknowledged).toBe(false);+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(true);+ release();+ expect(await paused).toMatchObject({ ok: true });+ } finally { release(); runtime.dispose(); }+ });++ it.each(['bot', 'parent'] as const)('serializes %s lifecycle cancellation with the held resume commit', async (scope) => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true });+ let release!: () => void;+ const boundary = new Promise<void>(resolve => { release = resolve; });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish safely.' });+ if (!task.ok) throw new Error('task failed');+ await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ await runtime.settleChild(task.childSessionId, 'Stopped.');+ let atBoundary = false;+ runtime.flushInput.mockImplementationOnce(async () => { atBoundary = true; await boundary; });+ const resumed = runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' });+ await vi.waitFor(() => expect(atBoundary).toBe(true));+ let cancellationSettled = false;+ const cancelled = (scope === 'bot'+ ? runtime.delegation.cancelDelegationsForBot('bot-a')+ : runtime.delegation.cancelDelegationsForParentSession('session-1'))+ .then(result => { cancellationSettled = true; return result; });+ await new Promise(resolve => setImmediate(resolve));+ expect(cancellationSettled).toBe(false);+ expect(h.sqlite!.prepare('SELECT status FROM bot_delegations WHERE id = ?').get(task.delegationId))+ .toEqual({ status: 'waiting' });+ // An abort awaiting its terminal callback must not deadlock with the lock.+ runtime.abortSession.mockImplementationOnce(async () => runtime.settleChild(task.childSessionId, 'Cancelled.'));+ release();+ expect(await resumed).toMatchObject({ ok: true });+ expect(await cancelled).toBe(1);+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(false);+ const count = runtime.started.length;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: false, errorCode: 'NOT_PAUSED' });+ expect(runtime.started).toHaveLength(count);+ } finally { release(); runtime.dispose(); }+ });++ it('routes owned queue edits through the shared consuming and sender guards and reports dispatch receipts', async () => {+ await seedPair();+ const item = (clientId: string, sender: string): AgentInputQueuedMessage => ({+ clientId, text: 'before', persistedContent: 'before', model: 'model', effort: 'medium', permissionMode: 'default', workingDir: h.userDataDir,+ chatMessage: { clientId, role: 'user', content: 'before' },+ createOpts: { agentKind: 'codex', workingDir: h.userDataDir, model: 'model', effort: 'medium', permissionMode: 'default' },+ origin: { kind: 'session', senderSessionId: sender, displayText: 'before' },+ });+ let queue = [item('mine', 'session-1'), item('foreign', 'other-session')];+ const consumingClientIds: string[] = [];+ const shared = createSessionQueueControlService({+ getSnapshot: async () => ({ pendingQueue: queue, consumingClientIds }),+ replaceQueuedMessage: (_id, clientId, next) => {+ const index = queue.findIndex(item => item.clientId === clientId);+ if (index < 0) return false;+ queue[index] = next; return true;+ },+ removeQueuedMessage: (_id, clientId) => { queue = queue.filter(item => item.clientId !== clientId); return true; },+ });+ const runtime = createDelegationRuntime({ taskControl: true, taskQueue: {+ inspect: async (_id, caller) => queue.filter(item => authorizeSessionQueueItem(item, caller).ok)+ .map(item => ({ queuedMessageId: item.clientId, consuming: consumingClientIds.includes(item.clientId), message: item.text })),+ update: params => shared.update({ sessionId: params.targetSessionId, queuedMessageId: params.queuedMessageId, message: params.message,+ authorize: item => authorizeSessionQueueItem(item, params.callerSessionId), rebuild: rebuildSessionQueueItem }),+ cancel: params => shared.cancel({ sessionId: params.targetSessionId, queuedMessageId: params.queuedMessageId,+ authorize: item => authorizeSessionQueueItem(item, params.callerSessionId) }),+ } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish the report.' });+ if (!task.ok) throw new Error('missing task');+ const edit = (id: string) => runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'edit', queuedMessageId: id, text: 'revised' });+ expect(await edit('foreign')).toMatchObject({ ok: false, errorCode: 'NOT_AUTHORIZED' });+ expect(await edit('mine')).toMatchObject({ ok: true, delivery: 'queued' });+ expect(queue[0].persistedContent).toBe('revised');+ consumingClientIds.push('mine');+ expect(await edit('mine')).toMatchObject({ ok: false, errorCode: 'MESSAGE_CONSUMING' });+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId, 'mine'))+ .toMatchObject({ task: { queue: [{ queuedMessageId: 'mine', message: 'revised', consuming: true }], message_receipt: { state: 'consuming' } } });+ consumingClientIds.length = 0;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'withdraw', queuedMessageId: 'mine' }))+ .toMatchObject({ ok: true, delivery: 'withdrawn' });+ expect(queue.map(item => item.clientId)).toEqual(['foreign']);+ const message = await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'additional requirements' });+ if (!message.ok || !('queuedMessageId' in message)) throw new Error('missing receipt');+ expect(message.queuedMessageId).toEqual(expect.any(String));+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId, message.queuedMessageId))+ .toMatchObject({ task: { message_receipt: { state: 'dispatched' } } });+ } finally { runtime.dispose(); }+ });++ it('holds a paused execution through terminal events and restart, then resumes the same Session once', async () => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true });+ try {+ const started = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Perform a non-repeatable action, then summarize.' });+ if (!started.ok) throw new Error('task did not start');+ const taskId = started.delegationId;+ const sessionId = started.childSessionId;+ const before = await runtime.delegation.getSessionTask('session-1', taskId);+ expect(await runtime.delegation.stopSessionTask('session-1', taskId, 'pause'))+ .toMatchObject({ ok: true, control: { state: 'pausing', queue_held: true, stop_status: 'requested' } });+ expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(await runtime.delegation.messageSessionTask('session-1', taskId, { kind: 'resume' }))+ .toMatchObject({ ok: false, errorCode: 'STOP_UNCONFIRMED' });+ expect(await runtime.delegation.messageSessionTask('session-1', taskId, { kind: 'message', text: 'new' }))+ .toMatchObject({ ok: false, errorCode: 'TASK_PAUSED' });+ // An interaction arriving after stop was requested must not retract that stop.+ const lateRequest = { kind: 'permission' as const, requestId: 'late-approval', toolName: 'write_file', input: {} };+ await runtime.delegation.handleInteractionStart(sessionId, lateRequest);+ expect(await runtime.delegation.messageSessionTask('session-1', taskId, { kind: 'resume' }))+ .toMatchObject({ ok: false, errorCode: 'STOP_UNCONFIRMED' });+ await runtime.delegation.handleInteractionEnd(sessionId, lateRequest);+ await runtime.settleChild(sessionId, 'Partial work already performed.');+ expect(await runtime.delegation.getSessionTask('session-1', taskId))+ .toMatchObject({ ok: true, task: { status: 'waiting', control: { state: 'paused' }, completed_at: null } });+ expect(runtime.started.filter((turn) => turn.sessionId === 'session-1')).toHaveLength(0);+ runtime.advance(120_000);+ const startCount = runtime.started.length;+ await runtime.delegation.restore();+ expect(runtime.started).toHaveLength(startCount);+ const restored = createDelegationRuntime({ taskControl: true, startTime: 130_000 });+ try {+ await restored.delegation.restore();+ expect(restored.started).toHaveLength(0);+ expect(restored.heldInputs.has(sessionId)).toBe(true);+ const results = await Promise.all([+ restored.delegation.messageSessionTask('session-1', taskId, { kind: 'resume' }),+ restored.delegation.messageSessionTask('session-1', taskId, { kind: 'resume' }),+ ]);+ expect(results.filter((result) => result.ok)).toHaveLength(2); // Same resume receipt; only one dispatch.+ expect(restored.started.map((turn) => turn.sessionId)).toEqual([sessionId]);+ const after = await restored.delegation.getSessionTask('session-1', taskId);+ if (!before.ok || !after.ok) throw new Error('missing task');+ expect(after.task.deadline_at).toBe(before.task.deadline_at! + 120_000);+ expect(after.task.session_id).toBe(sessionId);+ const inputs = h.sqlite!.prepare("SELECT content FROM messages WHERE session_id = ? AND role = 'user' ORDER BY rowid").all(sessionId) as Array<{ content: string }>;+ expect(inputs).toHaveLength(2);+ expect(inputs[1].content).toContain('do not replay the original request');+ await restored.settleChild(sessionId, 'Final result.');+ expect(await restored.delegation.getSessionTask('session-1', taskId))+ .toMatchObject({ ok: true, task: { status: 'completed', result: 'Final result.' } });+ expect(restored.started.filter((turn) => turn.sessionId === 'session-1')).toHaveLength(1);+ } finally { restored.dispose(); }+ } finally { runtime.dispose(); }+ });++ it.each(['claude', 'codex', 'pi'])('keeps owned %s task steer distinct from queue and preserves denial', async (harness) => {+ await seedPair({ harness });+ const runtime = createDelegationRuntime({ taskControl: true, steerUnsupported: true });+ try {+ const started = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish a report.' });+ if (!started.ok) throw new Error('task did not start');+ const count = runtime.started.length;+ expect(await runtime.delegation.messageSessionTask('session-1', started.delegationId,+ { kind: 'message', text: 'urgent', mode: 'steer' }))+ .toMatchObject({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' });+ expect(runtime.started).toHaveLength(count);+ expect(await runtime.delegation.stopSessionTask(started.childSessionId, started.delegationId, 'pause'))+ .toMatchObject({ ok: false, errorCode: 'NOT_A_BOT_SESSION' });+ expect(runtime.stopTurn).not.toHaveBeenCalled();+ expect(await runtime.delegation.messageSessionTask('session-1', started.delegationId,+ { kind: 'message', text: 'next turn' }))+ .toMatchObject({ ok: true, queued: true, delivery: 'queued' });+ } finally { runtime.dispose(); }+ });++ it.each([false, true])('preserves the permission input boundary after a failed pause write (already paused: %s)', async alreadyPaused => {+ await seedPair();+ const resolveInteraction = vi.fn(() => true);+ const runtime = createDelegationRuntime({ taskControl: true, resolveInteraction });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Wait for approval.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.handleInteractionStart(task.childSessionId,+ { kind: 'permission', requestId: 'pause-write-permission', toolName: 'write_file', input: {} });+ if (alreadyPaused) await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ const before = await runtime.delegation.getSessionTask('session-1', task.delegationId);+ h.sqlite!.exec("CREATE TEMP TRIGGER fail_pause_write BEFORE UPDATE OF permission_snapshot_json ON bot_delegations BEGIN SELECT RAISE(FAIL, 'fixture pause unavailable'); END");+ expect(await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause'))+ .toMatchObject({ ok: false, errorCode: 'PAUSE_UNCONFIRMED' });+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(alreadyPaused);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toEqual(before);+ expect(resolveInteraction).not.toHaveBeenCalled();+ expect(runtime.stopTurn).not.toHaveBeenCalled();+ h.sqlite!.exec('DROP TRIGGER fail_pause_write');+ if (alreadyPaused) expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: true, delivery: 'awaiting-interaction' });+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'approve' }))+ .toMatchObject({ ok: true, delivery: 'interaction' });+ expect(resolveInteraction).toHaveBeenCalledTimes(1);+ } finally { h.sqlite!.exec('DROP TRIGGER IF EXISTS fail_pause_write'); runtime.dispose(); }+ });++ it.each(['queued', 'completed'] as const)('keeps %s recovery retryable after an unavailable worktree readback', async status => {+ await seedPair();+ let blocked = true;+ const reconcileWorktree = vi.fn(async () => { if (blocked) throw new Error('fixture reconciliation unavailable'); });+ const runtime = createDelegationRuntime({ taskControl: true, reconcileWorktree });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Resume only after ownership readback.' });+ if (!task.ok) throw new Error('missing task');+ if (status === 'completed') h.sqlite!.prepare("UPDATE bot_delegations SET status = 'completed', result_summary = 'fixture finished' WHERE id = ?").run(task.delegationId);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ ok: true, task: { status } });+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'continue' }))+ .toMatchObject({ ok: false, errorCode: 'WORKTREE_TRANSFER_PENDING' });+ const { createBotRuntimeRestoreCoordinator } = await import('../../../maker-ipc/botRuntimeRestore');+ const coordinator = createBotRuntimeRestoreCoordinator({+ readDbIdentity: () => ({ userId: 'owner', clientEpoch: 1 }),+ readServices: () => ({ directMessages: { restore: async () => undefined }, delegation: runtime.delegation }),+ log: { warn: vi.fn() },+ });+ expect(await coordinator.restoreCurrentOwner()).toBe(false);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ ok: true, task: { status } });+ blocked = false;+ expect(await coordinator.restoreCurrentOwner()).toBe(true);+ expect(await coordinator.restoreCurrentOwner()).toBe(true);+ // A new owner epoch performs a real recovery pass; durable receipts must+ // also prevent duplicate delivery when coordinator caching cannot help.+ await runtime.delegation.restore();+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ ok: true, task: { status: status === 'queued' ? 'running' : 'completed' } });+ expect(runtime.dispatch.mock.calls.filter(([params]) => params.clientId === `bot-delegation-start:${task.delegationId}`)).toHaveLength(status === 'queued' ? 1 : 0);+ if (status === 'completed') {+ expect((h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id = ?').get(task.delegationId) as { completion_delivered_at: number | null }).completion_delivered_at).not.toBeNull();+ expect(runtime.dispatch.mock.calls.filter(([params]) => params.targetSessionId === 'session-1')).toHaveLength(1);+ }+ } finally { runtime.dispose(); }+ });++ it.each([false, true])('retries the resume dispatch readback failure unless cancelled (%s)', async cancel => {+ await seedPair();+ vi.useFakeTimers();+ let readbacks = 0;+ let failReadback = false;+ const runtime = createDelegationRuntime({ taskControl: true, reconcileWorktree: async () => {+ if (failReadback && ++readbacks === 2) throw new Error('fixture second readback unavailable');+ } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Recover the interrupted turn.' });+ if (!task.ok) throw new Error('missing task');+ failReadback = true;+ await runtime.delegation.restore();+ const resumeCalls = () => runtime.dispatch.mock.calls.filter(([params]) => params.clientId?.startsWith(`bot-delegation-resume:${task.delegationId}:`));+ expect(resumeCalls()).toHaveLength(0);+ if (cancel) {+ await runtime.delegation.stopSessionTask('session-1', task.delegationId);+ await runtime.settleChild(task.childSessionId, 'Cancelled.');+ }+ runtime.advance(1_000);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(resumeCalls()).toHaveLength(cancel ? 0 : 1);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ ok: true, task: { status: cancel ? 'cancelled' : 'running' } });+ } finally { runtime.dispose(); vi.useRealTimers(); }+ });++ it('preserves other recovery progress and never dispatches a task cancelled between failed passes', async () => {+ await seedPair();+ let blockedSession: string | null = null;+ let unavailable = true;+ const runtime = createDelegationRuntime({ taskControl: true,+ transientUnavailable: () => unavailable,+ reconcileWorktree: async sessionId => {+ if (sessionId === blockedSession) throw new Error('fixture reconciliation unavailable');+ },+ });+ try {+ const blocked = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Cancel before recovery.' });+ const unaffected = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Recover the independent result.' });+ if (!blocked.ok || !unaffected.ok) throw new Error('missing tasks');+ blockedSession = blocked.childSessionId;+ h.sqlite!.prepare("UPDATE bot_delegations SET status = 'completed', result_summary = 'fixture finished' WHERE id = ?").run(unaffected.delegationId);+ const { createBotRuntimeRestoreCoordinator } = await import('../../../maker-ipc/botRuntimeRestore');+ const coordinator = createBotRuntimeRestoreCoordinator({+ readDbIdentity: () => ({ userId: 'owner', clientEpoch: 1 }),+ readServices: () => ({ directMessages: { restore: async () => undefined }, delegation: runtime.delegation }),+ log: { warn: vi.fn() },+ });+ // Let parent result delivery succeed while ownership blocks child startup.+ unavailable = false;+ runtime.dispatch.mockClear();+ expect(await coordinator.restoreCurrentOwner()).toBe(false);+ expect(runtime.dispatch.mock.calls.filter(([params]) => params.targetSessionId === 'session-1')).toHaveLength(1);+ expect(await runtime.delegation.stopSessionTask('session-1', blocked.delegationId, 'cancel')).toMatchObject({ ok: true });+ expect(runtime.heldInputs.has(blocked.childSessionId)).toBe(false);+ blockedSession = null;+ expect(await coordinator.restoreCurrentOwner()).toBe(true);+ await runtime.delegation.restore();+ expect(await runtime.delegation.getSessionTask('session-1', blocked.delegationId)).toMatchObject({ ok: true, task: { status: 'cancelled' } });+ expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === blocked.childSessionId)).toBe(false);+ expect(runtime.dispatch.mock.calls.filter(([params]) => params.targetSessionId === 'session-1')).toHaveLength(2);+ } finally { runtime.dispose(); }+ });++ it.each([false, true])('only renotifies an unresolved interaction on resume (applied IM answer: %s)', async applied => {+ await seedPair();+ let decisionApplied = false;+ const runtime = createDelegationRuntime({ taskControl: true,+ appliedOnResume: () => decisionApplied ? ['im-answer'] : [] });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Wait for an IM answer.' });+ if (!task.ok) throw new Error('missing task');+ const request = { kind: 'permission' as const, requestId: 'im-answer', toolName: 'write_file', input: {} };+ await runtime.delegation.handleInteractionStart(task.childSessionId, request);+ expect(await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause')).toMatchObject({ ok: true });+ runtime.dispatch.mockClear();+ decisionApplied = applied;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: true, delivery: applied ? 'interaction' : 'awaiting-interaction' });+ const notifications = runtime.dispatch.mock.calls.filter(([params]) => params.clientId?.includes('bot-delegation-interaction:'));+ expect(notifications).toHaveLength(applied ? 0 : 1);+ const row = h.sqlite!.prepare('SELECT status, pending_interaction_json FROM bot_delegations WHERE id = ?').get(task.delegationId) as { status: string; pending_interaction_json: string | null };+ expect(row.status).toBe(applied ? 'running' : 'waiting');+ if (applied) {+ expect(row.pending_interaction_json).toBeNull();+ // The delayed native callback is harmless after synchronous bookkeeping.+ await runtime.delegation.handleInteractionEnd(task.childSessionId, request);+ expect(runtime.dispatch.mock.calls.filter(([params]) => params.clientId?.includes('bot-delegation-interaction:'))).toHaveLength(0);+ }+ } finally { runtime.dispose(); }+ });++ it('pauses an interaction without resolving it, and accounts for the wait only once', async () => {+ await seedPair();+ const resolveInteraction = vi.fn(() => true);+ const runtime = createDelegationRuntime({ taskControl: true, resolveInteraction });+ try {+ const started = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Write the report after approval.' });+ if (!started.ok) throw new Error('task did not start');+ const request = { kind: 'permission' as const, requestId: 'held-approval', toolName: 'write_file', input: {} };+ const before = await runtime.delegation.getSessionTask('session-1', started.delegationId);+ await runtime.delegation.handleInteractionStart(started.childSessionId, request);+ runtime.advance(10_000);+ expect(await runtime.delegation.stopSessionTask('session-1', started.delegationId, 'pause')).toMatchObject({ ok: true });+ expect(runtime.stopTurn).not.toHaveBeenCalled();+ expect(await runtime.delegation.messageSessionTask('session-1', started.delegationId, { kind: 'approve' }))+ .toMatchObject({ ok: false, errorCode: 'TASK_PAUSED' });+ expect(resolveInteraction).not.toHaveBeenCalled();+ runtime.advance(20_000);+ expect(await runtime.delegation.messageSessionTask('session-1', started.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: true, delivery: 'awaiting-interaction' });+ runtime.advance(5_000);+ expect(await runtime.delegation.messageSessionTask('session-1', started.delegationId, { kind: 'approve' }))+ .toMatchObject({ ok: true, delivery: 'interaction' });+ expect(resolveInteraction).toHaveBeenCalledTimes(1);+ await runtime.delegation.handleInteractionEnd(started.childSessionId, request);+ const after = await runtime.delegation.getSessionTask('session-1', started.delegationId);+ if (!before.ok || !after.ok) throw new Error('missing task');+ expect(after.task.deadline_at).toBe(before.task.deadline_at! + 35_000);+ expect(after.task.pendingInteraction).toBeNull();+ expect(runtime.started.filter((turn) => turn.sessionId === started.childSessionId)).toHaveLength(1);+ } finally { runtime.dispose(); }+ });++ /** Commit the real SQLite update, then lose only its worker acknowledgement. */+ function loseResumeCommitReceipt(readbackUnavailable: boolean) {+ const update = h.db!.update.bind(h.db!);+ return vi.spyOn(h.db!, 'update').mockImplementation(table => {+ const builder = update(table);+ const set = builder.set.bind(builder);+ builder.set = values => {+ const query = set(values);+ if (table === botDelegations && JSON.stringify(values).includes('taskResume')) {+ const returning = query.returning.bind(query);+ query.returning = (fields?: Parameters<typeof returning>[0]) => {+ const result = fields ? returning(fields) : returning();+ result.all();+ if (readbackUnavailable) vi.spyOn(h.db!, 'select').mockImplementationOnce(() => {+ throw new Error('fixture readback unavailable');+ });+ throw new Error('fixture commit acknowledgement lost');+ };+ }+ return query;+ };+ return builder;+ });+ }++ const flushTaskQueue = async () => {+ for (let i = 0; i < 30; i++) await new Promise<void>(resolve => setImmediate(resolve));+ };++ it.each(['retry', 'restart', 'cancel'] as const)('retains an idle resume behind the real queue barrier on DB failure, then handles %s', async recovery => {+ 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: 'Do each action once.' });+ if (!task.ok) throw new Error('missing task');+ await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ await runtime.settleChild(task.childSessionId, 'Stopped before continuing.');+ runtime.advance(1_000);+ h.sqlite!.exec("CREATE TEMP TRIGGER fail_resume_commit BEFORE UPDATE OF permission_snapshot_json ON bot_delegations WHEN json_extract(NEW.permission_snapshot_json, '$.taskPause') IS NULL BEGIN SELECT RAISE(FAIL, 'fixture resume DB unavailable'); END");+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: false, errorCode: 'RESUME_FAILED' });+ await flushTaskQueue();+ expect(runtime.started).toHaveLength(1);+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(true);+ expect(queueSnapshots.get(task.childSessionId)).toHaveLength(1);+ const retainedId = queueSnapshots.get(task.childSessionId)![0].clientId;+ expect(h.sqlite!.prepare('SELECT 1 FROM messages WHERE client_id = ?').get(retainedId)).toBeUndefined();+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { control: { state: 'paused' }, completed_at: null } });+ h.sqlite!.exec('DROP TRIGGER fail_resume_commit');+ if (recovery === 'cancel') {+ expect(await runtime.delegation.stopSessionTask('session-1', task.delegationId)).toMatchObject({ ok: true });+ await flushTaskQueue();+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(1);+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: false });+ expect(queueSnapshots.get(task.childSessionId) ?? []).toHaveLength(0);+ return;+ }+ if (recovery === 'restart') {+ runtime.dispose();+ const restored = createDelegationRuntime({ taskControl: true, queueSnapshots, startTime: 12_000 });+ try {+ await restored.delegation.restore();+ await flushTaskQueue();+ expect(restored.started).toHaveLength(0);+ expect(await restored.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: true });+ await flushTaskQueue();+ expect(restored.started).toHaveLength(1);+ await restored.settleChild(task.childSessionId, 'Restored continuation completed.');+ expect(await restored.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'completed' } });+ } finally { restored.dispose(); }+ return;+ }+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: true });+ await flushTaskQueue();+ expect(runtime.started).toHaveLength(2);+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(false);+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: true });+ await flushTaskQueue();+ expect(runtime.started).toHaveLength(2);+ await runtime.settleChild(task.childSessionId, 'The resumed work is complete.');+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'completed', result: 'The resumed work is complete.' } });+ } finally {+ h.sqlite!.exec('DROP TRIGGER IF EXISTS fail_resume_commit');+ runtime.dispose();+ }+ });++ it('keeps a completion emitted immediately as the resume barrier opens', async () => {+ await seedPair();+ let childId = '';+ let completion: Promise<void> | undefined;+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots: new Map(),+ onNativeStarted: id => {+ if (id === childId) completion = runtime.settleChild(id, 'Immediate resumed completion.');+ },+ });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish without duplication.' });+ if (!task.ok) throw new Error('missing task');+ childId = task.childSessionId;+ await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ await runtime.settleChild(childId, 'Stopped.');+ runtime.advance(1_000);+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: true });+ await flushTaskQueue();+ expect(completion).toBeDefined();+ await completion;+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'completed', result: 'Immediate resumed completion.' } });+ expect(runtime.started.filter(turn => turn.sessionId === childId)).toHaveLength(2);+ } finally { runtime.dispose(); }+ });++ it.each(['readback', 'retry', 'restore', 'restart'] as const)('recovers a committed resume after receipt loss through %s without replaying work', async recovery => {+ await seedPair();+ const queueSnapshots = new Map<string, AgentInputQueuedMessage[]>();+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots });+ let restored: ReturnType<typeof createDelegationRuntime> | undefined;+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Continue 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(1_000);+ const fault = loseResumeCommitReceipt(recovery !== 'readback');+ const result = await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' });+ fault.mockRestore();+ await flushTaskQueue();+ expect(result).toMatchObject({ ok: recovery === 'readback' });+ if (recovery !== 'readback') {+ expect(runtime.started).toHaveLength(1);+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(true);+ expect(queueSnapshots.get(task.childSessionId)).toHaveLength(1);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { control: { state: 'resuming', queue_held: true } } });+ }+ if (recovery === 'retry') {+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: true });+ } else if (recovery === 'restore') {+ await runtime.delegation.restore();+ } else if (recovery === 'restart') {+ runtime.dispose();+ restored = createDelegationRuntime({ taskControl: true, queueSnapshots, startTime: 11_000 });+ await restored.delegation.restore();+ }+ await flushTaskQueue();+ const active = restored ?? runtime;+ expect(active.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(restored ? 1 : 2);+ const dispatchCount = active.dispatch.mock.calls.length;+ expect(await active.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume', text: 'Different input' }))+ .toMatchObject({ ok: false, errorCode: 'RESUME_INPUT_CHANGED' });+ expect(await active.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' })).toMatchObject({ ok: true });+ expect(active.dispatch).toHaveBeenCalledTimes(dispatchCount);+ await active.settleChild(task.childSessionId, 'One completed continuation.');+ expect(await active.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'completed', result: 'One completed continuation.' } });+ const afterCompletion = createDelegationRuntime({ taskControl: true, queueSnapshots, startTime: 12_000 });+ try {+ await afterCompletion.delegation.restore();+ expect(afterCompletion.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(0);+ } finally { afterCompletion.dispose(); }+ } finally { vi.restoreAllMocks(); restored?.dispose(); runtime.dispose(); }+ });++ it('uses native steer and graceful stop without queueing or finishing the task', async () => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true });+ try {+ const started = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish.' });+ if (!started.ok) throw new Error('task did not start');+ expect(await runtime.delegation.messageSessionTask('session-1', started.delegationId,+ { kind: 'message', text: 'Correct the current direction.', mode: 'steer' }))+ .toMatchObject({ ok: true, delivery: 'same-turn', queued: false });+ expect(await runtime.delegation.stopSessionTask('session-1', started.delegationId, 'request-stop'))+ .toMatchObject({ ok: true, control: { state: 'requested', queue_held: false } });+ expect(runtime.stopTurn).toHaveBeenCalledWith({ targetSessionId: started.childSessionId });+ expect(runtime.started).toHaveLength(1);+ expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(await runtime.delegation.getSessionTask('session-1', started.delegationId))+ .toMatchObject({ task: { status: 'running', completed_at: null,+ control: { last_stop_request: { requested_at: 10_000, status: 'requested' }, stop_status: 'unconfirmed' } } });+ const restored = createDelegationRuntime({ taskControl: true });+ try {+ expect(await restored.delegation.getSessionTask('session-1', started.delegationId))+ .toMatchObject({ task: { control: { last_stop_request: { status: 'requested' }, stop_status: 'stopped' } } });+ expect(restored.stopTurn).not.toHaveBeenCalled();+ } finally { restored.dispose(); }+ } finally { runtime.dispose(); }+ });++ it.each([undefined, 'Use the revised requirements.'])('keeps a pre-dispatch pause durable with resume input %s, and cancel prevents resume', async (text) => {+ await seedPair();+ let transientUnavailable = true;+ const runtime = createDelegationRuntime({ taskControl: true, transientUnavailable: () => transientUnavailable });+ try {+ const started = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish when ready.' });+ if (!started.ok) throw new Error('task did not start');+ expect(await runtime.delegation.stopSessionTask('session-1', started.delegationId, 'pause'))+ .toMatchObject({ ok: true, control: { state: 'paused' } });+ transientUnavailable = false;+ // Paused time must not consume the initial dispatch deadline.+ runtime.advance(24 * 60 * 60 * 1_000);+ await runtime.delegation.restore();+ expect(runtime.started).toHaveLength(0);+ expect(await runtime.delegation.messageSessionTask('session-1', started.delegationId, { kind: 'resume', text }))+ .toMatchObject({ ok: true, childSessionId: started.childSessionId });+ expect(runtime.started.map((turn) => turn.sessionId)).toEqual(text+ ? [started.childSessionId, started.childSessionId] : [started.childSessionId]);+ expect(await runtime.delegation.getSessionTask('session-1', started.delegationId)).toMatchObject({ task: { status: 'running' } });+ await runtime.delegation.stopSessionTask('session-1', started.delegationId, 'pause');+ expect(await runtime.delegation.stopSessionTask('session-1', started.delegationId))+ .toMatchObject({ ok: true, control: { state: 'cancelling', stop_status: 'unconfirmed' } });+ expect(await runtime.delegation.messageSessionTask('session-1', started.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: false, errorCode: 'STOP_UNCONFIRMED' });+ await runtime.settleChild(started.childSessionId, 'Interrupted.');+ expect(await runtime.delegation.getSessionTask('session-1', started.delegationId))+ .toMatchObject({ ok: true, task: { status: 'cancelled', control: { stop_status: 'stopped' } } });+ expect(await runtime.delegation.messageSessionTask('session-1', started.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: false, errorCode: 'NOT_PAUSED' });+ } finally { runtime.dispose(); }+ });++ it('preserves cancellation across a late interaction end and host restore', async () => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Wait for approval.' });+ if (!task.ok) throw new Error('missing task');+ const request = { kind: 'permission' as const, requestId: 'approval', toolName: 'write_file', input: {} };+ await runtime.delegation.handleInteractionStart(task.childSessionId, request);+ await runtime.delegation.stopSessionTask('session-1', task.delegationId);+ runtime.advance(1_000);+ await runtime.delegation.handleInteractionEnd(task.childSessionId, request);+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', text: 'must not run' }))+ .toMatchObject({ ok: false, errorCode: 'STOP_UNCONFIRMED' });+ const restored = createDelegationRuntime({ taskControl: true });+ try {+ await restored.delegation.restore();+ expect(await restored.delegation.getSessionTask('session-1', task.delegationId))+ .toMatchObject({ task: { status: 'cancelled', control: { stop_status: 'stopped' } } });+ expect(restored.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(0);+ } finally { restored.dispose(); }+ } finally { runtime.dispose(); }+ });++ it('does not leave a durable hold when graceful stop is unsupported', async () => {+ await seedPair();+ const runtime = createDelegationRuntime({ taskControl: true, stopUnsupported: true });+ try {+ const started = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish.' });+ if (!started.ok) throw new Error('task did not start');+ expect(await runtime.delegation.stopSessionTask('session-1', started.delegationId, 'pause'))+ .toMatchObject({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' });+ expect(runtime.heldInputs.size).toBe(0);+ expect(await runtime.delegation.getSessionTask('session-1', started.delegationId))+ .toMatchObject({ ok: true, task: { status: 'running', control: { queue_held: false } } });+ } finally { runtime.dispose(); }+ });+it('delivers every continued run once without reusing the previous completion receipt', async () => {await seedPair();const runtime = createDelegationRuntime();diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 50f4ecbfb0..714211e02b 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -820,6 +820,10 @@ function botsReopenDelegation(const session = asRecord(p.session, 'session');insertBotSession(db, session);const childSessionId = expectString(p.childSessionId, 'childSessionId');+ if (p.worktreePath != null) {+ db.prepare('UPDATE sessions SET worktree_path = ? WHERE id = ?')+ .run(expectString(p.worktreePath, 'worktreePath'), childSessionId);+ }if (targetBotId) {db.prepare(`INSERT INTO bot_session_links(id, bot_id, session_id, profile_version, role, route_key, created_at, archived_at)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 6a657cae63..fcb3b699b7 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@@ -7,7 +7,7 @@ import {type OrcaTeamServiceDeps,type OrcaWorkerRecordSnapshot,} from '../orcaTeamService.js';-import { rebuildSessionQueueItem } from '../sessionControlService.js';+import { createSessionControlService, rebuildSessionQueueItem } from '../sessionControlService.js';import type {AgentInputCoordinatorDeps,AgentInputHostSendFailureCode,@@ -52,6 +52,25 @@ describe('AgentInputCoordinator Orca priority queue transactions', () => {origin: { kind: 'orca', senderLabel: 'Lead', displayText: text },});+ it('holds even an empty task queue through enqueue, ordinary Resume and restored input', async () => {+ const h = createHarness();+ const sid = 'paused-task';+ h.coordinator.setExecutionPaused(sid, true);+ await h.coordinator.ensureQueueRestored(sid);+ h.coordinator.enqueue(sid, makeItem('first', 'first'), { resumeRestorePausedQueue: true });+ h.coordinator.enqueue(sid, makeItem('second', 'second'));+ h.coordinator.resume(sid);+ await flush();+ expect(h.coordinator.isQueuePaused(sid)).toBe(true);+ expect(h.coordinator.shouldQueueNewTurn(sid)).toBe(true);+ expect(h.sendToAgent).not.toHaveBeenCalled();+ expect(h.coordinator.getQueueControlSnapshot(sid).pendingQueue.map((item) => item.clientId)).toEqual(['first', 'second']);+ h.coordinator.setExecutionPaused(sid, false);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(h.sendToAgent.mock.calls[0]?.[1]).toMatchObject({ content: 'first' });+ });+it('forwards main-stamped device-link provenance from enqueue to send', async () => {const h = createHarness();const sid = 'device-link-lead';@@ -6436,6 +6455,124 @@ describe('AgentInputCoordinator steer transaction', () => {expect(projection.errorRetryText).toBeNull();});+ it.each(['claude-code', 'codex', 'pi'] as const)('holds generic %s steer across pause, preparation and stop', async (agentKind) => {+ const h = createHarness();+ const sid = 'stable-control-steer';+ h.setAgentKind(agentKind);+ h.coordinator.enqueue(sid, makeItem('initial', 'work'));+ await flush();+ const generation = 0;+ let allocatedIds = 0;+ const live = {+ agentKind, capabilities: { sameTurnSteer: { supported: true } },+ isTurnRunning: () => true, getTurnGeneration: () => generation,+ requestGracefulStop: vi.fn(), getTurnControlSnapshot: vi.fn(),+ };+ h.setTurnSessionIdentity(live);+ const service = createSessionControlService({+ sessionExists: async () => true, getLiveSession: () => live,+ getSessionActivitySnapshot: vi.fn(), getSessionRuntimeDetails: vi.fn(), setSessionRuntime: vi.fn(),+ assertExternalInputAllowed: async () => undefined,+ createQueuedMessage: async ({ queuedMessageId, message, callerSessionId }) => makeItem(queuedMessageId, message, {+ origin: { kind: 'session', senderSessionId: callerSessionId, displayText: message },+ }),+ steerQueuedMessage: (id, item, expected) => h.coordinator.steer(id, item, {+ fallbackToTurn: false, expectedTurnSession: expected.session, expectedTurnGeneration: expected.turnGeneration,+ }),+ getQueueSnapshot: vi.fn(), replaceQueuedMessage: vi.fn(), removeQueuedMessage: vi.fn(),+ createId: () => `unexpected-random-ID-${++allocatedIds}`,+ });+ const input = { callerSessionId: 'caller', targetSessionId: sid, message: 'urgent', queuedMessageId: 'stable-ID' };+ h.coordinator.setExecutionPaused(sid, true);+ expect(await service.steerSession(input)).toMatchObject({ ok: false });+ expect(await h.coordinator.steer(sid, makeItem('ui-steer', 'UI'))).toBe(false);+ expect(h.steerToAgent).not.toHaveBeenCalled();+ h.coordinator.setExecutionPaused(sid, false);+ const screen = deferred<{ action: 'allow' }>();+ h.setScreenUserMessage(() => screen.promise);+ const preparing = service.steerSession(input);+ await flush();+ h.coordinator.setExecutionPaused(sid, true);+ screen.resolve({ action: 'allow' });+ expect(await preparing).toMatchObject({ ok: false });+ expect(h.steerToAgent).not.toHaveBeenCalled();+ await h.coordinator.stop(sid);+ expect(h.coordinator.isExecutionPaused(sid)).toBe(true);+ expect(await service.steerSession(input)).toMatchObject({ ok: false });+ expect(h.steerToAgent).not.toHaveBeenCalled();+ h.coordinator.setExecutionPaused(sid, false);+ h.setRunning(true);+ expect(await service.steerSession(input)).toMatchObject({ ok: true });+ expect(h.steerToAgent).toHaveBeenCalledTimes(1);+ });++ it('propagates pause into a steer already preparing inside the Host adapter', async () => {+ const h = createHarness();+ const sid = 'pause-host-steer';+ h.coordinator.enqueue(sid, makeItem('initial', 'work'));+ await flush();+ const preparing = deferred<void>();+ const injected = vi.fn();+ h.steerToAgent.mockImplementation(async (_id, _message, opts) => {+ await preparing.promise;+ opts?.signal?.throwIfAborted();+ injected();+ });+ const pending = h.coordinator.steer(sid, makeItem('steer', 'urgent'), { fallbackToTurn: false });+ await flush();+ expect(h.steerToAgent).toHaveBeenCalledTimes(1);+ h.coordinator.setExecutionPaused(sid, true);+ preparing.resolve();+ expect(await pending).toBe(false);+ expect(injected).not.toHaveBeenCalled();+ expect(h.coordinator.isExecutionPaused(sid)).toBe(true);+ });++ it.each(['claude-code', 'codex', 'pi'] as const)('deduplicates stable %s control IDs across native acceptance and the next turn', async (agentKind) => {+ const h = createHarness();+ const sid = 'stable-control-steer';+ h.setAgentKind(agentKind);+ h.coordinator.enqueue(sid, makeItem('initial', 'work'));+ await flush();+ let generation = 0;+ let allocatedIds = 0;+ const live = {+ agentKind, capabilities: { sameTurnSteer: { supported: true } },+ isTurnRunning: () => true, getTurnGeneration: () => generation,+ requestGracefulStop: vi.fn(), getTurnControlSnapshot: vi.fn(),+ };+ h.setTurnSessionIdentity(live);+ const service = createSessionControlService({+ sessionExists: async () => true, getLiveSession: () => live,+ getSessionActivitySnapshot: vi.fn(), getSessionRuntimeDetails: vi.fn(), setSessionRuntime: vi.fn(),+ assertExternalInputAllowed: async () => undefined,+ createQueuedMessage: async ({ queuedMessageId, message, callerSessionId }) => makeItem(queuedMessageId, message, {+ origin: { kind: 'session', senderSessionId: callerSessionId, displayText: message },+ }),+ steerQueuedMessage: (id, item, expected) => h.coordinator.steer(id, item, {+ fallbackToTurn: false, expectedTurnSession: expected.session, expectedTurnGeneration: expected.turnGeneration,+ }),+ getQueueSnapshot: vi.fn(), replaceQueuedMessage: vi.fn(), removeQueuedMessage: vi.fn(),+ createId: () => `unexpected-random-ID-${++allocatedIds}`,+ });+ const input = { callerSessionId: 'caller', targetSessionId: sid, message: 'urgent', queuedMessageId: 'stable-ID' };+ // Native acceptance succeeds even if its subsequent history write fails.+ mocks.createMessage.mockRejectedValueOnce(new Error('fixture history unavailable'));+ const firstReceipt = await service.steerSession(input);+ const retryReceipt = await service.steerSession(input);+ expect(h.steerToAgent).toHaveBeenCalledTimes(1);+ expect(firstReceipt).toEqual({ ok: true, queuedMessageId: 'stable-ID' });+ expect(retryReceipt).toEqual(firstReceipt);+ h.coordinator.onTurnEvent(sid, 'done');+ await flush();+ generation = 1;+ h.setTurnGeneration(generation);+ h.setRunning(true);+ expect(await service.steerSession(input)).toEqual({ ok: true, queuedMessageId: 'stable-ID' });+ expect(h.steerToAgent).toHaveBeenCalledTimes(1);+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ });+it('deduplicates an accepted steer after persistence and terminal failure', async () => {const h = createHarness();h.setAgentKind('codex');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.tsindex 4b41ef2747..30ff62f42c 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts@@ -308,6 +308,18 @@ describe('session control domain service', () => {).resolves.toMatchObject({ ok: false, errorCode: 'NO_ACTIVE_TURN' });});+ it('passes a stable host steer ID to the coordinator without allocating a replacement', async () => {+ const { deps, service } = setup();+ const params = { callerSessionId: 'caller', targetSessionId: 'target', message: 'urgent', queuedMessageId: 'stable-steer' };+ expect(await service.steerSession(params)).toEqual({ ok: true, queuedMessageId: 'stable-steer' });+ expect(await service.steerSession(params)).toEqual({ ok: true, queuedMessageId: 'stable-steer' });+ expect(deps.createId).not.toHaveBeenCalled();+ expect(deps.createQueuedMessage).toHaveBeenNthCalledWith(1, params);+ expect(deps.createQueuedMessage).toHaveBeenNthCalledWith(2, params);+ expect(deps.steerQueuedMessage).toHaveBeenLastCalledWith('target',+ expect.objectContaining({ clientId: 'stable-steer' }), expect.any(Object));+ });+it('rejects when the original turn changes while the control message is being built', async () => {const generationRace = setup();const generationGate = deferred<AgentInputQueuedMessage>();diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex d140a0b340..0b9fc92e44 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -1434,7 +1434,8 @@ export class AgentInputCoordinator {* 等不来、存活探测又看到项还在,run 会永久挂 running(PR #972 review)。*/isQueuePaused(sessionId: string): boolean {- return this.getState(sessionId).queuePaused;+ const state = this.getState(sessionId);+ return state.queuePaused || state.queueInteractionLocks.includes('execution-pause');}/**@@ -2125,8 +2126,13 @@ export class AgentInputCoordinator {try {const referenceContexts = await this.resolveReferenceContexts(item);- if (!matchesExpectedTurn()) {- const latest = this.getState(sessionId);+ // A pause/Stop can arrive while references are being prepared. Recheck+ // before crossing the provider boundary, including direct UI/IM callers.+ const current = this.getState(sessionId);+ if (!matchesExpectedTurn() || current.queueInteractionLocks.length > 0+ || current.queueAbortPending || inputBoundarySignal.aborted || steerAbort.signal.aborted+ || !this.isCurrentSteerRequest(current, item.clientId, steerGeneration, steerRequestToken)) {+ const latest = current;if (this.clearSteeringMarker(latest, item.clientId, {generation: steerGeneration,@@ -3174,6 +3180,18 @@ export class AgentInputCoordinator {return this.getProjection(sessionId);}+ isExecutionPaused(sessionId: string): boolean {+ return this.getState(sessionId).queueInteractionLocks.includes('execution-pause');+ }++ /** A durable owner-controlled pause survives ordinary queue Resume/Stop. */+ setExecutionPaused(sessionId: string, paused: boolean): void {+ this.setInteractionLock(sessionId, 'execution-pause', paused, { preserveOnStop: true });+ // Propagate the hold through async normalization/authorization in the Host+ // adapter and harness, including steers already admitted before the pause.+ if (paused) this.abortSteerTransactions(sessionId);+ }+setInteractionLock(sessionId: string,lockId: string,diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex cc883d6887..07ea4a4d6f 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -1,6 +1,6 @@import { existsSync, statSync } from 'node:fs';import path from 'node:path';-import { randomUUID } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import { app } from 'electron';import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';@@ -11,6 +11,7 @@ import type { BotsFinishDelegationResult } from '../localDb/client/tx/types.js';import { visibleMessageTextForConversationSearch } from '../localDb/conversationSearch.pure.js';import { createBotCanonicalSession } from '../localDb/ipc/bots.js';import { createMessage } from '../localDb/ipc/messages.js';+import { setWorktreePathInDb } from '../localDb/ipc/sessions.js';import { sessionCreateToRow } from '../localDb/mapper.js';import {botDelegations,@@ -44,6 +45,7 @@ import type {} from '../../shared/botCollaboration.js';import { BOT_DELEGATION_CLIENT_ID } from '../../shared/botCollaboration.js';import { ensureBotWorkspaceDir } from './botProfileFolder.js';+import type { SessionQueuedMessageControlResult, SessionSteerResult, SessionStopResult } from './sessionControlService.js';import { ownerScopedUserDataPath } from '../appSessionState.js';const ACTIVE_DELEGATION_STATUSES = ['queued', 'running', 'waiting'] as const;@@ -80,8 +82,35 @@ export interface BotDelegationServiceDeps {persistedContent?: string;clientId?: string;onAccepted?: () => void | Promise<void>;+ dispatcherSessionId?: string;}) => Promise<DispatchResult>;abortSession: (sessionId: string) => Promise<void>;+ taskControl?: {+ steer(params: { callerSessionId: string; targetSessionId: string; message: string; queuedMessageId?: string }): Promise<SessionSteerResult>;+ stop(params: { targetSessionId: string }): Promise<SessionStopResult>;+ /** Includes native pending interactions and in-flight sends, not just visible streaming. */+ isActive(sessionId: string): boolean;+ /** IDs of decisions synchronously applied while releasing the pause. */+ holdInput(sessionId: string, held: boolean): readonly string[] | void;+ waitForInputBoundary(sessionId: string): Promise<void>;+ preparePause(sessionId: string): Promise<void>;+ restoreInput(sessionId: string): Promise<void>;+ flushInput(sessionId: string): Promise<void>;+ resumeInput(sessionId: string): Promise<void>;+ };+ discardUnusedWorktree?: (sessionId: string) => Promise<void>;+ getWorktree?: (sessionId: string) => { path: string } | null;+ reconcileWorktree?: (sessionId: string) => Promise<void>;+ withTransferredWorktree?: <T extends { reopened: boolean }>(+ previousSessionId: string, sessionId: string, worktreePath: string, commit: () => Promise<T>,+ identity: { delegationId: string; requestingBotId: string },+ ) => Promise<T>;+ prepareWorktree?: (workingDir: string) => Promise<{ ok: true; sessionId: string; workingDir: string } | { ok: false; message: string }>;+ taskQueue?: {+ inspect(sessionId: string, callerSessionId: string): Promise<Array<{ queuedMessageId: string; consuming: boolean; message: string }>>;+ update(params: { callerSessionId: string; targetSessionId: string; queuedMessageId: string; message: string }): Promise<SessionQueuedMessageControlResult>;+ cancel(params: { callerSessionId: string; targetSessionId: string; queuedMessageId: string }): Promise<SessionQueuedMessageControlResult>;+ };closeSession?: (sessionId: string) => Promise<void>;broadcastSessionCreated?: (sessionId: string) => void;persistTimelineMessage?: (params: {@@ -129,6 +158,7 @@ export interface SessionTaskInput {* 工作目录,必须是已存在的绝对路径;缺省用发起伙伴的 Home workspace。*/workingDir?: string;+ useWorktree?: boolean;timeoutMs?: number;}@@ -140,7 +170,10 @@ export type SessionTaskMessage =| { kind: 'approve' }| { kind: 'deny'; reason?: string }| { kind: 'answer'; answers: Record<string, string> }- | { kind: 'message'; text: string; idempotencyKey?: string };+ | { kind: 'message'; text: string; idempotencyKey?: string; mode?: 'queue' | 'steer' }+ | { kind: 'resume'; text?: string }+ | { kind: 'edit'; queuedMessageId: string; text: string }+ | { kind: 'withdraw'; queuedMessageId: string };export type BotDelegationResult<T extends object = object> =({ ok: true } & T)@@ -157,6 +190,20 @@ function parseRecord(value: string | null | undefined): Record<string, unknown>}}+/** Mutable execution hold lives beside the frozen plan, without changing its authority fields. */+interface SessionTaskPause {+ token: string;+ pausedAt: number;+ previousStatus: 'queued' | 'running' | 'waiting';+ interactionOnly?: boolean;+}+function readTaskPause(row: Pick<DelegationRow, 'permissionSnapshotJson'>): SessionTaskPause | null {+ const value = parseRecord(row.permissionSnapshotJson).taskPause as Partial<SessionTaskPause> | undefined;+ return value && typeof value.token === 'string' && typeof value.pausedAt === 'number'+ && ['queued', 'running', 'waiting'].includes(value.previousStatus ?? '')+ ? value as SessionTaskPause : null;+}+function parseStringArray(value: string | null | undefined): string[] {try {const parsed = JSON.parse(value ?? '[]') as unknown;@@ -213,6 +260,7 @@ function extendDeadlineSnapshot(permissionSnapshotJson: string, pausedMs: numberconst plan = parseBotDelegationPlanSnapshot(permissionSnapshotJson);if (!plan || pausedMs <= 0) return null;return JSON.stringify({+ ...parseRecord(permissionSnapshotJson),...plan,limits: {...plan.limits,@@ -268,6 +316,24 @@ function normalizeDelegationReferences(}export function createBotDelegationService(deps: BotDelegationServiceDeps) {+ const heldSessionIds = new Set<string>();+ const holdTaskInput = (sessionId: string, held: boolean) => {+ if (held) heldSessionIds.add(sessionId); else heldSessionIds.delete(sessionId);+ const applied = deps.taskControl?.holdInput(sessionId, held);+ if (applied?.length) {+ for (const pending of pendingInteractions.values()) {+ if (applied.includes(pending.requestId)) pending.decisionApplied = true;+ }+ }+ };+ const taskOperations = new Map<string, Promise<unknown>>();+ const withTaskOperation = async <T>(id: string, run: () => Promise<T>): Promise<T> => {+ const previous = taskOperations.get(id) ?? Promise.resolve();+ const operation = previous.catch(() => undefined).then(run);+ taskOperations.set(id, operation);+ try { return await operation; }+ finally { if (taskOperations.get(id) === operation) taskOperations.delete(id); }+ };const timers = new Map<string, ReturnType<typeof setTimeout>>();const retryTimers = new Map<string, ReturnType<typeof setTimeout>>();const completionRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();@@ -279,6 +345,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {* summary and paused status are persisted on the delegation row. */const pendingInteractions = new Map<string, BotDelegationPendingInteraction & {request: InteractionRequest;+ decisionApplied?: boolean;}>();const now = deps.now ?? Date.now;const createId = deps.createId ?? randomUUID;@@ -791,6 +858,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {updated.childSessionId,params.abortChild === true,);+ holdTaskInput(updated.childSessionId, false);}}return updated;@@ -830,12 +898,18 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.from(botDelegations).where(eq(botDelegations.id, delegationId)).limit(1);- if (!row) return;+ if (!row || readTaskPause(row) || parseRecord(row.permissionSnapshotJson).taskCancelRequested === true) return;// 对方停在等人拍板的地方不算超时:等人不是干活慢。答完再按原截止时间续算。if (row.status === 'waiting' || pendingInteractions.has(delegationId)) {scheduleTimeout(delegationId, now() + WAITING_TIMEOUT_GRACE_MS);return;}+ // A fired callback may have waited behind a resume that extended the deadline.+ const deadline = readDeadline(row.permissionSnapshotJson);+ if (deadline !== null && deadline > now()) {+ scheduleTimeout(delegationId, deadline);+ return;+ }const lastError = 'TIMEOUT: 到了约定时间后台任务还没有交回结果';const changed = await updateTerminal({delegationId,@@ -857,10 +931,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {clearTimer(delegationId);const delay = deadlineAt - now();if (delay <= 0) {- void timeoutDelegation(delegationId);+ void withTaskOperation(delegationId, () => timeoutDelegation(delegationId));return;}- const timer = setTimeout(() => void timeoutDelegation(delegationId), delay);+ const timer = setTimeout(() => void withTaskOperation(delegationId, () => timeoutDelegation(delegationId)), delay);timer.unref?.();timers.set(delegationId, timer);};@@ -934,11 +1008,15 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {pending: BotDelegationPendingInteraction & { request: InteractionRequest },attempt = 0,): Promise<void> => {- if (pendingInteractions.get(row.id)?.requestId !== pending.requestId) return;+ const stillPending = () => pendingInteractions.get(row.id)?.requestId === pending.requestId+ && !pendingInteractions.get(row.id)?.decisionApplied;+ if (!stillPending()+ || (row.childSessionId && heldSessionIds.has(row.childSessionId))) return;const requesterSessionId = await requesterLiveSessionId(row.requestingBotId,row.parentSessionId,);+ if (!stillPending() || (row.childSessionId && heldSessionIds.has(row.childSessionId))) return;const message = [`${UI_ACTION_TRIGGER_PREFIX}[任务需要你处理] task_id: ${row.id}`,`类型: ${pending.request.kind}`,@@ -967,7 +1045,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {interactionRetryTimers.set(row.id, timer);};- const handleInteractionStart = async (+ const handleInteractionStartUnserialized = async (childSessionId: string,request: InteractionRequest,): Promise<void> => {@@ -1018,10 +1096,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {status: 'waiting',pendingInteraction: pendingInteractionView(pending),});- await notifyRequesterOfInteraction(row, pending);+ if (!readTaskPause(row)) await notifyRequesterOfInteraction(row, pending);};- const handleInteractionEnd = async (+ const handleInteractionEndUnserialized = async (childSessionId: string,request: InteractionRequest,): Promise<void> => {@@ -1035,6 +1113,13 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (!row) return;const pending = pendingInteractions.get(row.id);if (!pending || pending.requestId !== request.requestId) return;+ if (readTaskPause(row)) {+ pendingInteractions.delete(row.id);+ clearInteractionRetryTimer(row.id);+ await db.update(botDelegations).set({ pendingInteractionJson: null })+ .where(eq(botDelegations.id, row.id));+ return;+ }const resumedAt = now();const extendedSnapshot = extendDeadlineSnapshot(row.permissionSnapshotJson,@@ -1064,6 +1149,16 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (deadlineAt !== null) scheduleTimeout(row.id, deadlineAt);};+ const withChildOperation = async (childSessionId: string, run: () => Promise<void>) => {+ const [row] = await getDbClient().drizzle.select({ id: botDelegations.id }).from(botDelegations)+ .where(eq(botDelegations.childSessionId, childSessionId)).limit(1);+ if (row) await withTaskOperation(row.id, run);+ };+ const handleInteractionStart = (id: string, request: InteractionRequest) =>+ withChildOperation(id, () => handleInteractionStartUnserialized(id, request));+ const handleInteractionEnd = (id: string, request: InteractionRequest) =>+ withChildOperation(id, () => handleInteractionEndUnserialized(id, request));+const buildDelegationPrompt = (row: {id: string;objective: string;@@ -1097,6 +1192,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (!row.childSessionId) {return { ok: false, errorCode: 'CHILD_SESSION_MISSING', message: '后台任务不存在' };}+ try { await deps.reconcileWorktree?.(row.childSessionId); }+ catch { return { ok: false, errorCode: 'WORKTREE_TRANSFER_PENDING', message: 'Task worktree ownership is awaiting reconciliation' }; }const db = getDbClient().drizzle;const liveRequesterSessionId = await requesterLiveSessionId(row.requestingBotId,@@ -1131,7 +1228,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const delay = Math.min(MAX_RETRY_DELAY_MS, 1_000 * 2 ** Math.min(attempt, 6));const timer = setTimeout(() => {retryTimers.delete(delegationId);- void attemptDispatch(delegationId, attempt + 1, isCreationPermissionCurrent);+ void withTaskOperation(delegationId, () => attemptDispatch(delegationId, attempt + 1, isCreationPermissionCurrent));}, delay);timer.unref?.();retryTimers.set(delegationId, timer);@@ -1164,6 +1261,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {delegationId: string,attempt = 0,isCreationPermissionCurrent?: () => boolean,+ resumingPause = false,): Promise<{ok: boolean;status: 'queued' | 'running' | 'failed';@@ -1178,13 +1276,18 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (!row || !row.childSessionId || row.status !== 'queued') {return { ok: true, status: row?.status === 'running' ? 'running' : 'queued' };}+ if ((readTaskPause(row) || parseRecord(row.permissionSnapshotJson).taskCancelRequested === true) && !resumingPause) return { ok: true, status: 'queued' };const deadlineAt = readDeadline(row.permissionSnapshotJson);- if (deadlineAt !== null && deadlineAt <= now()) {+ if (!resumingPause && deadlineAt !== null && deadlineAt <= now()) {await timeoutDelegation(delegationId);return { ok: false, status: 'failed' };}const validation = await validateDispatchPlan(row);if (!validation.ok) {+ if (validation.errorCode === 'WORKTREE_TRANSFER_PENDING') {+ scheduleDispatchRetry(row.id, attempt, isCreationPermissionCurrent);+ return { ok: false, status: 'queued', error: validation };+ }await failDelegationDispatch(row, `${validation.errorCode}: ${validation.message}`);return { ok: false, status: 'failed' };}@@ -1282,7 +1385,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {// 重启前停在 waiting 的:保留持久等待摘要与暂停状态,先恢复子任务;只有新的// turn 真正被接受后才切回 running。旧 resolver 随进程消失,子任务会从历史继续// 并在仍需决定时重新发出一条新的 interaction request。- if (!row || (row.status !== 'running' && row.status !== 'waiting')) return;+ if (!row || readTaskPause(row) || parseRecord(row.permissionSnapshotJson).taskCancelRequested === true || (row.status !== 'running' && row.status !== 'waiting')) return;let effectiveSnapshot = row.permissionSnapshotJson;if (row.status === 'waiting') {effectiveSnapshot = extendDeadlineSnapshot(@@ -1313,6 +1416,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (changed) await deliverCompletion({ ...row, status: 'failed', lastError });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,@@ -1338,11 +1449,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (child.activeTurnStartedAt !== null&& child.lastTurnEndedAt !== null- && child.lastTurnEndedAt >= child.activeTurnStartedAt+ && child.lastTurnEndedAt >= Math.max(child.activeTurnStartedAt, typeof resumedAt === 'number' ? resumedAt : 0)) {const resultText = await readLatestAssistantText(row.childSessionId);if (resultText) {- await settleSession({+ await settleSessionUnserialized({childSessionId: row.childSessionId,outcome: 'done',resultText,@@ -1361,6 +1472,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const validation = await validateDispatchPlan(row);if (!validation.ok) {+ if (validation.errorCode === 'WORKTREE_TRANSFER_PENDING') {+ scheduleResumeRetry(row.id, attempt);+ return;+ }const lastError = `${validation.errorCode}: ${validation.message}`;const changed = await updateTerminal({delegationId: row.id,@@ -1446,13 +1561,18 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {await failDelegationDispatch(row, `${verdict.errorCode}: ${verdict.message}`);return;}+ scheduleResumeRetry(row.id, attempt);+ }++ function scheduleResumeRetry(delegationId: string, attempt: number): void {+ clearRetryTimer(delegationId);const delay = Math.min(MAX_RETRY_DELAY_MS, 1_000 * 2 ** Math.min(attempt, 6));const timer = setTimeout(() => {- retryTimers.delete(row.id);- void resumeRunningDelegation(row.id, attempt + 1);+ retryTimers.delete(delegationId);+ void withTaskOperation(delegationId, () => resumeRunningDelegation(delegationId, attempt + 1));}, delay);timer.unref?.();- retryTimers.set(row.id, timer);+ retryTimers.set(delegationId, timer);}/**@@ -1504,6 +1624,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {objective: string;contextRefs: string[];plan: Omit<BotDelegationPlanSnapshot, 'permission'>;+ useWorktree?: boolean;session: {workingDir: string;model: string;@@ -1512,6 +1633,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {providerId?: string | null;agentKind: 'cc' | 'codex' | 'pi';title: string;+ workspaceKind?: 'project' | 'dialogue';source: 'desktop';};}): Promise<BotDelegationResult<{@@ -1521,14 +1643,24 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {deadlineAt: number;}>> => {const delegationId = createId();- const childSessionId = resolveBusinessSessionId(undefined);+ let childSessionId = resolveBusinessSessionId(undefined);+ if (input.useWorktree) {+ if (!deps.prepareWorktree) return { ok: false, errorCode: 'WORKTREE_UNAVAILABLE', message: 'Task worktree creation is unavailable' };+ const prepared = await deps.prepareWorktree(input.session.workingDir);+ if (!prepared.ok) return { ok: false, errorCode: 'WORKTREE_UNAVAILABLE', message: prepared.message };+ childSessionId = prepared.sessionId;+ input.session = { ...input.session, workingDir: prepared.workingDir, workspaceKind: 'project' };+ }await ensureProjectGitInitialized({workingDir: input.session.workingDir,- workspaceKind: 'dialogue',+ workspaceKind: input.session.workspaceKind ?? 'dialogue',remoteHostId: null,sessionId: childSessionId,autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,source: 'bot-delegation',+ }).catch(async error => {+ if (input.useWorktree) await deps.discardUnusedWorktree?.(childSessionId);+ throw error;});// Read stable authority after asynchronous preparation, with no await before// submitting creation. Both persisted records must use this same snapshot.@@ -1536,6 +1668,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {? deps.readCallerPermission(input.callerSessionId): input.caller.permissionMode;if (callerPermission === null) {+ if (input.useWorktree) await deps.discardUnusedWorktree?.(childSessionId);return { ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE', message: '伙伴权限正在切换或任务正在关闭,请稍后重试' };}const permissionMode = permissionModeOrAsk(typeof callerPermission === 'string' ? callerPermission : callerPermission.mode);@@ -1562,7 +1695,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {...sessionCreateToRow(childSessionId,{- workspaceKind: 'dialogue',+ workspaceKind: input.session.workspaceKind ?? 'dialogue',workingDir: input.session.workingDir,model: input.session.model,// 后台任务沿用发起伙伴当前任务的模型、来源和执行档位。@@ -1616,6 +1749,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {createdAt,},});+ // The worktree store and workingDir already own the binding. A failed+ // display snapshot must not strand the committed task before dispatch.+ if (input.useWorktree) await setWorktreePathInDb(childSessionId, input.session.workingDir);// The worker transaction yields: a permission switch may complete while// creation is pending. Never publish or start the stale Full Access child.if (!isCreationPermissionCurrent()) {@@ -1632,6 +1768,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {status: 'queued',});} catch (error) {+ if (input.useWorktree) await deps.discardUnusedWorktree?.(childSessionId);// The Profile workspace is durable and shared across the Bot's Sessions.// A failed child creation never owns it and must not compensate by deleting it.if (error instanceof Error && error.message === 'BOT_DELEGATION_CONCURRENCY_LIMIT') {@@ -1677,7 +1814,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}scheduleTimeout(delegationId, plan.limits.deadlineAt);- const dispatchResult = await attemptDispatch(delegationId, 0, isCreationPermissionCurrent);+ const dispatchResult = await withTaskOperation(delegationId, () => attemptDispatch(delegationId, 0, isCreationPermissionCurrent));return {ok: true,delegationId,@@ -1773,8 +1910,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {objective,contextRefs: contextRefs.refs,plan,+ useWorktree: input.useWorktree,session: {workingDir,+ workspaceKind: input.workingDir?.trim() ? 'project' : 'dialogue',model: callerRuntime.model,...(callerRuntime.effort ? { effort: callerRuntime.effort } : {}),...(callerRuntime.fastMode !== null && callerRuntime.fastMode !== undefined@@ -1859,25 +1998,41 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.sort((a, b) => b.depth - a.depth);let rootChanged = false;for (const row of affected) {- const changed = await updateTerminal({- delegationId: row.id,- status: 'cancelled',- lastError: reason,- abortChild: !(rootAlreadyAborted && row.id === currentRoot.id),- });- if (changed && !deliverRoot) {- // Lifecycle shutdown already owns the user-visible explanation. Mark- // its cancellation handled so restore cannot wake a paused/archived Bot.- await db- .update(botDelegations)- .set({ completionDeliveredAt: now(), updatedAt: now() })- .where(and(- eq(botDelegations.id, row.id),- eq(botDelegations.status, 'cancelled'),- isNull(botDelegations.completionDeliveredAt),- ));- }- rootChanged ||= row.id === currentRoot.id && changed !== null;+ const cancelRow = async () => {+ // Native abort may await its terminal callback. Keep that callback from+ // waiting on the task operation that is itself awaiting this abort.+ const wasHeld = !!row.childSessionId && heldSessionIds.has(row.childSessionId);+ if (row.childSessionId) holdTaskInput(row.childSessionId, true);+ let changed: Awaited<ReturnType<typeof updateTerminal>>;+ try {+ changed = await updateTerminal({+ delegationId: row.id,+ status: 'cancelled',+ lastError: reason,+ abortChild: !(rootAlreadyAborted && row.id === currentRoot.id),+ });+ } catch (error) {+ if (row.childSessionId) holdTaskInput(row.childSessionId, wasHeld);+ throw error;+ }+ if (row.childSessionId) holdTaskInput(row.childSessionId, false);+ if (changed && !deliverRoot) {+ // Lifecycle shutdown already owns the user-visible explanation. Mark+ // its cancellation handled so restore cannot wake a paused/archived Bot.+ await db+ .update(botDelegations)+ .set({ completionDeliveredAt: now(), updatedAt: now() })+ .where(and(+ eq(botDelegations.id, row.id),+ eq(botDelegations.status, 'cancelled'),+ isNull(botDelegations.completionDeliveredAt),+ ));+ }+ rootChanged ||= row.id === currentRoot.id && changed !== null;+ };+ // Callers own the root lock; descendants use their own input boundary.+ if (row.id === currentRoot.id) await cancelRow();+ else await withTaskOperation(row.id, cancelRow);}if (deliverRoot && rootChanged) {await deliverCompletion({@@ -1906,7 +2061,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {);let cancelled = 0;for (const root of roots) {- if (await cancelDelegationTree(root, reason, false)) cancelled += 1;+ if (await withTaskOperation(root.id, () => cancelDelegationTree(root, reason, false))) cancelled += 1;}return cancelled;};@@ -1931,7 +2086,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.orderBy(desc(botDelegations.depth), desc(botDelegations.createdAt));let cancelled = 0;for (const row of rows) {- if (await cancelDelegationTree(row, reason, false)) cancelled += 1;+ if (await withTaskOperation(row.id, () => cancelDelegationTree(row, reason, false))) cancelled += 1;}return cancelled;};@@ -1939,7 +2094,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const cancelDelegation = async (callerSessionId: string,delegationId: string,- ): Promise<BotDelegationResult<{ delegationId: string; childSessionId: string | null }>> => {+ ): Promise<BotDelegationResult<{ delegationId: string; childSessionId: string | null; control?: { state: string; queue_held: boolean; stop_status: string } }>> => {const caller = await resolveCaller(callerSessionId);if (!caller) {return { ok: false, errorCode: 'NOT_A_BOT_SESSION', message: '当前任务不属于任何伙伴' };@@ -1964,6 +2119,17 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}if (row.childSessionId) {+ if (deps.taskControl) {+ // Commit intent before changing the input/timer boundary. A failed write+ // must leave the running (or already paused) task exactly as it was.+ await getDbClient().drizzle.update(botDelegations).set({+ permissionSnapshotJson: JSON.stringify({ ...parseRecord(row.permissionSnapshotJson), taskCancelRequested: true }),+ }).where(eq(botDelegations.id, row.id));+ holdTaskInput(row.childSessionId, true);+ clearTimer(row.id);+ clearRetryTimer(row.id);+ await deps.taskControl.waitForInputBoundary(row.childSessionId);+ }try {// A successful stop response means the active process has actually// accepted cancellation, not merely that the card changed color.@@ -1981,6 +2147,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}}+ if (row.childSessionId && 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.',@@ -1990,7 +2160,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (!changed) {return { ok: false, errorCode: 'ALREADY_TERMINAL', message: '后台任务已由另一操作结束' };}- return { ok: true, delegationId, childSessionId: row.childSessionId };+ return { ok: true, delegationId, childSessionId: row.childSessionId,+ control: { state: 'terminal', queue_held: false, stop_status: deps.taskControl ? 'stopped' : 'unknown' } };};/**@@ -2014,7 +2185,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {delegationId: string,text: string,idempotencyToken?: string,- ): Promise<BotDelegationInterjectResult> => {+ ): Promise<BotDelegationInterjectResult & { queuedMessageId?: string }> => {const trimmed = text.trim();if (!trimmed) {return { ok: false, errorCode: 'INVALID_ARGS', message: '消息内容不能为空' };@@ -2069,6 +2240,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const requesterName = await requesterDisplayName(caller.botId);const dispatched = await deps.dispatch({targetSessionId: row.childSessionId,+ dispatcherSessionId: callerSessionId,message: [`[来自 ${requesterName} 的补充]`, trimmed].join('\n\n'),persistedContent: [`[来自 ${requesterName} 的补充]`, trimmed].join('\n\n'),clientId: BOT_DELEGATION_CLIENT_ID.interjection(delegationId, token),@@ -2108,6 +2280,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {delegationId,childSessionId: row.childSessionId,queued: dispatched.wakeKind === 'queued',+ queuedMessageId: BOT_DELEGATION_CLIENT_ID.interjection(delegationId, token),};};@@ -2137,6 +2310,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {message: `继续说明超过 ${MAX_INTERJECTION_CHARS} 字,请新建后台任务`,};}+ if (row.childSessionId && deps.taskControl?.isActive(row.childSessionId)) {+ return { ok: false, errorCode: 'STOP_UNCONFIRMED', message: 'Previous execution is still active; continuation is not safe yet' };+ }const oldPlan = parseBotDelegationPlanSnapshot(row.permissionSnapshotJson);if (!oldPlan || !row.childSessionId) {return {@@ -2150,6 +2326,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.select({title: sessions.title,workingDir: sessions.workingDir,+ worktreePath: sessions.worktreePath,workspaceKind: sessions.workspaceKind,model: sessions.model,effort: sessions.effort,@@ -2176,6 +2353,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}+ await deps.reconcileWorktree?.(row.childSessionId);+ const worktreePath = deps.getWorktree?.(row.childSessionId)?.path ?? oldChild.worktreePath;const reopenedAt = now();const deadlineAt = reopenedAt + Math.min(MAX_TIMEOUT_MS, oldPlan.limits.timeoutMs);const nextPlan: BotDelegationPlanSnapshot = {@@ -2196,13 +2375,13 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {await completionInFlight.get(row.id)?.catch(() => undefined);await ensureProjectGitInitialized({workingDir: oldChild.workingDir,- workspaceKind: 'dialogue',+ workspaceKind: oldChild.workspaceKind ?? 'dialogue',remoteHostId: null,sessionId: childSessionId,autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,source: 'bot-delegation',});- const reopened = await getDbClient().tx('bots.reopenDelegation', {+ const commitReopen = () => getDbClient().tx('bots.reopenDelegation', {maxActiveChildren,delegationId: row.id,requestingBotId: callerBotId,@@ -2232,7 +2411,15 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {updatedAt: reopenedAt,},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();if (!reopened.reopened) {await deliverCompletion({...row,@@ -2310,6 +2497,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {childSessionId: string | null;resumed: boolean;queued?: boolean;+ queuedMessageId?: string;}>> => {const caller = await resolveCaller(callerSessionId);if (!caller) {@@ -2328,6 +2516,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.limit(1);if (!row) return { ok: false, errorCode: 'NOT_FOUND', message: '后台任务不存在' };+ if (input.kind === 'resume') return { ok: false, errorCode: 'NOT_PAUSED', message: 'Task is not paused' };const pending = pendingInteractions.get(delegationId);if (pending) {let decision: InteractionDecision | null = null;@@ -2354,7 +2543,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}if (!deps.resolveInteraction?.(pending.requestId, decision)) {- await handleInteractionEnd(row.childSessionId ?? '', pending.request);+ await handleInteractionEndUnserialized(row.childSessionId ?? '', pending.request);return {ok: false,errorCode: 'INTERACTION_STALE',@@ -2401,6 +2590,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {childSessionId: result.childSessionId,resumed: false,queued: result.queued,+ queuedMessageId: result.queuedMessageId,};};@@ -2429,23 +2619,62 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {: { ok: false as const, errorCode: 'NOT_FOUND', message: '后台任务不存在' };};- const getSessionTask = async (callerSessionId: string, taskId: string) => {+ const getSessionTask = (callerSessionId: string, taskId: string, queuedMessageId?: string) => withTaskOperation(taskId, async () => {const found = await findOwnedSessionTask(callerSessionId, taskId);if (!found.ok) return found;- const row = found.row;+ let row = found.row;+ if (isActiveDelegation(row.status as DelegationStatus) && parseRecord(row.permissionSnapshotJson).taskCancelRequested === true+ && row.childSessionId && deps.taskControl && !deps.taskControl.isActive(row.childSessionId)) {+ await cancelDelegationTree(row, 'Cancelled by the requesting Bot.', true, true);+ const refreshed = await findOwnedSessionTask(callerSessionId, taskId);+ if (!refreshed.ok) return refreshed;+ row = refreshed.row;+ }const [child] = row.childSessionId? await getDbClient().drizzle- .select({ title: sessions.title })+ .select({ title: sessions.title, workingDir: sessions.workingDir, workspaceKind: sessions.workspaceKind }).from(sessions).where(eq(sessions.id, row.childSessionId)).limit(1): [];+ let queue: Awaited<ReturnType<NonNullable<BotDelegationServiceDeps['taskQueue']>['inspect']>> | null = null;+ let queueError: 'QUEUE_UNAVAILABLE' | undefined;+ if (row.childSessionId && deps.taskQueue) {+ try {+ queue = await deps.taskQueue.inspect(row.childSessionId, callerSessionId);+ } catch {+ // Queue restoration is diagnostic; it must not hide a task's result.+ queueError = 'QUEUE_UNAVAILABLE';+ }+ }+ let messageReceipt: { queued_message_id: string; state: string } | undefined;+ if (queuedMessageId && row.childSessionId) {+ const queued = queue?.find(item => item.queuedMessageId === queuedMessageId);+ let state = queued ? (queued.consuming ? 'consuming' : 'queued') : queue === null ? 'unavailable' : 'not-found';+ if (!queued) {+ try {+ const [sent] = await getDbClient().drizzle.select({ agentMeta: messages.agentMeta }).from(messages)+ .where(and(eq(messages.sessionId, row.childSessionId), eq(messages.clientId, queuedMessageId), isNull(messages.rewindAt))).limit(1);+ const origin = parseRecord(sent?.agentMeta).origin as { kind?: string; senderSessionId?: string } | undefined;+ if (origin?.kind === 'session' && origin.senderSessionId === callerSessionId) state = 'dispatched';+ } catch {+ state = 'unavailable';+ }+ }+ messageReceipt = { queued_message_id: queuedMessageId, state };+ }return {ok: true as const,task: {task_id: row.id,session_id: row.childSessionId,status: sessionTaskViewStatus(row),+ control: taskControlView(row),+ working_dir: child?.workingDir ?? null,+ workspace_kind: child?.workspaceKind ?? null,+ queue,+ queue_error: queueError,+ message_receipt: messageReceipt,title: child?.title || row.objective.trim().split('\n')[0]?.slice(0, 120) || 'Background task',objective: row.objective,created_at: row.createdAt,@@ -2460,25 +2689,290 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {artifacts: parseArtifacts(row.outputArtifactsJson),},};+ });++ const taskControlView = (row: DelegationRow) => {+ const pause = isActiveDelegation(row.status as DelegationStatus) ? readTaskPause(row) : null;+ const cancelling = isActiveDelegation(row.status as DelegationStatus) && parseRecord(row.permissionSnapshotJson).taskCancelRequested === true;+ const resuming = !pause && isActiveDelegation(row.status as DelegationStatus)+ && !!row.childSessionId && heldSessionIds.has(row.childSessionId)+ && !!parseRecord(row.permissionSnapshotJson).taskResume;+ return {+ state: cancelling ? 'cancelling' : resuming ? 'resuming' : pause+ ? (row.childSessionId && deps.taskControl?.isActive(row.childSessionId)+ ? 'pausing' : 'paused')+ : isActiveDelegation(row.status as DelegationStatus) ? 'active' : 'terminal',+ paused_at: pause?.pausedAt ?? null,+ queue_held: !!pause || cancelling || resuming,+ // Historical receipt only: request-stop never freezes or replays a turn.+ last_stop_request: parseRecord(row.permissionSnapshotJson).taskStopRequest ?? null,+ stop_status: row.childSessionId && deps.taskControl+ ? (deps.taskControl.isActive(row.childSessionId) ? 'unconfirmed' : 'stopped') : 'unknown',+ };};- const messageSessionTask = async (- callerSessionId: string,- taskId: string,- input: SessionTaskMessage,- ) => {- const found = await findOwnedSessionTask(callerSessionId, taskId);- if (!found.ok) return found;- return reply(callerSessionId, taskId, input);+ const restorePauseForSession = async (sessionId: string): Promise<boolean> => {+ const [row] = await getDbClient().drizzle.select().from(botDelegations)+ .where(and(eq(botDelegations.childSessionId, sessionId),+ inArray(botDelegations.status, [...ACTIVE_DELEGATION_STATUSES]))) .limit(1);+ const paused = !!row && (!!readTaskPause(row) || parseRecord(row.permissionSnapshotJson).taskCancelRequested === true);+ if (paused) holdTaskInput(sessionId, true);+ return paused;+ };++ /** Release only a committed resume; repeat receipts never enqueue a second turn. */+ const finishTaskResume = async (row: DelegationRow) => {+ if (!row.childSessionId || !deps.taskControl) throw new Error('Missing task input control');+ let status = row.status as DelegationStatus;+ const control = deps.taskControl;+ const pending = pendingInteractions.get(row.id);+ if (pending) pending.raisedAt = row.updatedAt;+ holdTaskInput(row.childSessionId, false);+ if (pending?.decisionApplied) {+ // Native settlement callbacks are serialized behind this operation. Apply+ // their bookkeeping now using the synchronous resolver receipt.+ await handleInteractionEndUnserialized(row.childSessionId, pending.request);+ status = 'running';+ }+ const awaitingInteraction = pending && !pending.decisionApplied ? pending : null;+ await control.resumeInput(row.childSessionId);+ if (awaitingInteraction) await notifyRequesterOfInteraction(row, awaitingInteraction);+ else {+ const deadline = readDeadline(row.permissionSnapshotJson);+ if (deadline !== null) scheduleTimeout(row.id, deadline);+ }+ emitChanged({ delegationId: row.id, parentSessionId: row.parentSessionId,+ childSessionId: row.childSessionId, status,+ pendingInteraction: awaitingInteraction ? pendingInteractionView(awaitingInteraction) : null });+ return { ok: true as const, childSessionId: row.childSessionId, resumed: true,+ delivery: awaitingInteraction ? 'awaiting-interaction' : pending?.decisionApplied ? 'interaction' : 'queued',+ control: { state: 'active', queue_held: false } };+ };++ const resumeTask = async (row: DelegationRow, text?: string) => {+ const pause = readTaskPause(row);+ const control = deps.taskControl;+ const receipt = parseRecord(row.permissionSnapshotJson).taskResume as { token?: string; text?: string } | undefined;+ if (!pause && receipt?.token && control && row.childSessionId && isActiveDelegation(row.status as DelegationStatus)) {+ if ((text?.trim() ?? '') !== (receipt.text ?? '')) {+ return { ok: false as const, errorCode: 'RESUME_INPUT_CHANGED', message: 'This pause has already resumed with different input' };+ }+ // A lost DB acknowledgement can leave the local barrier held even though+ // the queue and resume are durable. Finish that transition without dispatch.+ if (heldSessionIds.has(row.childSessionId)) {+ await control.restoreInput(row.childSessionId);+ return finishTaskResume(row);+ }+ return { ok: true as const, childSessionId: row.childSessionId, resumed: true,+ delivery: 'accepted', control: taskControlView(row) };+ }+ if (!pause || !control || !row.childSessionId || !isActiveDelegation(row.status as DelegationStatus)) {+ return { ok: false as const, errorCode: 'NOT_PAUSED', message: 'Task has no resumable pause' };+ }+ // A requested interrupt cannot be retracted. Never race it with another send.+ const pending = pendingInteractions.get(row.id);+ if (control.isActive(row.childSessionId) && (!pending || !pause.interactionOnly)) {+ return { ok: false as const, errorCode: 'STOP_UNCONFIRMED', message: 'The previous turn has not stopped; resume is not yet safe' };+ }+ if (pending && text) {+ return { ok: false as const, errorCode: 'WRONG_REPLY_KIND', message: 'Resume without a message, then answer the pending interaction' };+ }+ const validation = await validateDispatchPlan(row);+ if (!validation.ok) return validation;+ // Reassert the durable hold before restore/dispatch, including a cold caller.+ 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.+ try {+ if (status === 'queued') {+ 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';+ }+ if (!pending && (text || (pause.previousStatus !== 'queued' && !deps.hasPendingInput?.(row.childSessionId)))) {+ const dispatched = await deps.dispatch({ targetSessionId: row.childSessionId,+ 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);+ }+ 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) };+ }+ // Keep the input barrier until the durable transition and continuation enqueue are complete.+ try {+ const [resumed] = await getDbClient().drizzle.update(botDelegations).set({ status,+ permissionSnapshotJson: JSON.stringify(snapshot),+ pendingInteractionJson: pending ? JSON.stringify(pendingInteractionView({ ...pending, raisedAt: resumedAt })) : null,+ updatedAt: resumedAt,+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.permissionSnapshotJson, row.permissionSnapshotJson),+ inArray(botDelegations.status, [...ACTIVE_DELEGATION_STATUSES])))+ .returning({ id: botDelegations.id });+ if (!resumed) throw new Error('Task changed before resume committed');+ } catch (error) {+ // SQLite can commit before the worker/RPC receipt fails. Only release the+ // barrier after reading the exact committed snapshot; otherwise leave the+ // durable queue and pause token intact for an explicit retry.+ let current: DelegationRow | undefined;+ try {+ [current] = await getDbClient().drizzle.select().from(botDelegations)+ .where(eq(botDelegations.id, row.id)).limit(1);+ } catch { /* An unavailable readback is not a commit receipt. */ }+ if (!current || current.permissionSnapshotJson !== JSON.stringify(snapshot)+ || !isActiveDelegation(current.status as DelegationStatus)) {+ return { ok: false as const, errorCode: 'RESUME_FAILED',+ message: error instanceof Error ? error.message : String(error) };+ }+ status = current.status as DelegationStatus;+ }+ return finishTaskResume({ ...row, status, updatedAt: resumedAt, permissionSnapshotJson: JSON.stringify(snapshot) });};- const stopSessionTask = async (callerSessionId: string, taskId: string) => {+ const messageSessionTask = (callerSessionId: string, taskId: string, input: SessionTaskMessage) =>+ withTaskOperation(taskId, async () => {+ const found = await findOwnedSessionTask(callerSessionId, taskId);+ if (!found.ok) return found;+ const row = found.row;+ if (parseRecord(row.permissionSnapshotJson).taskCancelRequested === true && isActiveDelegation(row.status as DelegationStatus) && input.kind !== 'withdraw') {+ return { ok: false as const, errorCode: 'STOP_UNCONFIRMED', message: 'Cancellation is still awaiting runtime confirmation' };+ }+ if (input.kind === 'edit' || input.kind === 'withdraw') {+ if (!row.childSessionId || !deps.taskQueue) return { ok: false as const,+ errorCode: 'UNSUPPORTED_CAPABILITY', message: 'Task queue control is unavailable' };+ const params = { callerSessionId, targetSessionId: row.childSessionId, queuedMessageId: input.queuedMessageId };+ const result = input.kind === 'edit'+ ? await deps.taskQueue.update({ ...params, message: input.text })+ : await deps.taskQueue.cancel(params);+ if (result.ok) await deps.taskControl?.flushInput(row.childSessionId);+ return result.ok ? { ...result, childSessionId: row.childSessionId, resumed: false,+ delivery: input.kind === 'edit' ? 'queued' : 'withdrawn' } : result;+ }+ try { if (row.childSessionId) await deps.reconcileWorktree?.(row.childSessionId); }+ catch { return { ok: false as const, errorCode: 'WORKTREE_TRANSFER_PENDING', message: 'Task worktree ownership is awaiting reconciliation' }; }+ if (input.kind === 'resume') return resumeTask(row, input.text);+ if (readTaskPause(row) && isActiveDelegation(row.status as DelegationStatus)) {+ return { ok: false as const, errorCode: 'TASK_PAUSED', message: 'Resume the task explicitly before sending input or answering an interaction' };+ }+ if (input.kind === 'message' && input.mode === 'steer') {+ if (!deps.taskControl || !row.childSessionId || !isActiveDelegation(row.status as DelegationStatus)) {+ return { ok: false as const, errorCode: 'NO_ACTIVE_TURN', message: 'Task has no steerable turn' };+ }+ // Keep the caller/task/key identity stable across retries and turns.+ // Do not strip characters or truncate keys into accidental collisions.+ const queuedMessageId = input.idempotencyKey === undefined ? undefined+ : `bot-task-steer:${createHash('sha256').update(JSON.stringify([callerSessionId, taskId, input.idempotencyKey])).digest('hex')}`;+ if (queuedMessageId) {+ const [sent] = await getDbClient().drizzle.select({ agentMeta: messages.agentMeta }).from(messages)+ .where(and(eq(messages.sessionId, row.childSessionId), eq(messages.clientId, queuedMessageId), isNull(messages.rewindAt))).limit(1);+ const origin = parseRecord(sent?.agentMeta).origin as { kind?: string; senderSessionId?: string } | undefined;+ if (origin?.kind === 'session' && origin.senderSessionId === callerSessionId) {+ return { ok: true as const, childSessionId: row.childSessionId,+ resumed: false, queued: false, delivery: 'same-turn', queuedMessageId };+ }+ }+ // The coordinator deduplicates in-flight and accepted IDs even when+ // persistence failed after native acceptance. Persisted rows cover restore.+ const result = await deps.taskControl.steer({ callerSessionId,+ targetSessionId: row.childSessionId, message: input.text, queuedMessageId });+ return result.ok ? { ok: true as const, childSessionId: row.childSessionId,+ resumed: false, queued: false, delivery: 'same-turn', queuedMessageId: result.queuedMessageId } : result;+ }+ const result = await reply(callerSessionId, taskId, input);+ return result.ok ? { ...result,+ delivery: input.kind !== 'message' ? 'interaction' : result.queued ? 'queued' : 'accepted' } : result;+ });++ const stopSessionTask = (callerSessionId: string, taskId: string,+ mode: 'cancel' | 'request-stop' | 'pause' = 'cancel') => withTaskOperation(taskId, async () => {const found = await findOwnedSessionTask(callerSessionId, taskId);if (!found.ok) return found;- return cancelDelegation(callerSessionId, taskId);- };+ if (mode === 'cancel') return cancelDelegation(callerSessionId, taskId);+ const row = found.row;+ const control = deps.taskControl;+ if (!control || !row.childSessionId) return { ok: false as const,+ 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' };+ 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 });+ if (result.ok) {+ await getDbClient().drizzle.update(botDelegations).set({+ permissionSnapshotJson: JSON.stringify({ ...parseRecord(row.permissionSnapshotJson),+ taskStopRequest: { requested_at: now(), status: result.status,+ turn_generation: result.turnGeneration ?? null } }),+ }).where(eq(botDelegations.id, row.id));+ }+ return result.ok ? { ok: true as const, childSessionId: row.childSessionId,+ control: { state: result.status, queue_held: false } } : result;+ }++ const pending = pendingInteractions.get(row.id);+ const pause: SessionTaskPause = existingPause ?? { token: createId(),+ pausedAt: pending?.raisedAt ?? now(), previousStatus: row.status as SessionTaskPause['previousStatus'],+ interactionOnly: !!pending };+ const wasHeld = !!existingPause || heldSessionIds.has(row.childSessionId);+ holdTaskInput(row.childSessionId, true);+ const snapshot = JSON.stringify({ ...parseRecord(row.permissionSnapshotJson), taskPause: pause });+ let persisted = false;+ try {+ const [paused] = await getDbClient().drizzle.update(botDelegations).set({ permissionSnapshotJson: snapshot,+ status: row.status === 'queued' ? 'queued' : 'waiting', updatedAt: now(),+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.permissionSnapshotJson, row.permissionSnapshotJson),+ inArray(botDelegations.status, [...ACTIVE_DELEGATION_STATUSES])))+ .returning({ id: botDelegations.id });+ if (!paused) {+ holdTaskInput(row.childSessionId, wasHeld);+ return { ok: false as const, errorCode: 'SESSION_TASK_STATE_CHANGED', message: 'Task changed before pause committed' };+ }+ 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 });+ if (!result.ok) {+ if (!existingPause) {+ await getDbClient().drizzle.update(botDelegations).set({ permissionSnapshotJson: row.permissionSnapshotJson,+ status: row.status }).where(and(eq(botDelegations.id, row.id),+ inArray(botDelegations.status, [...ACTIVE_DELEGATION_STATUSES])));+ holdTaskInput(row.childSessionId, false);+ }+ 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);+ emitChanged({ delegationId: row.id, parentSessionId: row.parentSessionId,+ childSessionId: row.childSessionId, status: row.status === 'queued' ? 'queued' : 'waiting' });+ return { ok: true as const, childSessionId: row.childSessionId,+ control: { ...taskControlView({ ...row, permissionSnapshotJson: snapshot }), stop_status: result.status } };+ } catch (error) {+ // A failed retry cannot release an already durable pause or its permission timer.+ if (!persisted) holdTaskInput(row.childSessionId, wasHeld);+ // Once persisted, a failed/uncertain stop keeps the hold for an explicit safe retry.+ return { ok: false as const, errorCode: 'PAUSE_UNCONFIRMED',+ message: error instanceof Error ? error.message : String(error) };+ }+ });- const settleSession = async (params: {+ const settleSessionUnserialized = async (params: {childSessionId: string;outcome: 'done' | 'error';resultText?: string;@@ -2488,7 +2982,6 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}): Promise<void> => {// A message sent while the child is busy is queued for its next turn. The// current turn's done event is only a boundary, not the task's final result.- if (params.hadPendingInputAtTerminal || deps.hasPendingInput?.(params.childSessionId)) return;const db = getDbClient().drizzle;const [row] = await db.select()@@ -2496,7 +2989,12 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.where(eq(botDelegations.childSessionId, params.childSessionId)).orderBy(desc(botDelegations.createdAt)).limit(1);- if (!row || !ACTIVE_DELEGATION_STATUSES.includes(row.status as (typeof ACTIVE_DELEGATION_STATUSES)[number])) 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;const [child] = await db.select({ tokensUsed: sessions.totalTokenUsage }).from(sessions)@@ -2541,6 +3039,22 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {});};+ const settleSession = async (params: Parameters<typeof settleSessionUnserialized>[0]) => {+ 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 =>+ log.warn('Task cancellation confirmation failed', { delegationId: held.id, error: String(error) }));+ }+ return;+ }+ const [row] = await getDbClient().drizzle.select({ id: botDelegations.id }).from(botDelegations)+ .where(eq(botDelegations.childSessionId, params.childSessionId)).limit(1);+ if (row) await withTaskOperation(row.id, () => settleSessionUnserialized(params));+ };+const restore = async (): Promise<void> => {const db = getDbClient().drizzle;const rows = await db@@ -2553,32 +3067,67 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {isNull(botDelegations.completionDeliveredAt),),));+ let reconciliationFailed = false;for (const persistedRow of rows) {- const row = await repairDelegationParent(persistedRow);- if (!isActiveDelegation(row.status as DelegationStatus)) {- // Recreate the task-card anchor as well as the hidden wake after an- // abnormal canonical replacement. The result must remain visible.+ await withTaskOperation(persistedRow.id, async () => {+ const [current] = await db.select().from(botDelegations)+ .where(eq(botDelegations.id, persistedRow.id)).limit(1);+ if (!current) return;+ const row = await repairDelegationParent(current);+ try { if (row.childSessionId) await deps.reconcileWorktree?.(row.childSessionId); }+ catch (error) {+ log.warn('Task worktree reconciliation deferred', { delegationId: row.id, error: String(error) });+ reconciliationFailed = true;+ return;+ }+ if (!isActiveDelegation(row.status as DelegationStatus)) {+ // Recreate the task-card anchor as well as the hidden wake after an+ // abnormal canonical replacement. The result must remain visible.+ await projectParentRequest(row);+ await deliverCompletion({+ ...row,+ status: row.status as Extract<DelegationStatus, 'completed' | 'failed' | 'cancelled' | 'timed-out'>,+ artifacts: parseArtifacts(row.outputArtifactsJson),+ });+ return;+ }+ // Idempotent repair for the crash window between durable task creation/reparenting+ // and its timeline projection. A running task must never become unfindable.await projectParentRequest(row);- await deliverCompletion({- ...row,- status: row.status as Extract<DelegationStatus, 'completed' | 'failed' | 'cancelled' | 'timed-out'>,- artifacts: parseArtifacts(row.outputArtifactsJson),- });- continue;- }- // Idempotent repair for the crash window between durable task creation/reparenting- // and its timeline projection. A running task must never become unfindable.- await projectParentRequest(row);- if (row.status === 'queued') {- const deadlineAt = readDeadline(row.permissionSnapshotJson);- if (deadlineAt !== null) scheduleTimeout(row.id, deadlineAt);- if (row.childSessionId) await attemptDispatch(row.id);- continue;- }- if (row.status === 'running' || row.status === 'waiting') {- await resumeRunningDelegation(row.id);- }+ if (parseRecord(row.permissionSnapshotJson).taskCancelRequested === true) {+ if (row.childSessionId) {+ holdTaskInput(row.childSessionId, true);+ await deps.abortSession(row.childSessionId);+ }+ if (!row.childSessionId || !deps.taskControl?.isActive(row.childSessionId)) {+ await cancelDelegationTree(row, 'Cancelled by the requesting Bot.', true, true);+ }+ return;+ }+ if (readTaskPause(row)) {+ if (row.childSessionId) holdTaskInput(row.childSessionId, true);+ return;+ }+ if (row.childSessionId && heldSessionIds.has(row.childSessionId)+ && parseRecord(row.permissionSnapshotJson).taskResume) {+ await deps.taskControl?.restoreInput(row.childSessionId);+ await finishTaskResume(row);+ return;+ }+ if (row.status === 'queued') {+ const deadlineAt = readDeadline(row.permissionSnapshotJson);+ if (deadlineAt !== null) scheduleTimeout(row.id, deadlineAt);+ if (row.childSessionId) await attemptDispatch(row.id);+ return;+ }+ if (row.status === 'running' || row.status === 'waiting') {+ await resumeRunningDelegation(row.id);+ }+ });}+ // Preserve progress for unaffected tasks, but do not let the coordinator+ // mark this owner epoch restored while a durable task is still blocked.+ if (reconciliationFailed) throw new Error('Task worktree reconciliation pending');};const unregisterParentCancellation = registerBotDelegationParentCancellation(@@ -2614,9 +3163,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {},listDelegations,getSessionTask,+ restorePauseForSession,messageSessionTask,stopSessionTask,- cancelDelegation,+ cancelDelegation: (callerSessionId: string, delegationId: string) => withTaskOperation(delegationId, () => cancelDelegation(callerSessionId, delegationId)),cancelDelegationsForParentSession,cancelDelegationsForBot,settleSession,diff --git a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts b/apps/desktop/src/main/maker-ipc/botSystemPrompt.tsindex 2ee13818c6..696e750bae 100644--- a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts+++ b/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts@@ -131,11 +131,11 @@ const TASK_AND_TEAMMATE_GUIDANCE = ['- `start_session_task` 会创建一条真正独立运行的 Cindy 任务:它出现在用户的任务列表,有自己的工作过程、状态、停止、授权代答、结果和产物回传。用户明确说“开/建一个任务”“session 任务”“后台任务”时必须用它。它不会唤起任何伙伴。一次请求只启动一次。','- 分工按实际工作量和复杂度判断,不靠猜测分钟数。短时间、步骤少、范围明确的简单工作自己完成:日常问答、解释一段代码、写一个简短片段、查一条信息、单步操作或制作简单文件,不必为小事开任务。','- 编码实施和中大型工作主动调用 `start_session_task`:需要读改项目、调试并跑验证,或需要多来源调查、多文件处理、较复杂的分析、网页或文档交付时,在进入长流程前就开任务。不要等用户说“分出去”,不要只建议开任务,也不要再问“要不要我开个任务”;可以简短告知后立即调用。用户明确要求留在这里做时尊重该要求;真实缺少目标、必要材料或授权才问。',- '- 简单工作开始后发现范围扩大,也要转交。把用户目标、约束、相关目录和文件、已查明的信息、已完成的操作与验收要求写进 `instruction`,有已确认的项目目录再传 `working_dir`;独立任务不会自动知道这里的聊天历史,不要让它重复已完成或可能有副作用的操作。',+ '- 简单工作开始后发现范围扩大,也要转交。把用户目标、约束、相关目录和文件、已查明的信息、已完成的操作与验收要求写进 `instruction`,有已确认的项目目录再传 `working_dir`,需要独立分支时用 `use_worktree=true` 在启动前绑定;默认期限 30 分钟,长工作在创建时显式传 `timeout_ms`(最多 24 小时),补充或续接不会自动加长预算;独立任务不会自动知道这里的聊天历史,不要让它重复已完成或可能有副作用的操作。','- 开任务不等于交付完成。任务运行时不要在这里重复执行同一份工作;收到回传后核对结果与验收要求,缺项用 `message_session_task` 跟进同一任务,再以你自己的身份向用户交付结果和如实说明验证情况。','- `check_session_task` 查看指定任务的实时状态;只有用户追问进度或自动回传疑似丢失时才查,不要定时轮询。',- '- `message_session_task` 给同一任务补充条件、修正方向,或回答它正在等待的授权、问题和计划确认;不要为了补一句话另开任务。',- '- `stop_session_task` 停止指定任务及其子任务。只有用户要求停止,或继续执行会不安全时才使用。',+ '- `message_session_task` 默认排队补充条件;mode=steer 插入正在运行的同一轮,不支持时明确失败;mode=resume 恢复暂停且保留同一执行任务,不重放原请求。已暂停且等待授权、问题或计划确认时,先恢复再回答;不要为了补一句话另开任务。',+ '- `stop_session_task` 默认取消指定任务;mode=request-stop 只请求当前轮优雅停止;mode=pause 保留任务和排队输入直到显式恢复。pausing、requested 或 unconfirmed 不代表引擎已停,必须按回执如实说明。只有用户要求停止,或继续执行会不安全时才使用。','- 后台任务完成、失败或停止时,当前时间线里的任务卡会更新,结果和文件会自动回到这里。','- `send_to_agent` 只给「你的队友」里明确存在的伙伴发一条异步消息,不启动任务,也没有进度、停止或自动交付。只有用户明确点名某个伙伴,或当前工作确实需要那个伙伴的身份和信息时,才用名册里的稳定 Bot id。编码实施和中大型工作必须用 `start_session_task`,不能把给伙伴发消息当作分配任务。','- 收到 `[Direct message from Cindy Bot ...]` 时,在自己的当前主任务里处理。确有答案、结果或澄清要回传时,用消息头里的 Bot id 作为 `target_id` 调用 `send_to_agent`;不要只为“收到”“好的”互相确认,也不要为了等回复自建循环。',diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 528fb4365a..b7370e777f 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -2275,6 +2275,11 @@ interface PendingInteractionEntry {*/persistId?: string;timeoutId?: ReturnType<typeof setTimeout>;+ timeoutDeadlineAt?: number;+ timeoutRemainingMs?: number;+ /** IM owns presentation/timeouts; Host retains the execution and cancellation boundary. */+ migrated?: boolean;+ deferredDecision?: InteractionDecision;}const pendingInteractionResolvers = new Map<string, PendingInteractionEntry>();@@ -2415,6 +2420,50 @@ function clearPendingInteraction(requestId: string): PendingInteractionEntry | nreturn entry;}+/** Permission safety time counts only while its owning task can accept input. */+function schedulePendingPermissionTimeout(requestId: string, entry: PendingInteractionEntry): void {+ if (entry.migrated || entry.kind !== 'permission' || entry.timeoutId !== undefined+ || pendingInteractionResolvers.get(requestId) !== entry+ || agentInputCoordinatorHolder?.isExecutionPaused(entry.sessionId)) return;+ const remaining = entry.timeoutRemainingMs ?? PERMISSION_INTERACTION_TIMEOUT_MS;+ entry.timeoutDeadlineAt = Date.now() + remaining;+ entry.timeoutId = setTimeout(() => {+ if (pendingInteractionResolvers.get(requestId) !== entry) return;+ entry.timeoutId = undefined;+ entry.timeoutRemainingMs = 0;+ entry.timeoutDeadlineAt = undefined;+ // Also guard an already-due callback at the pause boundary.+ if (agentInputCoordinatorHolder?.isExecutionPaused(entry.sessionId)) return;+ const pending = clearPendingInteraction(requestId);+ if (!pending) return;+ handleAgentIslandInteractionDismissed(entry.sessionId, requestId);+ pending.resolve({ kind: 'permission', behavior: 'deny', reason: 'timeout' });+ dismissRendererInteraction(pending, requestId, 'timeout', 'deny');+ }, remaining);+}++function setPendingInteractionTimeoutsPaused(sessionId: string, paused: boolean): string[] {+ const applied: string[] = [];+ for (const [requestId, entry] of pendingInteractionResolvers) {+ if (entry.sessionId !== sessionId) continue;+ if (!paused && entry.deferredDecision) {+ if (resolvePendingInteraction(requestId, entry.deferredDecision)) applied.push(requestId);+ continue;+ }+ if (entry.kind !== 'permission') continue;+ if (paused) {+ if (entry.timeoutId === undefined) continue;+ clearTimeout(entry.timeoutId);+ entry.timeoutId = undefined;+ entry.timeoutRemainingMs = Math.max(0, (entry.timeoutDeadlineAt ?? Date.now()) - Date.now());+ entry.timeoutDeadlineAt = undefined;+ } else {+ schedulePendingPermissionTimeout(requestId, entry);+ }+ }+ return applied;+}+type RecoverableInteractionSnapshot =| InteractionRequest| GhostSetupInteractionSnapshot@@ -2436,7 +2485,7 @@ type PendingInteractionSnapshotEntry = {function getPendingInteractionsForSession(sessionId: string): PendingInteractionSnapshotEntry[] {const out: PendingInteractionSnapshotEntry[] = [];for (const entry of pendingInteractionResolvers.values()) {- if (entry.sessionId === sessionId)+ if (entry.sessionId === sessionId && !entry.migrated)out.push({ request: entry.request, persistId: entry.persistId });}out.push(@@ -2558,7 +2607,7 @@ function persistInteractionDecision(function resolvePendingInteraction(requestId: string, decision: InteractionDecision): boolean {const resolver = pendingInteractionResolvers.get(requestId);- if (!resolver) return false;+ if (!resolver || agentInputCoordinatorHolder?.isExecutionPaused(resolver.sessionId)) return false;clearPendingInteraction(requestId);handleAgentIslandInteractionDismissed(resolver.sessionId, requestId);resolver.resolve(decision);@@ -2707,7 +2756,7 @@ export function takePendingInteractionsForSession(sessionId: string): Array<{resolve: (decision: InteractionDecision) => void;}> {const entries = Array.from(pendingInteractionResolvers.entries()).filter(- ([, entry]) => entry.sessionId === sessionId,+ ([, entry]) => entry.sessionId === sessionId && !entry.migrated,);const taken: Array<{requestId: string;@@ -2715,8 +2764,19 @@ export function takePendingInteractionsForSession(sessionId: string): Array<{resolve: (decision: InteractionDecision) => void;}> = [];for (const [requestId, entry] of entries) {- clearPendingInteraction(requestId);- taken.push({ requestId, request: entry.request, resolve: entry.resolve });+ // Transfer the UI, never the raw engine resolver. Keep cancellation and pause+ // ownership here even after the IM registry consumes its one-shot answer.+ if (entry.timeoutId) clearTimeout(entry.timeoutId);+ entry.timeoutId = undefined;+ entry.migrated = true;+ taken.push({ requestId, request: entry.request, resolve: decision => {+ if (pendingInteractionResolvers.get(requestId) !== entry || entry.deferredDecision) return;+ if (agentInputCoordinatorHolder?.isExecutionPaused(sessionId)) {+ entry.deferredDecision = decision;+ return;+ }+ resolvePendingInteraction(requestId, decision);+ } });handleAgentIslandInteractionDismissed(entry.sessionId, requestId);// resolvedAs 省略 — renderer 行 1537 默认 'deny', UI 上只是关掉对话框,// 跟我们这里"搬走"语义一致(没真选 allow/deny)。@@ -3990,18 +4050,10 @@ export function installDesktopInteractionListener(session: {request: boundaryRequest,persistId: interactionPersistId ?? undefined,};- if (req.kind === 'permission') {- entry.timeoutId = setTimeout(() => {- const pending = clearPendingInteraction(req.requestId);- if (!pending) return;- handleAgentIslandInteractionDismissed(session.id, req.requestId);- pending.resolve({ kind: 'permission', behavior: 'deny', reason: 'timeout' });- dismissRendererInteraction(pending, req.requestId, 'timeout', 'deny');- }, PERMISSION_INTERACTION_TIMEOUT_MS);- }// 必须先登记 pending,再广播。否则 renderer / device-link 回得太快会打到// 「no pending resolver」,确认卡看起来没反应,Codex 最终却记成用户拒绝。pendingInteractionResolvers.set(req.requestId, entry);+ schedulePendingPermissionTimeout(req.requestId, entry);broadcastToAllWindows(MAKER_PUSH.INTERACTION_REQUEST, {sessionId: session.id,request: boundaryRequest,@@ -9081,6 +9133,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const dispatchBotSessionMessage = async (params: {targetSessionId: string;+ dispatcherSessionId?: string;authorizationGuard?: BotAuthorizationInputGuard;message: string;persistedContent?: string;@@ -9246,6 +9299,57 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});botDelegationServiceHolder?.dispose();botDelegationServiceHolder = createBotDelegationService({+ taskControl: {+ steer: (params) => sessionControlService.steerSession(params),+ stop: (params) => sessionControlService.stopSessionTurn(params),+ isActive: (id) => {+ const session = maker.getSession(id);+ return !!session && (session.isTurnRunning() || session.getTurnControlSnapshot().pendingInteractionCount > 0);+ },+ holdInput: (id, held) => {+ inputCoordinator.setExecutionPaused(id, held);+ return setPendingInteractionTimeoutsPaused(id, held);+ },+ // Wait for sends already admitted before the hold before sampling native activity.+ waitForInputBoundary: (id) => withSendToSessionLock(id, async () => undefined),+ preparePause: async (id) => {+ resetAutomaticRecoveryForExplicitStop(id);+ contextOverflowRolloverHolder?.cancelRecovery(id);+ await pauseGoalBeforeExplicitStop(id);+ },+ restoreInput: (id) => inputCoordinator.ensureQueueRestored(id),+ flushInput: awaitAgentInputQueueSnapshotPersistence,+ resumeInput: async (id) => { inputCoordinator.resume(id); },+ },+ getWorktree: worktreeManager.getForSession,+ reconcileWorktree: worktreeManager.reconcileSessionTransfer,+ withTransferredWorktree: worktreeManager.withTransferredSession,+ discardUnusedWorktree: async sessionId => {+ const [row] = await getDbClient().drizzle.select({ id: sessions.id }).from(sessions)+ .where(eq(sessions.id, sessionId)).limit(1);+ if (!row) await worktreeManager.removeWorktreeForSession(sessionId);+ },+ prepareWorktree: async workingDir => {+ const prepared = await prepareHandoffWorktree({+ getForSession: worktreeManager.getForSession, listAll: worktreeManager.listAll,+ detectCwd: worktreeManager.detectCwd, suggestName: worktreeManager.suggestName,+ listBranches: worktreeManager.listBranches, resolveCommit: worktreeManager.revParseCommit,+ createWorktree: worktreeManager.createWorktree, createId: () => randomUUID(),+ resolveFreshSource: resolveFreshSourceBranch,+ }, undefined, workingDir);+ return prepared.ok ? { ok: true, sessionId: prepared.sessionId, workingDir: prepared.meta.path } : prepared;+ },+ taskQueue: {+ inspect: async (id, callerSessionId) => {+ await inputCoordinator.ensureQueueRestored(id);+ if (!inputCoordinator.isQueueRestored(id)) throw new Error('Task queue restoration is incomplete');+ return inputCoordinator.getQueueInspection(id)+ .filter(item => item.source === 'session' && item.sourceLabel === callerSessionId)+ .map(item => ({ queuedMessageId: item.queuedMessageId, consuming: item.consuming, message: item.content }));+ },+ update: params => sessionControlService.updateQueuedMessage(params),+ cancel: params => sessionControlService.cancelQueuedMessage(params),+ },readCallerPermission: (sessionId) => {const state = maker.getSession(sessionId)?.stablePermissionModeState;return state?.mode ? { mode: state.mode, generation: state.generation } : null;@@ -9260,17 +9364,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)fastMode: getSessionFastMode(sessionId),} : null;},- dispatch: ({ targetSessionId, message, persistedContent, clientId, onAccepted }) =>+ dispatch: ({ targetSessionId, message, persistedContent, clientId, onAccepted, dispatcherSessionId }) =>dispatchBotSessionMessage({targetSessionId,message,persistedContent,clientId,onAccepted,+ dispatcherSessionId,}),abortSession: (async (sessionId) => {- const session = maker.getSession(sessionId);- if (session?.isTurnRunning?.()) await session.abort();+ await inputCoordinator.ensureQueueRestored(sessionId);+ resetAutomaticRecoveryForExplicitStop(sessionId);+ contextOverflowRolloverHolder?.cancelRecovery(sessionId);+ await pauseGoalBeforeExplicitStop(sessionId);+ inputCoordinator.stop(sessionId);+ await awaitAgentInputQueueSnapshotPersistence(sessionId);}),closeSession: (sessionId) => maker.closeSession(sessionId),broadcastSessionCreated,@@ -12027,6 +12136,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)throwIpcError('NOT_FOUND', 'Session does not exist');}if (blocked) throwIpcError('PRECONDITION_FAILED', blocked);+ if (inputCoordinator.isExecutionPaused(sessionId)) {+ throwIpcError('PRECONDITION_FAILED', 'Task is paused; resume it before continuing');+ }return sendToAgentAcceptedUnlocked(...args);});};@@ -13139,7 +13251,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)signals: InterruptedTurnErrorSignals,item: AgentInputQueuedMessage,) => {- if (!isInterruptedTurnError(signals)) return null;+ if (!isInterruptedTurnError(signals) || inputCoordinator.isExecutionPaused(sessionId)) return null;const erroredAt = Date.now();const decision = interruptedTurnAutoResumeGuard.onInterruptedTurn(sessionId, erroredAt);if (decision.action !== 'resume') {@@ -13610,7 +13722,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)persistQueueSnapshot: (sessionId, items) => saveAgentInputQueueSnapshot(sessionId, items),loadClearBoundary: async (sessionId) =>(await getSessionRowSnapshotStrict(sessionId))?.clearedAt,- loadQueueSnapshot: (sessionId) => loadAgentInputQueueSnapshot(sessionId),+ loadQueueSnapshot: async (sessionId) => {+ // Rehydrate durable task holds before any entry point can drain restored/new input.+ await botDelegationServiceHolder?.restorePauseForSession(sessionId);+ return loadAgentInputQueueSnapshot(sessionId);+ },getPersistedClientIds: getPersistedInputClientIds,});agentInputCoordinatorHolder = inputCoordinator;diff --git a/apps/desktop/src/main/maker-ipc/sessionControlService.ts b/apps/desktop/src/main/maker-ipc/sessionControlService.tsindex bab4e15a1e..62def3dcd0 100644--- a/apps/desktop/src/main/maker-ipc/sessionControlService.ts+++ b/apps/desktop/src/main/maker-ipc/sessionControlService.ts@@ -165,6 +165,8 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {callerSessionId: string;targetSessionId: string;message: string;+ /** Host-owned stable ID; the input coordinator owns acceptance deduplication. */+ queuedMessageId?: string;}): Promise<SessionSteerResult> {const missing = await ensureTarget(params.targetSessionId);if (missing) return missing;@@ -196,7 +198,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {};}const turnGeneration = live.getTurnGeneration();- const queuedMessageId = deps.createId();+ const queuedMessageId = params.queuedMessageId ?? deps.createId();const item = await deps.createQueuedMessage({...params,queuedMessageId,diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 1578920678..4300a51173 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -520,7 +520,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc};}},- getSessionTask: async ({ callerSessionId, taskId }) => {+ getSessionTask: async ({ callerSessionId, taskId, queuedMessageId }) => {const svc = tryGetBotDelegationService();if (!svc) {return {@@ -529,9 +529,9 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcmessage: 'Session task service not initialized',};}- return svc.getSessionTask(callerSessionId, taskId);+ return svc.getSessionTask(callerSessionId, taskId, queuedMessageId);},- stopSessionTask: async ({ callerSessionId, taskId }) => {+ stopSessionTask: async ({ callerSessionId, taskId, mode }) => {const svc = tryGetBotDelegationService();if (!svc) {return {@@ -540,7 +540,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcmessage: 'Session task service not initialized',};}- return svc.stopSessionTask(callerSessionId, taskId);+ return svc.stopSessionTask(callerSessionId, taskId, mode);},},botMessaging: {diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.tsindex d64245c74f..6729b52c93 100644--- a/apps/desktop/src/main/worktree/WorktreeManager.ts+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts@@ -43,7 +43,7 @@ import {import { hasLiveSessionReference, loadLiveSessionPathKeys } from './liveSessionRefs';import { withWorktreeRestoreMutation } from './restoreLock';import { recycleManagedWorktree } from './managedRecycle';-import { withWorktreeResourceLock } from './resourceLock';+import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease } from './runtimeLeases';import * as store from './worktreeStore';import { createLogger } from '../logger';@@ -616,6 +616,102 @@ export function getForSession(sessionId: string): WorktreeMeta | null {return store.get(sessionId);}+/** Caller holds the session/resource locks. Unknown DB outcomes retain the intent. */+async function reconcileSessionTransferLocked(meta: WorktreeMeta): Promise<void> {+ const transfer = meta.pendingSessionTransfer;+ if (!transfer) return;+ if (!transfer.sessionId || transfer.sessionId === meta.sessionId+ || !transfer.delegationId || !transfer.requestingBotId) {+ throw new Error('Invalid worktree transfer intent preserved');+ }+ const row = await getDbClient().queryOne<{+ childSessionId: string; requestingBotId: string; worktreePath: string | null; persistedSessionId: string | null;+ targetExists: number;+ }>(`SELECT d.child_session_id AS childSessionId, d.requesting_bot_id AS requestingBotId,+ s.worktree_path AS worktreePath, s.id AS persistedSessionId,+ EXISTS(SELECT 1 FROM sessions WHERE id = ?) AS targetExists+ FROM bot_delegations d LEFT JOIN sessions s ON s.id = d.child_session_id WHERE d.id = ?`,+ [transfer.sessionId, transfer.delegationId]);+ if (!row || !row.persistedSessionId || row.requestingBotId !== transfer.requestingBotId+ // The previous registry is authoritative if its historical display snapshot+ // is absent. A committed target must have the snapshot from the same DB tx.+ || (row.childSessionId === transfer.sessionId && !row.worktreePath)+ || (row.worktreePath && await physicalWorktreeKey(row.worktreePath) !== await physicalWorktreeKey(meta.path))+ || (row.childSessionId !== transfer.sessionId+ && (row.childSessionId !== meta.sessionId || row.targetExists))) {+ throw new Error('Worktree ownership changed; pending transfer preserved for reconciliation');+ }+ const key = await physicalWorktreeKey(meta.path);+ for (const other of store.getAll()) {+ if (other.sessionId !== meta.sessionId && await physicalWorktreeKey(other.path) === key) {+ throw new Error('Worktree ownership changed; another session owns this resource');+ }+ }+ const next = { ...meta, sessionId: row.childSessionId };+ delete next.pendingSessionTransfer;+ await store.replace(meta.sessionId, next.sessionId, next, meta);+}++/** Startup/dispatch/retry reconciliation, scoped to the affected execution only. */+export async function reconcileSessionTransfer(sessionId: string): Promise<void> {+ const pending = store.getAll().find(meta => meta.pendingSessionTransfer+ && (meta.sessionId === sessionId || meta.pendingSessionTransfer.sessionId === sessionId));+ if (!pending?.pendingSessionTransfer) return;+ if (pending.pendingSessionTransfer.sessionId === pending.sessionId) throw new Error('Invalid worktree transfer intent preserved');+ await withWorktreeRestoreMutation(pending.sessionId, () =>+ withWorktreeRestoreMutation(pending.pendingSessionTransfer!.sessionId, () =>+ withWorktreeResourceLock(pending.path, async () => {+ const current = store.get(pending.sessionId);+ if (current?.pendingSessionTransfer) await reconcileSessionTransferLocked(current);+ })));+}++/** Journal before the DB transaction; move registration only after authoritative readback. */+export async function withTransferredSession<T extends { reopened: boolean }>(+ previousSessionId: string,+ sessionId: string,+ worktreePath: string,+ commit: () => Promise<T>,+ identity: { delegationId: string; requestingBotId: string },+): Promise<T> {+ if (previousSessionId === sessionId) throw new Error('Worktree transfer requires a new session');+ return withWorktreeRestoreMutation(previousSessionId, () =>+ withWorktreeRestoreMutation(sessionId, () =>+ withWorktreeResourceLock(worktreePath, async () => {+ const previous = store.get(previousSessionId);+ if (!previous || previous.pendingSessionTransfer || path.resolve(previous.path) !== path.resolve(worktreePath)+ || store.get(sessionId)) {+ throw new Error('Worktree ownership changed; restore the previous task before continuing');+ }+ const key = await physicalWorktreeKey(worktreePath);+ for (const other of store.getAll()) {+ if (other.sessionId !== previousSessionId && await physicalWorktreeKey(other.path) === key) {+ throw new Error('Worktree ownership changed; another session owns this resource');+ }+ }+ const pending = { ...previous, pendingSessionTransfer: { ...identity, sessionId } };+ await store.replace(previousSessionId, previousSessionId, pending, previous);+ try {+ const result = await commit();+ await reconcileSessionTransferLocked(pending);+ return result;+ } catch (error) {+ // A rejected worker receipt is not proof of rollback. Never reverse a+ // committed transfer; failed readback leaves durable retry evidence.+ const current = store.get(previousSessionId);+ if (JSON.stringify(current) === JSON.stringify(pending)) {+ await reconcileSessionTransferLocked(pending).catch(reconcileError => {+ log.warn('Worktree transfer reconciliation deferred', { sessionId: previousSessionId,+ error: reconcileError instanceof Error ? reconcileError.message : String(reconcileError) });+ });+ }+ throw error;+ }+ }),+ ),+ );+}+export function listAll(): WorktreeMeta[] {return store.getAll();}@@ -1233,6 +1329,7 @@ async function removeWorktreeForSessionInner(): Promise<void> {let meta = store.get(sessionId);if (!meta) return;+ if (meta.pendingSessionTransfer) return;if (meta.quarantinePath && !isExpectedQuarantinePath(meta, meta.quarantinePath)) {log.warn(`[worktree] preserved worktree at ${meta.path}: invalid persisted quarantine path`);return;diff --git a/apps/desktop/src/main/worktree/managedRecycle.ts b/apps/desktop/src/main/worktree/managedRecycle.tsindex a0c06e1777..9a41a53ded 100644--- a/apps/desktop/src/main/worktree/managedRecycle.ts+++ b/apps/desktop/src/main/worktree/managedRecycle.ts@@ -27,7 +27,7 @@ export interface ManagedRecycleOptions {/** Pool reset is destructive too: preserve the old generation before clean/reset. */export async function checkpointWorktreeForReuse(meta: WorktreeMeta): Promise<void> {const current = store.get(meta.sessionId);- if (!current || worktreeGeneration(current) !== worktreeGeneration(meta) || await hasOtherGeneration(meta)) throw new Error('pooled generation changed');+ if (!current || current.pendingSessionTransfer || worktreeGeneration(current) !== worktreeGeneration(meta) || await hasOtherGeneration(meta)) throw new Error('pooled generation changed');await assertManagedResourcePath(meta, store.getAllPaths());await assertWorktreeGitIdentity(meta);if (hasLiveSessionReference(meta, await loadLiveSessionPathKeys({ contextPath: meta.path }))) {@@ -91,6 +91,7 @@ export async function recycleManagedWorktree(meta: WorktreeMeta, options: Manageasync function recycleManagedWorktreeInSlot(meta: WorktreeMeta, options: ManagedRecycleOptions): Promise<boolean> {return withWorktreeResourceLock(meta.path, () => withLegacyWorktreeRuntimeGuard(async (legacyGuardHeld) => {const registered = store.get(meta.sessionId);+ if (registered?.pendingSessionTransfer) return false;if (registered && worktreeGeneration(registered) !== worktreeGeneration(meta)) return false;if (await hasOtherGeneration(meta)) return false;let record = await readRecycleRecord(meta.path);diff --git a/apps/desktop/src/main/worktree/types.ts b/apps/desktop/src/main/worktree/types.tsindex 6a028432f5..d9bcd0d789 100644--- a/apps/desktop/src/main/worktree/types.ts+++ b/apps/desktop/src/main/worktree/types.ts@@ -10,6 +10,8 @@* 同时也是 sessions.worktree_path 反范式快照的来源。*/export interface WorktreeMeta {+ /** Durable intent; DB delegation ownership decides whether to finish or discard it. */+ pendingSessionTransfer?: { sessionId: string; delegationId: string; requestingBotId: string };/** New physical contents at the same path invalidate old recycle requests. */generation?: string;sessionId: string;diff --git a/apps/desktop/src/main/worktree/worktreeStore.ts b/apps/desktop/src/main/worktree/worktreeStore.tsindex 9561f0eee6..7e310074c4 100644--- a/apps/desktop/src/main/worktree/worktreeStore.ts+++ b/apps/desktop/src/main/worktree/worktreeStore.ts@@ -213,9 +213,14 @@ export async function replace(previousSessionId: string,sessionId: string,meta: WorktreeMeta,+ expected?: WorktreeMeta,): Promise<void> {if (!sessionId) throw new Error('worktreeStore.replace: sessionId is required');await mutateRegistry((map) => {+ if (expected && (JSON.stringify(map[previousSessionId]) !== JSON.stringify(expected)+ || (previousSessionId !== sessionId && map[sessionId]))) {+ throw new Error('Worktree ownership changed during transfer');+ }if (previousSessionId && previousSessionId !== sessionId) delete map[previousSessionId];map[sessionId] = meta;});diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 1e56710579..9e2afe5ed2 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -194,9 +194,20 @@ harness + provider + model + effort + fastMode停止或自动交付合同;对方可以在自己的正常 turn 里处理,并通过反向消息回答。- `check_session_task`:按 `task_id` 读取一条后台任务的实时状态,只在用户追问或自动回传疑似丢失时使用,不作为轮询机制。-- `message_session_task`:按 `task_id` 给同一任务追加或修正要求,也负责回答它正在等待的权限、- 提问或计划确认;不得为了补充一句话重复创建任务。-- `stop_session_task`:按 `task_id` 停止这条后台任务。+- `message_session_task`:按 `task_id` 给同一任务追加或修正要求;`mode=queue`(默认)在忙碌时+ 排到下一轮,`mode=steer` 只使用运行中引擎的 same-turn 插话,不支持或旧轮已结束时明确失败,+ 不偷偷降级排队。`mode=resume` 解除可恢复暂停,可附新指令;不重放原请求或已完成操作。+ 它也负责回答等待的权限、提问或计划确认;暂停时先恢复再回答,不为补充一句话重复建任务。+- `stop_session_task`:`mode=cancel`(默认)终止任务;`mode=request-stop` 只请求当前轮优雅停止,+ 不承诺冻结下一轮;`mode=pause` 持久暂停同一执行任务,保留未消费输入与剩余执行期限。+ `control.state=pausing` 或 `stop_status=requested/unconfirmed` 不表示引擎已停;活跃执行仍在+ 等工具或确认时如实报告,确认空闲才返回 `paused`。等待中的交互保持原 resolver,恢复后才允许推进引擎。+ 交互迁移到 IM 后仍受同一暂停与取消边界约束;暂停期间收到的渠道回答或安全超时决定暂存,+ 恢复后只生效一次,取消优先撤销暂存回答。恢复依据宿主实际应用回执清理等待状态,+ 已应用的回答不再通知发起伙伴;确实未答的交互仍重新通知。渠道卡片的回答状态不表示引擎已恢复。+ 这些模式都只作用于调用伙伴拥有的后台任务;通用 Session control 类不因此开放给伙伴。+ `check_session_task.control.last_stop_request` 保留最近一次优雅停止请求的时间、返回状态和轮次;+ 它是历史回执,实际是否停稳仍看 `stop_status`,重启不会重放停止请求或冻结下一轮。伙伴按工作量主动分工(2026-09-07 产品裁决):@@ -213,7 +224,14 @@ harness + provider + model + effort + fastModeSession 任务遵守同一套机制与呈现契约:- **统一状态机**:`queued → running ⇄ waiting → completed | failed | cancelled`。`waiting`- 表示子任务正在等权限、答案或计划确认,不把“等人”误报成执行超时。+ 表示子任务正在等权限、答案、计划确认或显式恢复;显式暂停另有持久控制标记,+ `check_session_task` 返回 `control` 区分暂停与交互等待,不把它们误报成执行超时。+- **显式暂停恢复**:暂停先锁住输入,旧轮终态不交付完成回执;重启只恢复锁,不自动执行。+ 恢复保留同一任务 ID、执行 Session 和历史,有队列先消费队列,无队列才投一次去重续接指令。+ 旧轮停止未确认时拒绝恢复,禁止与迟到中断竞争;计时只补回实际等待时长。+ 续接输入先在暂停锁内持久入队,恢复状态提交并确认后才释放输入。提交失败保留原队列和暂停;+ 提交已成功但回执不明时回读确认,仍无法确认则保持锁并报告 `resuming`,显式重试或宿主恢复+ 只完成释放,不再投递新指令。相同恢复请求复用回执;不同补充内容须作为新的消息发送。- **等待恢复**:等待事项的人话摘要、请求标识和开始时间随任务行持久化;Host 重启后先保持`waiting` 与暂停计时,子任务恢复成功才回到 `running`。旧进程的 resolver 不可复用,恢复的子任务仍需要决定时必须重新发出 interaction request,不能让一个失效按钮假装批准成功。@@ -233,7 +251,28 @@ Session 任务遵守同一套机制与呈现契约:第二条消息。- **不静默丢失**:发起方的原父任务已被异常恢复流程替换时,完成信号改投该伙伴当前的canonical Session;只有伙伴本身已暂停 / 归档才放弃投递,此时卡片终态仍然可见。-- Session 任务只创建一层子任务,受并发上限约束;超时是持久化的执行边界。+- Session 任务只创建一层子任务,受并发上限约束;超时是持久化的执行边界。默认执行预算+ 30 分钟,创建时 `timeout_ms` 可指定至 24 小时;终态续接从新的开始时间按原预算计算,+ 普通补充不延长正在运行的期限。没有 Host 回读证据不得声称已延长。+- 项目执行显式传 `working_dir`,可用 `use_worktree=true` 在启动前复用现有 worktree 管理器+ 完成独立分支、目录与 Session 绑定;失败不得落回共享目录。只在 Shell 中新建 worktree+ 不会修改任务登记或运行时 cwd;`check_session_task` 返回实际登记目录与项目归属。+ 终态续接复用既有目录和分支,并将 worktree 管理器归属及数据库快照迁到新执行任务;+ 迁移先在原登记保存持久意图,提交后按数据库实际归属完成登记。提交回执丢失不盲目回滚,+ 重启、派发和续接重试会对账;数据库不可读或归属冲突时保留意图与目录,只阻止受影响执行,+ 不接管他人归属、不回收工作成果。+- 补充输入返回 `queued_message_id`;`check_session_task` 返回调用 Session 自己投递的队列,+ 可按消息 ID 查询 queued / consuming / dispatched / not-found / unavailable。队列恢复失败时+ 保留任务状态和结果,单独返回 `queue_error=QUEUE_UNAVAILABLE`;无法核实的消息不能报 not-found。+ dispatched 仅指宿主历史接受,+ 不证明模型已执行要求。`message_session_task(mode=edit/withdraw)` 复用共享队列的发送方与+ 消费竞态校验;不得改他人输入,consuming 不能编辑撤回,缺失不能假称已消费。+- `mode=steer` 的 `idempotency_key` 在同一调用 Session、同一后台任务内生成稳定消息 ID,+ 复用输入协调器去重;已落库的回执在运行时重建后仍可查询,不把旧插话重新注入新轮。+ 原生接受后的落库失败依赖协调器的有界近期去重窗口;进程崩溃且回执未落库时不能保证恰好一次。+- 取消复用界面停止的输入协调器,清除未派发队列与自动续接。持久取消标记阻止再次投递;+ `cancelling/unconfirmed` 不是已停,原生终态或状态回读确认空闲后才收口为 cancelled。+ 超时终态也必须检查旧引擎是否已停,仍活跃时不得通过续接启动第二份执行。`send_to_agent` 是另一条更轻的伙伴间通讯通道,不得伪装成任务:diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.tsindex e8a59f362e..578cec34ed 100644--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts@@ -210,6 +210,7 @@ describe("cindy_helper MCP server", () => {await client.callTool({ name: "call_tool", arguments: { name: "start_session_task", args: {title: "Build the demo",working_dir: "/repo",+ use_worktree: true,instruction: "Build and verify a standalone HTML demo.",} } }),);@@ -227,6 +228,7 @@ describe("cindy_helper MCP server", () => {objective: "Build and verify a standalone HTML demo.",title: "Build the demo",workingDir: "/repo",+ useWorktree: true,}),);@@ -247,6 +249,31 @@ describe("cindy_helper MCP server", () => {reply: { kind: "approve" },});+ for (const mode of ['queue', 'steer', 'resume']) {+ await client.callTool({ name: 'call_tool', arguments: { name: 'message_session_task', args: {+ task_id: 'session-task-1', mode, ...(mode === 'resume' ? {} : { message: 'follow up', idempotency_key: 'retry-key' }),+ } } });+ expect(messageSessionTask).toHaveBeenLastCalledWith({+ callerSessionId: 'bot-parent-session', taskId: 'session-task-1',+ reply: mode === 'resume' ? { kind: 'resume' } : { kind: 'message', text: 'follow up', mode, idempotencyKey: 'retry-key' },+ });+ }+ for (const mode of ['edit', 'withdraw']) {+ await client.callTool({ name: 'call_tool', arguments: { name: 'message_session_task', args: {+ task_id: 'session-task-1', mode, queued_message_id: 'mine', ...(mode === 'edit' ? { message: 'revised' } : {}),+ } } });+ expect(messageSessionTask).toHaveBeenLastCalledWith({ callerSessionId: 'bot-parent-session', taskId: 'session-task-1',+ reply: { kind: mode, queuedMessageId: 'mine', ...(mode === 'edit' ? { text: 'revised' } : {}) } });+ }+ const invalid = parsePayload(await client.callTool({ name: 'call_tool', arguments: {+ name: 'message_session_task', args: { task_id: 'session-task-1', mode: 'steer', decision: 'approve' },+ } }));+ expect(invalid).toMatchObject({ ok: false });+ for (const mode of ['pause', 'request-stop']) {+ await client.callTool({ name: 'call_tool', arguments: { name: 'stop_session_task', args: { task_id: 'session-task-1', mode } } });+ expect(stopSessionTask).toHaveBeenLastCalledWith({ callerSessionId: 'bot-parent-session', taskId: 'session-task-1', mode });+ }+const taskStatus = parsePayload(await client.callTool({ name: "call_tool", arguments: { name: "check_session_task", args: { task_id: "session-task-1" } } }),);diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex 96eebe5e2c..052f9bf244 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -117,6 +117,7 @@ interface SessionTaskCallbacks {contextRefs?: string[];title?: string;workingDir?: string;+ useWorktree?: boolean;timeoutMs?: number;}): Promise<ControlResult<Record<string, unknown>, string>>;messageSessionTask(params: {@@ -126,15 +127,20 @@ interface SessionTaskCallbacks {| { kind: 'approve' }| { kind: 'deny'; reason?: string }| { kind: 'answer'; answers: Record<string, string> }- | { kind: 'message'; text: string; idempotencyKey?: string };+ | { kind: 'message'; text: string; idempotencyKey?: string; mode?: 'queue' | 'steer' }+ | { kind: 'resume'; text?: string }+ | { kind: 'edit'; queuedMessageId: string; text: string }+ | { kind: 'withdraw'; queuedMessageId: string };}): Promise<ControlResult<Record<string, unknown>, string>>;getSessionTask(params: {callerSessionId: string;taskId: string;+ queuedMessageId?: string;}): Promise<ControlResult<{ task: unknown }, string>>;stopSessionTask(params: {callerSessionId: string;taskId: string;+ mode?: 'cancel' | 'request-stop' | 'pause';}): Promise<ControlResult<Record<string, unknown>, string>>;}@@ -289,7 +295,7 @@ function registerStartSessionTaskEntry(name: 'start_session_task',category: 'bots',description: [- 'Start one real independent Cindy Session task in the background.',+ 'Start one real independent Cindy Session task in the background. For project work, pass the actual project/worktree path in working_dir before starting. Set use_worktree=true to create and register an isolated worktree before runtime starts; failure never falls back to the shared directory; creating a worktree later in a shell does not relocate the registered Session. timeout_ms defaults to 1800000 (30 minutes), maximum 86400000 (24 hours); specify the needed budget at creation. Follow-up after timeout inherits the original budget, it does not extend it.','Proactively use this for coding implementation and medium or large work: reading/modifying a project and running checks, multi-source research, multi-file processing, or complex analysis and deliverables. Do not wait for the user to request delegation or ask permission merely to start a task. Handle short simple questions, code explanations, small snippets, and single-step work yourself unless the user explicitly requests a separate task. Respect an explicit request to work inline.','Pass the objective, constraints, known facts, relevant files, completed actions, and acceptance criteria in instruction; the task does not automatically inherit this chat. Do not duplicate its work. Review the returned result and follow up on the same task if needed.',"This never calls a Cindy Bot or any other teammate. Use send_to_agent for a bounded message to a named teammate.",@@ -299,10 +305,11 @@ function registerStartSessionTaskEntry(instruction: z.string().min(1).max(12_000),title: z.string().min(1).max(120).optional(),working_dir: z.string().min(1).max(1_024).optional(),+ use_worktree: z.boolean().optional(),context_refs: z.array(z.string().max(512)).max(32).optional(),timeout_ms: z.number().int().min(1_000).max(86_400_000).optional(),},- handler: async ({ instruction, title, working_dir, context_refs, timeout_ms }) => {+ handler: async ({ instruction, title, working_dir, use_worktree, context_refs, timeout_ms }) => {const callerSessionId = resolveLiziMcpSessionContext(sessionCtx).sessionId;if (!callerSessionId) {return errorPayload('NOT_A_BOT_SESSION', '当前调用未绑定 Cindy 伙伴任务。');@@ -313,6 +320,7 @@ function registerStartSessionTaskEntry(contextRefs: context_refs,title,workingDir: working_dir,+ ...(use_worktree === undefined ? {} : { useWorktree: use_worktree }),timeoutMs: timeout_ms,});return result.ok@@ -397,14 +405,15 @@ function registerSessionTaskControlEntries(registry.register({name: 'check_session_task',category: 'bots',- description: 'Read the current state and result of one Session task. Use only when the user asks for progress or the automatic completion return appears to be missing.',- inputShape: { task_id: z.string().min(1).max(128) },- handler: async ({ task_id }) => {+ description: 'Read state, registered working_dir, stop confirmation and your own pending queue. Optional queued_message_id returns queued/consuming/dispatched/not-found/unavailable. Queue restoration failure preserves task state and result with queue_error=QUEUE_UNAVAILABLE; dispatched means accepted into host history, not proof the model acted on it. Use only when the user asks for progress or the automatic completion return appears to be missing.',+ inputShape: { task_id: z.string().min(1).max(128), queued_message_id: z.string().min(1).max(256).optional() },+ handler: async ({ task_id, queued_message_id }) => {const callerError = requireCaller();if (callerError) return callerError;const result = await deps.sessionTasks!.getSessionTask({callerSessionId: callerSessionId()!,taskId: task_id,+ ...(queued_message_id ? { queuedMessageId: queued_message_id } : {}),});return result.ok? okPayload({@@ -420,13 +429,16 @@ function registerSessionTaskControlEntries(name: 'message_session_task',category: 'bots',description: [- 'Send a follow-up to one Session task without starting another task.',- 'Use message to add or correct instructions. Use decision or answers only when the task is waiting for that exact response.',- 'A completed task resumes in a fresh execution of the same tracked task.',+ 'Send a follow-up to one Session task without starting another task. check_session_task includes your pending queue; edit/withdraw require its queued_message_id. Only your own unconsumed messages can be changed; consuming input is rejected. Absence from the pending queue does not prove the model acted on it.',+ 'mode=queue (default) adds input for the next turn when busy. mode=steer requires a running engine with same-turn steer; it never falls back to queue. Reuse idempotency_key when retrying the same steer from this Session to avoid duplicate injection.',+ 'mode=resume releases a reversible pause on the same Session; optional message supplies new instructions, never replays the original request. Use decision or answers only for the exact pending interaction; if paused, resume first.',+ 'Ordinary queued input to a completed task starts a fresh execution of the same tracked task; mode=resume only releases a reversible pause.',].join('\n'),inputShape: {task_id: z.string().min(1).max(128),message: z.string().min(1).max(4_000).optional(),+ mode: z.enum(['queue', 'steer', 'resume', 'edit', 'withdraw']).optional(),+ queued_message_id: z.string().min(1).max(256).optional(),decision: z.enum(['approve', 'deny']).optional(),answers: z.record(z.string(), z.string()).optional(),reason: z.string().max(4_000).optional(),@@ -435,6 +447,8 @@ function registerSessionTaskControlEntries(handler: async ({task_id,message,+ mode,+ queued_message_id,decision,answers,reason,@@ -442,21 +456,37 @@ function registerSessionTaskControlEntries(}) => {const callerError = requireCaller();if (callerError) return callerError;+ if (mode === 'edit' || mode === 'withdraw') {+ if (!queued_message_id || decision || answers || (mode === 'edit' ? !message?.trim() : !!message)) {+ return errorPayload('INVALID_ARGS', 'edit requires queued_message_id and message; withdraw requires only queued_message_id.');+ }+ const result = await deps.sessionTasks!.messageSessionTask({ callerSessionId: callerSessionId()!, taskId: task_id,+ reply: mode === 'edit' ? { kind: 'edit', queuedMessageId: queued_message_id, text: message!.trim() }+ : { kind: 'withdraw', queuedMessageId: queued_message_id } });+ return result.ok ? okPayload({ action: 'message_session_task', task_id, session_id: result.childSessionId,+ queued_message_id: result.queuedMessageId, delivery: result.delivery, resumed: false }) : errorPayload(result.errorCode, result.message);+ }+ if (queued_message_id) return errorPayload('INVALID_ARGS', 'queued_message_id requires edit or withdraw mode.');const choices =Number(Boolean(message?.trim())) +Number(Boolean(decision)) +Number(Boolean(answers));- if (choices !== 1) {+ if ((mode === 'resume' ? Boolean(decision || answers) : choices !== 1)+ || (mode === 'steer' && !message?.trim())+ || (mode && mode !== 'queue' && Boolean(decision || answers))) {return errorPayload('INVALID_ARGS','Provide exactly one of message, decision, or answers.',);}- const reply = message?.trim()+ const reply = mode === 'resume'+ ? { kind: 'resume' as const, ...(message?.trim() ? { text: message.trim() } : {}) }+ : message?.trim()? {kind: 'message' as const,text: message.trim(),idempotencyKey: idempotency_key,+ ...(mode ? { mode: mode as 'queue' | 'steer' } : {}),}: decision === 'approve'? { kind: 'approve' as const }@@ -475,6 +505,9 @@ function registerSessionTaskControlEntries(session_id: result.childSessionId,resumed: result.resumed,...(result.queued === undefined ? {} : { queued: result.queued }),+ ...(result.delivery === undefined ? {} : { delivery: result.delivery }),+ ...(result.queuedMessageId === undefined ? {} : { queued_message_id: result.queuedMessageId }),+ ...(result.control === undefined ? {} : { control: result.control }),}): errorPayload(result.errorCode, result.message);},@@ -483,20 +516,22 @@ function registerSessionTaskControlEntries(registry.register({name: 'stop_session_task',category: 'bots',- description: 'Stop one running Session task and its child tasks. Use only when the user asks to stop it or continuing would be unsafe.',- inputShape: { task_id: z.string().min(1).max(128) },- handler: async ({ task_id }) => {+ description: 'mode=cancel (default) terminates the task. mode=request-stop requests graceful stop of the current turn only. mode=pause holds the same task and pending input until message_session_task(mode=resume); pausing/unconfirmed is not proof the engine stopped. Only control tasks owned by your teammate.',+ inputShape: { task_id: z.string().min(1).max(128), mode: z.enum(['cancel', 'request-stop', 'pause']).optional() },+ handler: async ({ task_id, mode }) => {const callerError = requireCaller();if (callerError) return callerError;const result = await deps.sessionTasks!.stopSessionTask({callerSessionId: callerSessionId()!,taskId: task_id,+ ...(mode ? { mode } : {}),});return result.ok? okPayload({action: 'stop_session_task',task_id,session_id: result.childSessionId,+ ...(result.control === undefined ? {} : { control: result.control }),}): errorPayload(result.errorCode, result.message);},diff --git a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.tsindex 8af9dda933..1336f5e55b 100644--- a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts+++ b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts@@ -67,6 +67,9 @@ export const TEAMMATE_CONTROL_GUIDANCE = ['Use `get_teammate_state` to inspect your current profile, stable chat, configured model candidates, memory switch and capability references. Candidates and selected references are not proof of the model or tools running this turn; the live runtime and registered tools are authoritative.','The references arrays contain optional external grants, not the shared teammate guide or your personal Skill shelf. Empty references do not mean you have no Skills. Report the preloaded shared guide separately; personal Skill storage and learning depend on the current runtime mounting your own shelf, as described in the teammate guide.','Use `update_teammate_profile` when the user asks to change your name, introduction, identity or your own model selection. Read the current version first and patch only the requested fields. For modelChain, first read `get_app_default_model` for enabled route ids and supported effort/Fast settings; supply the complete ordered chain (1–5 routes), preserving existing candidates unless the user asks to replace them. Set modelChain to null to remove your override and follow the application default again. This saves only your profile through the same settings service, persists across restarts, and applies next turn; it never changes the application default, other teammates, personal Skills, memory or chat history. A next-turn save is not proof of the model running this turn.',+ 'For project work, set working_dir to the actual project and use_worktree=true for isolation before starting. check_session_task returns the registered directory. Shell cd/worktree creation does not relocate a Session. timeout_ms defaults to 30 minutes and supports up to 24 hours at creation; terminal follow-up inherits the original budget. Do not claim an existing deadline was extended without a verified host response.',+ 'message_session_task returns queued_message_id for queued or steered input. check_session_task exposes only your own queue; optionally query queued_message_id for queued/consuming/dispatched/not-found/unavailable; queue restore errors preserve task results and cannot prove a message is missing. Dispatched means accepted into host history, not proof of model action. Use mode=edit with message or mode=withdraw for your own unconsumed item; consuming input cannot be edited or withdrawn.',+ 'Control your own background tasks with `message_session_task` (mode=queue by default, mode=steer for same-turn input, mode=resume for a reversible pause) and `stop_session_task` (mode=cancel by default, request-stop for a graceful stop request, pause to hold execution and queued input). General control tools are not part of the teammate toolset. A successful queue receipt is not a steer, and pausing/requested/unconfirmed is not proof the engine stopped. Check the returned control state; unsupported engines fail explicitly. Pause preserves the same task and Session, holds timers and automatic input, and resumes without replaying completed work. If paused, resume without a message before answering a pending interaction. Only tasks owned by your teammate are controllable.','Use `get_capabilities` for application features and UI guidance. It describes the product, not a permission grant or proof that every feature is available here. Use the matching live tool to act, and verify its result before claiming success.',].join('\n');diff --git a/packages/lizi-mcps/src/xdt-helper/capabilities.ts b/packages/lizi-mcps/src/xdt-helper/capabilities.tsindex 6e638d2c5b..ef700662c4 100644--- a/packages/lizi-mcps/src/xdt-helper/capabilities.ts+++ b/packages/lizi-mcps/src/xdt-helper/capabilities.ts@@ -92,6 +92,7 @@ export const CAPABILITIES: readonly CapabilityEntry[] = ['agent 可观察任意本机会话队列与运行状态,并控制自己投递的队列消息、same-turn 插话或请求优雅停止。',detail: ['【入口】cindy_helper 的 history 类 list_sessions / list_session_queue 提供 queuedCount、队列位置、来源、入队时间、正文摘要与 consuming 状态;control 类提供 update_session_queued_message、cancel_session_queued_message、steer_session、stop_session_turn、get_session_runtime。',+ '【伙伴入口】伙伴不挂载通用 control 类。只管理自己拥有的后台任务:message_session_task 的 queue / steer / resume 分别表示排队、同轮插话、恢复暂停;stop_session_task 的 cancel / request-stop / pause 分别表示取消任务、请求当前轮停止、保留任务与队列的可恢复暂停。check_session_task 的 control 区分 pausing / paused;requested 或 unconfirmed 不能当作已停。不支持的引擎明确返回失败。','【队列所有权】只能修改或撤回当前调用 session 自己通过 send_to_session 投递、且尚未进入 consuming 的消息;Orca、scheduler、用户或其它 session 的消息都会 fail-closed 拒绝。Orca worker 队列控制与这里复用同一底层生命周期实现。','【插话】steer_session 只对正在运行且支持 same-turn steer 的 session 生效,在 provider 的下一个输入间隙注入当前 turn;若 turn 已结束会明确失败,不会退化成下一 turn。','【停止】stop_session_turn 是请求式优雅停止:当前并行工具全部收尾后才发送 provider 软中断;不关闭 transport、不重建 session、不硬杀进程,超时未确认会返回 unconfirmed。',diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.tsindex c5691f59cd..05f8df5d7b 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts@@ -150,6 +150,19 @@ function latestToolResultContent(request: Record<string, unknown>): string {function scriptedAnthropicTurn(requestBody: string): string {const toolResultCount = countToolResults(requestBody);+ if (requestBody.includes('exercise task control modes')) {+ const calls = [+ { name: 'message_session_task', input: { task_id: 'task-fixture', mode: 'steer', message: 'new direction' } },+ { name: 'stop_session_task', input: { task_id: 'task-fixture', mode: 'pause' } },+ { name: 'message_session_task', input: { task_id: 'task-fixture', mode: 'resume' } },+ { name: 'message_session_task', input: { task_id: 'task-fixture', mode: 'edit', queued_message_id: 'mine', message: 'revised' } },+ { name: 'message_session_task', input: { task_id: 'task-fixture', mode: 'withdraw', queued_message_id: 'mine' } },+ { name: 'stop_session_task', input: { task_id: 'task-fixture', mode: 'request-stop' } },+ ];+ const call = calls[toolResultCount];+ return call ? anthropicToolTurn(toolResultCount + 1, call.name, call.input)+ : anthropicTextTurn(5, 'Task controls complete');+ }if (requestBody.includes('multi command MCP workflow')) {const turns: Array<{ name: string; input: Record<string, unknown> }> = [{ name: 'cindy_mcp_list_tools', input: {} },@@ -317,6 +330,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pconst contactsLookupCalls: Array<{ query: string }> = [];const agentMessageCalls: Array<Record<string, unknown>> = [];const sessionTaskCalls: Array<Record<string, unknown>> = [];+ const taskControlCalls: Array<{ name: string; args: unknown }> = [];const botMemoryCalls: Array<Record<string, unknown>> = [];// 记录假 MCP server 收到的请求 URL —— 断言真 pi(经 cindy-bridge fetch)把// host 下发的 `?session=<id>` 原样带到每个 MCP 请求上(orca 身份路由的 pi 侧半)。@@ -622,9 +636,12 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pname,{description: name,- inputSchema: { task_id: z.string() },- },- async () => ({ content: [{ type: 'text', text: "OK" }] }),+ inputSchema: { task_id: z.string(), mode: z.string().optional(), message: z.string().optional(), queued_message_id: z.string().optional() },+ },+ async (args) => {+ taskControlCalls.push({ name, args });+ return { content: [{ type: 'text', text: 'OK' }] };+ },);}} else if (isMemory) {@@ -1010,6 +1027,27 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p},);+ it('passes control modes through the real Pi facade and permission identity', { timeout: 90_000 }, async () => {+ taskControlCalls.length = 0;+ const permissions: Array<{ toolName: string; input: unknown }> = [];+ const { requests } = await runOneTurn('ask', async (req) => {+ if (req.kind === 'permission') permissions.push({ toolName: req.toolName, input: req.input });+ return { kind: 'permission', behavior: 'allow' };+ }, 'local-multi', 'exercise task control modes');+ expect(taskControlCalls).toEqual([+ { name: 'message_session_task', args: { task_id: 'task-fixture', mode: 'steer', message: 'new direction' } },+ { name: 'stop_session_task', args: { task_id: 'task-fixture', mode: 'pause' } },+ { name: 'message_session_task', args: { task_id: 'task-fixture', mode: 'resume' } },+ { name: 'message_session_task', args: { task_id: 'task-fixture', mode: 'edit', queued_message_id: 'mine', message: 'revised' } },+ { name: 'message_session_task', args: { task_id: 'task-fixture', mode: 'withdraw', queued_message_id: 'mine' } },+ { name: 'stop_session_task', args: { task_id: 'task-fixture', mode: 'request-stop' } },+ ]);+ expect(permissions).toEqual(taskControlCalls.map(({ name, args }) => ({+ toolName: `mcp__cindy_helper__${name}`, input: args,+ })));+ expect(requests).toHaveLength(7);+ });+it('starts a typed independent Session task without selecting a Bot',{ timeout: 90_000 },diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex 887c7a0432..91dfc068a9 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -3182,6 +3182,7 @@ class CindyMcpGateway {instruction: { type: 'string', minLength: 1, maxLength: 12000 },title: { type: 'string', minLength: 1, maxLength: 120 },working_dir: { type: 'string', minLength: 1, maxLength: 1024 },+ use_worktree: { type: 'boolean' },context_refs: { type: 'array', items: { type: 'string' }, maxItems: 32 },timeout_ms: { type: 'integer', minimum: 1000, maximum: 86400000 },},@@ -3219,7 +3220,8 @@ class CindyMcpGateway {label: 'Check Session task',description: 'Read one Session task state when the user asks for progress or automatic completion appears to be missing. Do not poll.',parameters: { type: 'object',- properties: { task_id: { type: 'string', minLength: 1, maxLength: 128 } },+ properties: { task_id: { type: 'string', minLength: 1, maxLength: 128 },+ queued_message_id: { type: 'string', minLength: 1, maxLength: 256 } },required: ['task_id'],additionalProperties: false,},@@ -3232,11 +3234,13 @@ class CindyMcpGateway {pi.registerTool({name: CINDY_MESSAGE_SESSION_TASK_TOOL,label: 'Message Session task',- description: 'Add instructions to the same Session task, or answer the exact approval/question it is waiting for. A terminal task resumes under the same task ID.',+ description: 'Queue instructions (default), steer the running turn with mode=steer, or release a reversible pause with mode=resume. Steer never falls back to queue. If paused, resume before answering pending interactions. A terminal task with ordinary input starts a fresh execution under the same task ID.',parameters: {type: 'object',properties: {task_id: { type: 'string', minLength: 1, maxLength: 128 },+ mode: { type: 'string', enum: ['queue', 'steer', 'resume', 'edit', 'withdraw'] },+ queued_message_id: { type: 'string', minLength: 1, maxLength: 256 },message: { type: 'string', minLength: 1, maxLength: 4000 },decision: { type: 'string', enum: ['approve', 'deny'] },answers: { type: 'object', additionalProperties: { type: 'string' } },@@ -3255,10 +3259,13 @@ class CindyMcpGateway {pi.registerTool({name: CINDY_STOP_SESSION_TASK_TOOL,label: 'Stop Session task',- description: 'Stop one running Session task and its child tasks.',+ description: 'mode=cancel (default) terminates the task; request-stop requests graceful stop only; pause holds the same task and queued input until explicit resume. Check returned control state: pausing/unconfirmed is not stopped.',parameters: {type: 'object',- properties: { task_id: { type: 'string', minLength: 1, maxLength: 128 } },+ properties: {+ task_id: { type: 'string', minLength: 1, maxLength: 128 },+ mode: { type: 'string', enum: ['cancel', 'request-stop', 'pause'] },+ },required: ['task_id'],additionalProperties: false,},