Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): keep delegated task coordination out of public chat
zqchrisf4915ea83d33
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex cd52e6bbb8..21923f76c2 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -6256,3 +6256,21 @@ describe('Agent Island device sessions', () => {});});});++it('does not sound or mark attention for internal coordination completion, but surfaces a failure', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn(() => true);+ const playSound = vi.fn(() => true);+ const service = new AgentIslandService({ getMainWindow: () => null, nativeHost: { failed: false, publish, playSound } });+ syncEnabledForTest(service, publish);+ service.setSoundSettings({ enabled: true, sounds: { ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,+ complete: customSound('complete.wav'), error: customSound('error.wav') } });+ const meta = { sessionId: 'coordination', agentKind: 'codex' as const };+ service.handleAgentEvent(meta, { type: 'status', source: 'codex', data: { isRunning: true } });+ playSound.mockClear();+ service.handleAgentEvent(meta, { ...doneEvent(), agentMeta: { botTaskCoordination: true, botPrivateReply: true } });+ expect(playSound).not.toHaveBeenCalled();+ expect(service.getSessionActivitySnapshot(meta.sessionId)?.attention).not.toBe(true);+ service.handleAgentEvent(meta, terminalErrorEvent('User action required'));+ expect(playSound).toHaveBeenCalledWith(customSound('error.wav'));+});diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex ad187eacb1..6a1ce523d8 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -1455,7 +1455,8 @@ export class AgentIslandService {private isCompletionEventSilenced(sessionId: string, event: AgentEvent): boolean {if (!isCompletionDoneEvent(event)) return false;- return event.turnOrigin?.surface === 'im' || this.silencedSessionRunIds.has(sessionId);+ return event.agentMeta?.botTaskCoordination === true+ || event.turnOrigin?.surface === 'im' || this.silencedSessionRunIds.has(sessionId);}private hadAttentionBeforeSilencedRun(sessionId: string): boolean {diff --git a/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts b/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.tsindex 2ce7e21951..10f59bb00a 100644--- a/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts+++ b/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts@@ -3,7 +3,7 @@ import { queueItemVisibleText } from '@cindy/maker-shared/queue';const HOOK_SCHEDULE_ID_PREFIX = 'hook:';-const GUEST_HIDDEN_META_KEYS = ['agentFacingWireContent', 'sourceDevice', 'sourcePlugin', 'sourceGroup'] as const;+const GUEST_HIDDEN_META_KEYS = ['botTaskCoordinationInput', 'agentFacingWireContent', 'sourceDevice', 'sourcePlugin', 'sourceGroup'] as const;function redactOriginForSharedGuest(origin: Record<string, unknown>): Record<string, unknown> | null {if (origin.kind === 'session') return { kind: 'session' };@@ -77,10 +77,11 @@ export function redactQueueItemForSharedGuest<T>(item: T): T {if (!item || typeof item !== 'object' || Array.isArray(item)) return item;const original = item as Record<string, unknown>;let entry = original;- if ('sourceDevice' in entry || 'sourcePlugin' in entry) {+ if ('sourceDevice' in entry || 'sourcePlugin' in entry || 'botTaskCoordination' in entry) {entry = { ...entry };delete entry.sourceDevice;delete entry.sourcePlugin;+ delete entry.botTaskCoordination;}const origin = entry.origin;if (!origin || typeof origin !== 'object' || Array.isArray(origin)) {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 7f5e499c48..537e027963 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -3401,6 +3401,20 @@ describe('Bots list unread projection', () => {expect((await getBotRemoteResourceSource('bot-1')).lastReplyAt).toBe(0);});+ it('keeps hidden coordination inputs and actions out of unread and preview after history reload', async () => {+ const sessionId = await canonicalFor('bot-1');+ insertMessage(sessionId, { id: 'result', role: 'assistant', content: 'Visible final result', createdAt: 1000 });+ insertMessage(sessionId, { id: 'coordination', role: 'user', content: '[UI_ACTION_TRIGGER]File ownership agreement', createdAt: 2000,+ agentMeta: { origin: { kind: 'session', senderSessionId: 'child' }, botTaskCoordinationInput: { delegationId: 'task', senderSessionId: 'child', runSequence: 1 } } });+ insertMessage(sessionId, { id: 'audit-tool', role: 'tool_use', content: { toolName: 'read', input: {} }, createdAt: 3000 });+ expect(await unreadFor('bot-1', { 'bot-1': 1500 })).toBe(0);+ const resource = await getBotRemoteResourceSource('bot-1');+ expect(resource.lastReplyAt).toBe(1000);+ expect(resource.lastMessagePreview).toBe('Visible final result');+ insertMessage(sessionId, { id: 'next-result', role: 'assistant', content: 'Requested update', createdAt: 4000 });+ expect(await unreadFor('bot-1', { 'bot-1': 1500 })).toBe(1);+ });+it('counts only replies that landed after the read position', async () => {const sessionId = await canonicalFor('bot-1');insertMessage(sessionId, {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 70c817221a..ccaf2e8a07 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@@ -1752,6 +1752,44 @@ describe('AgentInputCoordinator send transaction', () => {expect(projection.recovery).toBeNull();});+ it('restores internal coordination through the durable queue and gives accepted human steering ownership', async () => {+ const h = createHarness();+ const sid = 'coordination';+ await h.coordinator.ensureQueueRestored(sid);+ h.setRunning(true);+ const receipt = { delegationId: 'delegation', senderSessionId: 'child', runSequence: 1 };+ h.coordinator.enqueue(sid, makeItem('internal', '[UI_ACTION_TRIGGER]File agreement', {+ botTaskCoordination: receipt, agentOmitsTriggerPrefix: true,+ autoReviewUserText: { kind: 'delegated-continuation' },+ }));+ await flush();+ const snapshot = JSON.parse(JSON.stringify(h.persistQueueSnapshot.mock.calls.at(-1)?.[1] ?? []));+ expect(snapshot[0].botTaskCoordination).toEqual(receipt);+ expect(h.coordinator.getProjection(sid).pendingQueue[0]).not.toHaveProperty('botTaskCoordination');+ const restarted = createHarness();+ restarted.setLoadQueueSnapshot(async () => snapshot);+ await restarted.coordinator.ensureQueueRestored(sid);+ expect(restarted.coordinator.isActiveTaskCoordination(sid)).toBe(false);+ restarted.sendToAgent.mockImplementationOnce(async (_id, message, _create, opts) => {+ expect(restarted.coordinator.isActiveTaskCoordination(sid)).toBe(true);+ expect(message).toMatchObject({ content: expect.stringContaining('Internal task coordination') });+ expect(message).toMatchObject({ content: expect.stringContaining('File agreement') });+ expect(opts?.persistUserMessage?.content).toBe('[UI_ACTION_TRIGGER]File agreement');+ expect(opts?.persistUserMessage?.botTaskCoordination).toEqual(receipt);+ restarted.setRunning(true);+ return sendSuccess();+ });+ restarted.coordinator.resume(sid);+ await flush();+ expect(restarted.sendToAgent).toHaveBeenCalledOnce();+ expect(restarted.coordinator.isActiveTaskCoordination(sid)).toBe(true);+ await restarted.coordinator.steer(sid, makeItem('human', 'Please explain the result'));+ expect(restarted.coordinator.isActiveTaskCoordination(sid)).toBe(false);+ restarted.setRunning(false);+ restarted.coordinator.onTurnEvent(sid, 'done');+ expect(restarted.coordinator.isActiveTaskCoordination(sid)).toBe(false);+ });+it('attributes synchronous provider output to its active input and clears after completion', async () => {const h = createHarness();const sid = 'private-reply-attribution';diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTaskCoordination.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTaskCoordination.test.tsnew file mode 100644index 0000000000..37ee3e2212--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTaskCoordination.test.ts@@ -0,0 +1,122 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { assertBotTaskCoordination, classifySessionMessagePurpose, coordinationInput, readBotTaskCoordination } from '../botTaskCoordination';+import { buildMakerUserMessage, sanitizeQueuedMessageForPersistence, type AgentInputQueuedMessage } from '../../../shared/agentInputQueue';+import { redactMessageOriginForSharedGuest, redactQueueItemForSharedGuest } from '../../device-link/sharedTaskMessageOrigin';+import { rebuildSessionQueueItem } from '../sessionControlService';+import { projectCoordinationOutput } from '../coordinationOutput';+import type { AgentEvent } from '@cindy/maker-core';+import { stripMainOnlySendOpts } from '../mobileClientPromptNote';++const h = vi.hoisted(() => ({ db: null as ReturnType<typeof drizzle> | null }));+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: h.db }) }));+let db: Database.Database;+const receipt = { delegationId: 'delegation', senderSessionId: 'child', runSequence: 2 };+beforeEach(() => {+ db = new Database(':memory:');+ h.db = drizzle(db);+ db.exec(`+ CREATE TABLE bot_delegations (id TEXT, child_session_id TEXT, requesting_bot_id TEXT, parent_session_id TEXT, run_sequence INTEGER);+ CREATE TABLE bot_profiles (id TEXT, canonical_session_id TEXT, status TEXT);+ CREATE TABLE bot_session_links (bot_id TEXT, session_id TEXT, role TEXT, archived_at INTEGER);+ CREATE TABLE sessions (id TEXT, status TEXT);+ INSERT INTO bot_delegations VALUES ('delegation', 'child', 'bot', 'parent', 2);+ INSERT INTO bot_profiles VALUES ('bot', 'parent', 'active');+ INSERT INTO bot_session_links VALUES ('bot', 'parent', 'canonical', NULL);+ INSERT INTO sessions VALUES ('child', 'active');+ `);+});+afterEach(() => db.close());++it('defaults only the verified delegated child to coordination, with an explicit visible escape', async () => {+ expect(await classifySessionMessagePurpose({ senderSessionId: 'child', targetSessionId: 'parent' })).toEqual({ coordination: receipt, delegatedContinuation: true });+ expect(await classifySessionMessagePurpose({ senderSessionId: 'child', targetSessionId: 'parent', purpose: 'user-visible' })).toEqual({ coordination: null, delegatedContinuation: true });+ expect(await classifySessionMessagePurpose({ senderSessionId: 'ordinary', targetSessionId: 'parent' })).toEqual({ coordination: null, delegatedContinuation: false });+ expect(await classifySessionMessagePurpose({ senderSessionId: 'child', targetSessionId: 'ordinary' })).toEqual({ coordination: null, delegatedContinuation: false });+ expect(await classifySessionMessagePurpose({ senderSessionId: 'child' })).toEqual({ coordination: null, delegatedContinuation: false });+ await expect(classifySessionMessagePurpose({ senderSessionId: 'ordinary', targetSessionId: 'parent', purpose: 'coordination' })).rejects.toThrow('delegated task');+});+it.each([+ "UPDATE bot_delegations SET parent_session_id = 'group-lane'",+ "UPDATE bot_profiles SET canonical_session_id = 'replacement'",+ "UPDATE bot_profiles SET status = 'disabled'",+ "UPDATE bot_session_links SET role = 'history'",+ 'UPDATE bot_session_links SET archived_at = 1',+ "UPDATE sessions SET status = 'archived'",+])('rejects a mismatched or retired relationship: %s', async sql => {+ db.exec(sql);+ expect(await readBotTaskCoordination('child', 'parent')).toBeNull();+ await expect(assertBotTaskCoordination('parent', receipt)).rejects.toThrow('changed');+});+it('revalidates the execution on restored queue dispatch', async () => {+ await expect(assertBotTaskCoordination('parent', JSON.parse(JSON.stringify(receipt)))).resolves.toBeUndefined();+ db.exec('UPDATE bot_delegations SET run_sequence = 3');+ await expect(assertBotTaskCoordination('parent', receipt)).rejects.toThrow('changed');+});+it('keeps the source and body durable, but puts the coordination instruction only in model input', () => {+ const input = coordinationInput('File ownership agreement', receipt);+ const item = { ...input, text: input.persistedContent, agentOmitsTriggerPrefix: true,+ clientId: 'coordination', origin: { kind: 'session', senderSessionId: 'child', displayText: input.message },+ chatMessage: { clientId: 'coordination', role: 'user', content: input.persistedContent }, createOpts: {},+ } as unknown as AgentInputQueuedMessage;+ const restored = JSON.parse(JSON.stringify(sanitizeQueuedMessageForPersistence(item)));+ expect(restored.botTaskCoordination).toEqual(receipt);+ expect(restored.text).toBe('[UI_ACTION_TRIGGER]File ownership agreement');+ expect(restored.persistedContent).not.toContain('Internal task coordination');+ const wire = buildMakerUserMessage(restored);+ expect(wire).toMatchObject({ content: expect.stringContaining('Internal task coordination') });+ expect(wire).toMatchObject({ content: expect.stringContaining('File ownership agreement') });+ expect(JSON.stringify(wire)).not.toContain('[UI_ACTION_TRIGGER]');+ expect(redactQueueItemForSharedGuest(restored)).not.toHaveProperty('botTaskCoordination');+ expect(redactMessageOriginForSharedGuest({ botTaskCoordinationInput: receipt })).toEqual({});+});+it('strips forged receipts from direct renderer/device-link sends', () => {+ expect(stripMainOnlySendOpts({ persistUserMessage: { clientId: 'x', content: 'Hello', botTaskCoordination: receipt } }))+ .toEqual({ persistUserMessage: { clientId: 'x', content: 'Hello' } });+});++it('retains hidden persistence and routing when the sending task edits its queued coordination', () => {+ const item = { clientId: 'edit', text: '[UI_ACTION_TRIGGER]Old agreement', persistedContent: '[UI_ACTION_TRIGGER]Old agreement',+ botTaskCoordination: receipt, agentOmitsTriggerPrefix: true, chatMessage: { role: 'user' },+ origin: { kind: 'session', senderSessionId: 'child', displayText: 'Old agreement' },+ } as unknown as AgentInputQueuedMessage;+ const edited = rebuildSessionQueueItem(item, 'Updated agreement');+ expect(edited.persistedContent).toBe('[UI_ACTION_TRIGGER]Updated agreement');+ expect(edited.botTaskCoordination).toEqual(receipt);+ expect(buildMakerUserMessage(edited)).toMatchObject({ content: expect.stringContaining('Updated agreement') });+});+it.each<AgentEvent['type']>(['interaction_request', 'interaction_dismissed', 'error', 'tool_use', 'tool_result', 'account_usage'])('does not suppress an attention/action event: %s', type => {+ const event: AgentEvent = { type, source: 'codex', data: { requestId: 'interaction', kind: 'ask_user_question', questions: [] } };+ expect(projectCoordinationOutput(event, true)).toBe(event);+});++it('uses the registered host entry for both quiet and explicitly visible delegated sends', async () => {+ const source = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8').replace(/\r\n/g, '\n');+ const start = source.indexOf(' sendToSession: async (params) => {');+ const end = source.indexOf(' enableOrca:', start);+ expect(start).toBeGreaterThan(0);+ const code = ts.transpileModule('return ({' + source.slice(start, end) + '}).sendToSession;', {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },+ }).outputText;+ const send = vi.fn(async (params: unknown) => params);+ let currentOwner = true;+ const dispatch = new Function('captureDataOwnerBroadcastScope', 'isDataOwnerBroadcastScopeCurrent',+ 'classifySessionMessagePurpose', 'coordinationInput', 'sendToSessionInternal', code)(+ () => 'owner', () => currentOwner, classifySessionMessagePurpose, coordinationInput, send);+ await dispatch({ dispatcherSessionId: 'child', targetSessionId: 'parent', message: 'Agreement' });+ expect(send).toHaveBeenLastCalledWith(expect.objectContaining({ forceQueue: true, botTaskCoordination: receipt,+ persistedContent: '[UI_ACTION_TRIGGER]Agreement', autoReviewUserText: { kind: 'delegated-continuation' } }));+ await dispatch({ dispatcherSessionId: 'child', targetSessionId: 'parent', message: 'Requested result', messagePurpose: 'user-visible' });+ expect(send).toHaveBeenLastCalledWith(expect.objectContaining({ message: 'Requested result', autoReviewUserText: { kind: 'delegated-continuation' } }));+ expect(send.mock.calls.at(-1)?.[0]).not.toHaveProperty('botTaskCoordination');+ await dispatch({ dispatcherSessionId: 'ordinary', targetSessionId: 'parent', message: 'Ordinary task message' });+ expect(send).toHaveBeenLastCalledWith({ dispatcherSessionId: 'ordinary', targetSessionId: 'parent', message: 'Ordinary task message' });+ currentOwner = false;+ const count = send.mock.calls.length;+ expect(await dispatch({ dispatcherSessionId: 'child', targetSessionId: 'parent', message: 'Agreement' })).toMatchObject({ ok: false });+ expect(send).toHaveBeenCalledTimes(count);+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex 7c8472bebd..e915b6ed98 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -2626,12 +2626,14 @@ describe('message source notes', () => {text: 'hello',sourceDevice: { deviceId: 'forged', platform: 'mobile' },sourcePlugin: { pluginId: 'forged' },+ botTaskCoordination: { delegationId: 'forged', senderSessionId: 'child', runSequence: 1 },agentOmitsTriggerPrefix: true,} as unknown as AgentInputQueuedMessage;const local = stampTrustedDeviceLinkQueuedOrigin(forged, false, phone);expect(local).not.toHaveProperty('sourceDevice');expect(local).not.toHaveProperty('sourcePlugin');expect(local).not.toHaveProperty('agentOmitsTriggerPrefix');+ expect(local).not.toHaveProperty('botTaskCoordination');expect(stampTrustedDeviceLinkQueuedOrigin(forged, true)).not.toHaveProperty('sourceDevice');expect(stampTrustedDeviceLinkQueuedOrigin(forged, true, phone).sourceDevice).toEqual(phone);expect(forged.sourceDevice).toEqual({ deviceId: 'forged', platform: 'mobile' });@@ -3418,3 +3420,18 @@ describe('session-agent-switch handoff injection', () => {expect(sent.content).toContain('OVERFLOW-HANDOFF');});});++it('persists coordination audit metadata and dispatches the model without a prompt notification', async () => {+ const previewUserPrompt = vi.fn();+ const receipt = { delegationId: 'delegation', senderSessionId: 'child', runSequence: 1 };+ const { deps, session } = createDeps({ previewUserPrompt });+ const transaction = createMakerSendTransaction(deps);+ await transaction.sendToAgentAccepted('session-1', 'Internal wire input', undefined, {+ persistUserMessage: { clientId: 'coordination', content: '[UI_ACTION_TRIGGER]Coordination', botTaskCoordination: receipt },+ });+ expect(session.send).toHaveBeenCalledOnce();+ expect(previewUserPrompt).not.toHaveBeenCalled();+ expect(vi.mocked(deps.createDbMessage).mock.calls[0]?.[1]).toMatchObject({+ role: 'user', content: '[UI_ACTION_TRIGGER]Coordination', agentMeta: { botTaskCoordinationInput: receipt },+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.tsindex 63c75ee1bd..c7b10dc830 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts@@ -303,6 +303,7 @@ function harness() {agentInputCoordinatorHolder: {getActiveInputClientId: vi.fn((): string | null => null),getActiveInputClientIds: vi.fn((): string[] => []),+ isActiveTaskCoordination: vi.fn(() => false),getQueueControlSnapshot: vi.fn(() => ({ pendingQueue: [] as unknown[] })),onTurnEvent: vi.fn(),noteSuppressedTerminalError: vi.fn(),@@ -399,6 +400,49 @@ function ordered(...names: string[]) {}describe('production Session event pipeline', () => {+ it('delivers coordination actions without public prose, then preserves ordinary and completion replies', async () => {+ const h = harness();+ h.deps.agentInputCoordinatorHolder.isActiveTaskCoordination.mockReturnValue(true);+ h.deps.agentInputCoordinatorHolder.getActiveInputClientId.mockReturnValue('coordination');+ try {+ h.emit(event('text', { text: 'Internal file ownership agreement', isFinal: true }));+ h.emit(event('text', { text: 'Internal standalone' }, { standaloneText: true }));+ h.emit(event('thinking', { text: 'Internal reasoning' }));+ expect(effects.fn('onAssistantTextEvent')).not.toHaveBeenCalled();+ expect(effects.fn('onStandaloneTextEvent')).not.toHaveBeenCalled();+ expect(h.deps.broadcastToAllWindows).not.toHaveBeenCalled();+ h.emit(event('tool_use', { id: 'tool', name: 'read', input: {} }));+ expect(effects.fn('onToolUseEvent')).toHaveBeenCalledOnce();+ h.deps.agentInputCoordinatorHolder.onTurnEvent.mockImplementation(() => {+ h.deps.agentInputCoordinatorHolder.isActiveTaskCoordination.mockReturnValue(false);+ });+ h.emit(event('done', { result: 'Internal acknowledgement', finalText: 'Internal acknowledgement' }));+ expect(h.deps.broadcastToAllWindows).toHaveBeenCalledWith('maker:event', expect.objectContaining({+ event: expect.objectContaining({ type: 'done', data: expect.objectContaining({ result: '', finalText: '' }),+ agentMeta: expect.objectContaining({ botPrivateReply: true, botTaskCoordination: true }) }),+ }));+ expect(JSON.stringify(h.deps.broadcastToAllWindows.mock.calls)).not.toContain('Internal acknowledgement');+ h.deps.agentInputCoordinatorHolder.getActiveInputClientId.mockReturnValue('bot-delegation-completion:result');+ h.emit(event('text', { text: 'User requested final result', isFinal: true }));+ expect(effects.fn('onAssistantTextEvent')).toHaveBeenCalledOnce();+ } finally { await h.dispose(); }+ });++ it('keeps terminal failures and runtime recovery notices visible during coordination', async () => {+ const h = harness();+ h.deps.redactEventForRenderer.mockImplementation(value => value);+ h.deps.agentInputCoordinatorHolder.isActiveTaskCoordination.mockReturnValue(true);+ h.deps.agentInputCoordinatorHolder.getActiveInputClientId.mockReturnValue('coordination');+ try {+ h.emit(event('error', { message: 'User action required' }));+ expect(h.deps.broadcastToAllWindows).toHaveBeenCalledWith('maker:event', expect.objectContaining({+ event: expect.objectContaining({ type: 'error', data: expect.objectContaining({ message: 'User action required' }) }),+ }));+ h.emit(event('text', { text: 'Recovery requires attention' }, { runtimeRecovery: true }));+ expect(effects.fn('onAssistantTextEvent')).toHaveBeenCalledOnce();+ } finally { await h.dispose(); }+ });+it('suppresses scheduled content before persistence and delivery while preserving unrelated replies', async () => {const h = harness();const close = beginQuietScheduledOutput('check', 'check-run');diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex 88173aae76..860ee0313c 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -257,6 +257,7 @@ export interface AgentInputSendOpts {/** Session reservation 时回调本轮 vendor generation;必须在 send 返回前绑定 leftover。 */onVendorTurnReserved?: (generation: number) => void;persistUserMessage?: {+ botTaskCoordination?: AgentInputQueuedMessage['botTaskCoordination'];sharedTaskAuthor?: AgentInputQueuedMessage['sharedTaskAuthor'];/** 插件来源:写入 agentMeta.sourcePlugin 并生成 `[消息来源]`(不传给 maker-core)。 */sourcePlugin?: AgentInputQueuedMessage['sourcePlugin'];@@ -1212,6 +1213,14 @@ export class AgentInputCoordinator {return active.latestSteeringClientId ?? active.item?.clientId ?? null;}+ /** Only a main-owned accepted receipt can silence this turn. Human steering restores visibility. */+ isActiveTaskCoordination(sessionId: string, vendorGeneration?: number): boolean {+ const active = this.states.get(sessionId)?.activeTurn;+ return !!active?.item?.botTaskCoordination && !active.latestSteeringClientId+ && (vendorGeneration === undefined || active.vendorTurnGeneration === null+ || vendorGeneration === active.vendorTurnGeneration);+ }+/** Authority follows the active input, never pending steering or cumulative reply attribution. */getAcceptedInputProvenance(sessionId: string): {clientId: string; autoResume?: boolean; retrySourceClientId?: string; authoredText?: string; originKind?: string;@@ -4298,6 +4307,7 @@ export class AgentInputCoordinator {delete projected[HOST_ONLY_AGENT_PREFIX];delete projected.hostAcceptedAtMs;delete projected.autoReviewUserText;+ delete projected.botTaskCoordination;delete projected.fromDeviceLinkClient;// Main-only wire-assembly hint; renderers mask rows from `text` alone.delete projected.agentOmitsTriggerPrefix;@@ -4881,6 +4891,7 @@ export class AgentInputCoordinator {...(head.fromDeviceLinkClient ? { fromDeviceLinkClient: true } : {}),...(head.sourceDevice ? { sourceDevice: head.sourceDevice } : {}),persistUserMessage: {+ ...(head.botTaskCoordination ? { botTaskCoordination: head.botTaskCoordination } : {}),...(head.sharedTaskAuthor ? { sharedTaskAuthor: head.sharedTaskAuthor } : {}),...(head.sourcePlugin ? { sourcePlugin: head.sourcePlugin } : {}),clientId: head.clientId,diff --git a/apps/desktop/src/main/maker-ipc/botTaskCoordination.ts b/apps/desktop/src/main/maker-ipc/botTaskCoordination.tsnew file mode 100644index 0000000000..c24b0a6a9e--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/botTaskCoordination.ts@@ -0,0 +1,51 @@+import { and, eq, isNull } from 'drizzle-orm';+import { getDbClient } from '../localDb/client/current.js';+import { botDelegations, botProfiles, botSessionLinks, sessions } from '../localDb/schema.js';+import type { BotTaskCoordination, SessionMessagePurpose } from '../../shared/botTaskCoordination.js';+import { UI_ACTION_TRIGGER_PREFIX } from '@cindy/maker-shared/synthetic-trigger';++/** Same-owner DB joins, not the caller's source labels, prove the delegation. */+export async function readBotTaskCoordination(+ senderSessionId: string, targetSessionId: string,+): Promise<BotTaskCoordination | null> {+ const [row] = await getDbClient().drizzle.select({+ delegationId: botDelegations.id, runSequence: botDelegations.runSequence,+ }).from(botDelegations)+ .innerJoin(botProfiles, eq(botProfiles.id, botDelegations.requestingBotId))+ .innerJoin(botSessionLinks, and(eq(botSessionLinks.botId, botProfiles.id), eq(botSessionLinks.sessionId, targetSessionId)))+ .innerJoin(sessions, eq(sessions.id, botDelegations.childSessionId))+ .where(and(eq(botDelegations.childSessionId, senderSessionId),+ eq(botDelegations.parentSessionId, targetSessionId),+ eq(botProfiles.canonicalSessionId, targetSessionId), eq(botProfiles.status, 'active'),+ eq(botSessionLinks.role, 'canonical'), isNull(botSessionLinks.archivedAt),+ eq(sessions.status, 'active'))).limit(1);+ return row ? { ...row, senderSessionId } : null;+}++export async function classifySessionMessagePurpose(params: {+ senderSessionId?: string;+ targetSessionId?: string;+ purpose?: SessionMessagePurpose;+}, read = readBotTaskCoordination): Promise<{ coordination: BotTaskCoordination | null; delegatedContinuation: boolean }> {+ const receipt = params.senderSessionId && params.targetSessionId+ ? await read(params.senderSessionId, params.targetSessionId) : null;+ if (!receipt && params.purpose === 'coordination') {+ throw new Error('Coordination requires a delegated task sending to its requesting teammate.');+ }+ // Visibility is independent of authority: public task messages are still delegated input.+ return { coordination: params.purpose === 'user-visible' ? null : receipt, delegatedContinuation: receipt !== null };+}++export async function assertBotTaskCoordination(+ targetSessionId: string, receipt: BotTaskCoordination,+ read = readBotTaskCoordination,+): Promise<void> {+ const current = await read(receipt.senderSessionId, targetSessionId);+ if (!current || current.delegationId !== receipt.delegationId || current.runSequence !== receipt.runSequence) {+ throw new Error('The task coordination recipient or execution has changed; delivery was not accepted.');+ }+}++export function coordinationInput(message: string, receipt: BotTaskCoordination) {+ return { message, persistedContent: `${UI_ACTION_TRIGGER_PREFIX}${message}`, botTaskCoordination: receipt };+}diff --git a/apps/desktop/src/main/maker-ipc/coordinationOutput.ts b/apps/desktop/src/main/maker-ipc/coordinationOutput.tsnew file mode 100644index 0000000000..a7ff4613df--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/coordinationOutput.ts@@ -0,0 +1,12 @@+import type { AgentEvent } from '@cindy/maker-core';++/** Preserve tool actions, errors, interactions and usage; only internal prose is omitted. */+export function projectCoordinationOutput(event: AgentEvent, coordination: boolean): AgentEvent | null {+ if (!coordination || event.runtimeRecovery) return event;+ if (event.type === 'text' || event.type === 'thinking') return null;+ if (event.type === 'done') {+ const data = event.data && typeof event.data === 'object' ? event.data : {};+ return { ...event, data: { ...data, result: '', finalText: '' } };+ }+ return event;+}diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex a64c5c6447..5e6c40a631 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -215,6 +215,7 @@ export function stampTrustedDeviceLinkQueuedOrigin(delete stamped.sourceDevice;delete stamped.sourcePlugin;delete stamped.agentOmitsTriggerPrefix;+ delete stamped.botTaskCoordination;if (deviceLinkInvoke && sourceDevice) stamped.sourceDevice = { ...sourceDevice };return stamped;}@@ -290,6 +291,7 @@ type MakerSendOptions = {*/sourceDevice?: MessageSourceDevice;persistUserMessage?: {+ botTaskCoordination?: AgentInputQueuedMessage['botTaskCoordination'];sharedTaskAuthor?: AgentInputQueuedMessage['sharedTaskAuthor'];/** 插件来源(只写入 agentMeta.sourcePlugin 并生成 `[消息来源]`,不传给 maker-core)。 */sourcePlugin?: unknown;@@ -558,6 +560,7 @@ type ResolveSessionResult =| { kind: 'failure'; result: DesktopMakerSendResult };function readPersistUserMessageOption(sendOpts: MakerSendOptions): {+ botTaskCoordination?: AgentInputQueuedMessage['botTaskCoordination'];sharedTaskAuthor?: AgentInputQueuedMessage['sharedTaskAuthor'];sourcePlugin?: AgentInputQueuedMessage['sourcePlugin'];clientId: string;@@ -580,6 +583,7 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {if (!persist || typeof persist.clientId !== 'string') return null;const sourcePlugin = readWireSourcePlugin(persist.sourcePlugin);return {+ ...(persist.botTaskCoordination ? { botTaskCoordination: persist.botTaskCoordination } : {}),...(persist.sharedTaskAuthor ? { sharedTaskAuthor: persist.sharedTaskAuthor } : {}),...(sourcePlugin ? { sourcePlugin } : {}),clientId: persist.clientId,@@ -1598,12 +1602,14 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakeonAccepted: persistUserMessage? async () => {persistUserMessage.onPersisting?.();- deps.previewUserPrompt?.(sess, persistUserMessage.content, {- source: 'maker_send:onPersisting',- clientId: persistUserMessage.clientId,- });- userPromptPreviewSessionId = sessionId;- userPromptPreviewClientId = persistUserMessage.clientId;+ if (!persistUserMessage.botTaskCoordination) {+ deps.previewUserPrompt?.(sess, persistUserMessage.content, {+ source: 'maker_send:onPersisting',+ clientId: persistUserMessage.clientId,+ });+ userPromptPreviewSessionId = sessionId;+ userPromptPreviewClientId = persistUserMessage.clientId;+ }try {await deps.createDbMessage(sessionId,@@ -1612,6 +1618,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makerole: 'user',content: persistUserMessage.content,agentMeta: {+ ...(persistUserMessage.botTaskCoordination ? { botTaskCoordinationInput: persistUserMessage.botTaskCoordination } : {}),...(persistUserMessage.sharedTaskAuthor ? { sharedTaskAuthor: persistUserMessage.sharedTaskAuthor } : {}),// 来源标签数据(只用于归属展示,不是权限判据)。...(sourceDevice ? { sourceDevice } : {}),diff --git a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.tsindex 98231a8e6e..5737c03b4e 100644--- a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts+++ b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts@@ -178,7 +178,9 @@ export function attachMainOwnedInputBoundary(};}-const MAIN_ONLY_PERSIST_FIELDS = ['sharedTaskAuthor', 'origin', 'sourceDevice', 'sourcePlugin', 'sourceGroup'] as const;+const MAIN_ONLY_PERSIST_FIELDS = [+ 'botTaskCoordination', 'sharedTaskAuthor', 'origin', 'sourceDevice', 'sourcePlugin', 'sourceGroup',+] as const;const MAIN_ONLY_SEND_FIELDS = ['fromMobileClient','fromDeviceLinkClient',diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 79f07c20cf..c164034091 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,3 +1,5 @@+import { assertBotTaskCoordination, classifySessionMessagePurpose, coordinationInput } from './botTaskCoordination.js';+import type { BotTaskCoordination, SessionMessagePurpose } from '../../shared/botTaskCoordination.js';import { openSession, setSessionOpeningModelAdmission } from '../localDb/sessionOpening.js';import { createPluginTaskReviewResolver } from './pluginTaskReviewContext.js';import { isPluginTaskPermissionAllowed, assertPluginTaskResult, createPluginTaskService, readPluginTaskPlanReceipt, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';@@ -2150,6 +2152,7 @@ interface OrcaCollabService {}>;sendToSession: (params: {+ messagePurpose?: SessionMessagePurpose;/** 省略 → create 新 session;提供 → jump 到该既有 session。 */targetSessionId?: string;message: string;@@ -9502,6 +9505,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}async function sendToSessionInternal(params: {+ botTaskCoordination?: BotTaskCoordination;targetSessionId?: string;message: string;persistedContent?: string;@@ -9940,6 +9944,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)origin: queuedOrigin,sourcePlugin,autoReviewUserText: params.autoReviewUserText,+ botTaskCoordination: params.botTaskCoordination,authorizationGuard: params.authorizationGuard,});return {@@ -10005,6 +10010,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)origin: queuedOrigin,sourcePlugin,autoReviewUserText: params.autoReviewUserText,+ botTaskCoordination: params.botTaskCoordination,});return {ok: true as const,@@ -10135,6 +10141,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)origin: queuedOrigin,sourcePlugin,autoReviewUserText: params.autoReviewUserText,+ botTaskCoordination: params.botTaskCoordination,});return {ok: true as const,@@ -10251,6 +10258,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)origin: queuedOrigin,sourcePlugin,autoReviewUserText: params.autoReviewUserText,+ botTaskCoordination: params.botTaskCoordination,});return {ok: true as const,@@ -11847,6 +11855,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}async function enqueueSendToSessionMessage(params: {+ botTaskCoordination?: BotTaskCoordination;targetSessionId: string;inheritTargetPlanMode?: boolean;message: string;@@ -11892,6 +11901,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}async function buildSessionControlInputItem(params: {+ botTaskCoordination?: BotTaskCoordination;targetSessionId: string;inheritTargetPlanMode?: boolean;message: string;@@ -11948,6 +11958,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)text: modelOnlyEnvelope ? params.persistedContent: hiddenTriggerForAgent ? `${UI_ACTION_TRIGGER_PREFIX}${params.message}` : params.message,...(modelOnlyEnvelope ? { [HOST_ONLY_AGENT_PREFIX]: params.message.slice(0, params.message.length - params.persistedContent.slice(UI_ACTION_TRIGGER_PREFIX.length).length) } : {}),+ ...(params.botTaskCoordination ? { botTaskCoordination: params.botTaskCoordination } : {}),...(hiddenTriggerForAgent ? { agentOmitsTriggerPrefix: true as const } : {}),...(params.autoReviewUserText !== undefined ? { autoReviewUserText: params.autoReviewUserText } : {}),...(params.toolsDisabled === true ? { toolsDisabled: true } : {}),@@ -14059,7 +14070,30 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)stopSessionTurn: (params) => sessionControlService.stopSessionTurn(params),getSessionRuntime: (params) => sessionControlService.getSessionRuntime(params),setSessionRuntime: (params) => sessionControlService.setSessionRuntime(params),- sendToSession: sendToSessionInternal,+ sendToSession: async (params) => {+ const ownerScope = captureDataOwnerBroadcastScope();+ let classification: Awaited<ReturnType<typeof classifySessionMessagePurpose>>;+ try {+ classification = await classifySessionMessagePurpose({+ senderSessionId: params.dispatcherSessionId,+ targetSessionId: params.targetSessionId,+ purpose: params.messagePurpose,+ });+ } catch (error) {+ return { ok: false, errorCode: 'INVALID_ARGS', message: error instanceof Error ? error.message : String(error) };+ }+ if (!isDataOwnerBroadcastScopeCurrent(ownerScope)) {+ return { ok: false, errorCode: 'AGENT_NOT_READY', message: 'Data owner changed before delivery.' };+ }+ return sendToSessionInternal({+ ...params,+ ...(classification.delegatedContinuation ? { autoReviewUserText: { kind: 'delegated-continuation' as const } } : {}),+ ...(classification.coordination ? {+ ...coordinationInput(params.message, classification.coordination),+ forceQueue: true,+ } : {}),+ });+ },enableOrca: enableOrcaInternal,disableOrca: disableOrcaInternal,// MCP worker 派活必须经 OrcaTeamService,确保 running、resume idle、广播和@@ -16242,6 +16276,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)publishUiSessionIntervention(sessionId);},previewQueuedUserTurn: (sessionId, item) => {+ if (item.botTaskCoordination) return;notifyAgentIslandUserPrompt({ id: sessionId, agentKind: item.createOpts?.agentKind, workDir: item.workingDir },// 预览给人看的正文:落库可见内容优先(发给模型的 text 可能带来源 / 回执前缀);@@ -16371,6 +16406,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},onUserMessageRewritten: (sessionId, item, info) => (revokeTrustedDesktopQueueOrigin(item), broadcastGhostMessageRewritten({ sessionId, clientId: item.clientId, ...info })),beforeDispatchUserTurn: async (sessionId, item) => {+ if (item.botTaskCoordination) await assertBotTaskCoordination(sessionId, item.botTaskCoordination);autoResumeBookkeeping.markReplacementDispatching(sessionId, item.clientId);const liveSession = maker.getSession(sessionId);if (liveSession) {@@ -16900,6 +16936,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const normalized: AgentInputQueuedMessage = { ...msg };delete normalized.sharedTaskAuthor;delete normalized.autoReviewUserText;+ delete normalized.botTaskCoordination;if (normalized.durableDelivery !== true) delete normalized.durableDelivery;// Only Main-created welcomes and restored host snapshots may carry this policy.delete normalized.toolsDisabled;diff --git a/apps/desktop/src/main/maker-ipc/sessionControlService.ts b/apps/desktop/src/main/maker-ipc/sessionControlService.tsindex 38a631d22e..7a2b2d1197 100644--- a/apps/desktop/src/main/maker-ipc/sessionControlService.ts+++ b/apps/desktop/src/main/maker-ipc/sessionControlService.ts@@ -398,7 +398,7 @@ export function rebuildSessionQueueItem(// synthetic `text` property into the old JSON value. Attachment items are// the exception: their persisted row is the host-built `{text, images, files}`// envelope, which updateQueuedMessageText already rewrote in place.- if (!item.files?.length) updated.persistedContent = message;+ if (!item.files?.length) updated.persistedContent = item.botTaskCoordination ? updated.text : message;updated.origin = { ...updated.origin, displayText: message };}return updated;diff --git a/apps/desktop/src/main/maker-ipc/sessionEventPipeline.ts b/apps/desktop/src/main/maker-ipc/sessionEventPipeline.tsindex dc41e88bf6..a4206424b9 100644--- a/apps/desktop/src/main/maker-ipc/sessionEventPipeline.ts+++ b/apps/desktop/src/main/maker-ipc/sessionEventPipeline.ts@@ -1,3 +1,4 @@+import { projectCoordinationOutput } from './coordinationOutput.js';import { observeBotLearningTurn } from './botLearningFeedback.js';import { projectQuietScheduledOutput } from '../scheduler-host/silent-output.js';import type { AgentEvent, Session } from '@cindy/maker-core';@@ -41,13 +42,17 @@ export function handleSessionEvent(): void {const prepared = prepareSessionEvent(deps, session, event);if (!prepared) return;- const projected = projectQuietScheduledOutput(prepared.event);+ const project = (input: AgentEvent) => {+ const scheduled = projectQuietScheduledOutput(input);+ return scheduled && projectCoordinationOutput(scheduled, prepared.taskCoordination);+ };+ const projected = project(prepared.event);if (!projected) return;if (projected !== prepared.event) {prepared.event = projected;- prepared.attributedEvent = projectQuietScheduledOutput(prepared.attributedEvent) ?? prepared.attributedEvent;+ prepared.attributedEvent = project(prepared.attributedEvent) ?? prepared.attributedEvent;// Project the already-redacted event independently; never copy raw fields back into it.- prepared.broadcastEvent = projectQuietScheduledOutput(prepared.broadcastEvent) ?? prepared.broadcastEvent;+ prepared.broadcastEvent = project(prepared.broadcastEvent) ?? prepared.broadcastEvent;}if (event.type === 'tool_use' && event.turnScope !== 'background') observeBotLearningTurn(session, event.sessionTurnGeneration);const stream = persistSessionStreamEvent(deps, session, prepared);diff --git a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.tsindex 1efa14f2d5..5baf4843c9 100644--- a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts+++ b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts@@ -116,7 +116,7 @@ export interface PrepareSessionEventDeps {readonly silentStopTurnLeaseGate: Pick<SilentStopTurnLeaseGate, 'turnLeaseIdForEvent'>;readonly agentInputCoordinatorHolder: Pick<AgentInputCoordinator,- 'onTurnEvent' | 'noteSuppressedTerminalError' | 'getActiveInputClientId' | 'getActiveInputClientIds'+ 'onTurnEvent' | 'noteSuppressedTerminalError' | 'getActiveInputClientId' | 'getActiveInputClientIds' | 'isActiveTaskCoordination'> | null;readonly handleSilentStopTurnEnd: (session: Session,@@ -168,7 +168,10 @@ export function prepareSessionEvent(},};}+ const taskCoordination = event.turnScope !== 'background'+ && (deps.agentInputCoordinatorHolder?.isActiveTaskCoordination?.(session.id, event.sessionTurnGeneration) ?? false);if (event.type === 'text' && event.standaloneText === true) {+ if (taskCoordination && !event.runtimeRecovery) return;if (isQuietScheduledOutput(event) && !event.runtimeRecovery) return;// Deliver through the existing persisted-row channel only. Sending a text// event as well would let older renderers adopt the notice as their active@@ -204,7 +207,8 @@ export function prepareSessionEvent(...event,agentMeta: {...event.agentMeta,- botPrivateReply: isBotPrivateInput(activeInputId),+ botPrivateReply: isBotPrivateInput(activeInputId) || (taskCoordination && !event.runtimeRecovery),+ botTaskCoordination: taskCoordination && !event.runtimeRecovery,// A group-lane turn is delivered into the group chat; its hidden Session never// raises completion/error attention of its own (docs/product-rules/bot-group-chat.md §3)....(isBotGroupClientId(activeInputId) ? { botGroupLane: true } : {}),@@ -568,6 +572,7 @@ export function prepareSessionEvent(event,attributedEvent,botTaskResultInputIds,+ taskCoordination,broadcastEvent,eventAgentMeta,pendingContextSnapshot,diff --git a/apps/desktop/src/main/maker-ipc/sharedTaskInput.ts b/apps/desktop/src/main/maker-ipc/sharedTaskInput.tsindex d807f00b5d..b629dea361 100644--- a/apps/desktop/src/main/maker-ipc/sharedTaskInput.ts+++ b/apps/desktop/src/main/maker-ipc/sharedTaskInput.ts@@ -14,6 +14,7 @@ export function stampSharedTaskInput(delete stamped.sourceDevice;delete stamped.sourcePlugin;delete stamped.agentOmitsTriggerPrefix;+ delete stamped.botTaskCoordination;if (!task || !capture.isCurrent() || !capture.authorize('input.send')) {throw new Error('[PERMISSION_DENIED] SharedTask task access denied');}diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex b25ba8526b..03d3dfe180 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -666,6 +666,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMctargetSessionId,message,dispatcherSessionId,+ messagePurpose,title,useWorktree,workingDir,@@ -688,6 +689,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMctargetSessionId,message,dispatcherSessionId,+ messagePurpose,title,useWorktree,workingDir,diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.tsindex 935ea55e18..cf0846c9ef 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts@@ -19,6 +19,13 @@ const project = (items: RenderItem[], streaming: boolean) =>simplifyBotRenderItems(groupWorkRuns(items, streaming), streaming);describe('teammate final-result presentation', () => {+ it('keeps coordination input hidden while explicit inputs, results and errors remain visible', () => {+ const rows = [message('coordination', 'user', '[UI_ACTION_TRIGGER]File agreement', { isSyntheticTrigger: true }),+ tool('audit'), message('visible-input', 'user', 'Requested status'),+ message('result', 'assistant', 'Final result', { turnCompleted: true }), message('error', 'error', 'Action required')];+ expect(allKeys(project(rows, false))).toEqual(['msg-visible-input', 'msg-result', 'msg-error']);+ });+it('omits all process rows and keeps final answers without mutating history', () => {const input = [message('u', 'user'), message('a', 'assistant'), tool('t1'),message('b', 'assistant'), tool('t2'), message('final', 'assistant', 'Result', { turnCompleted: true })];diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex 3f295ea8ee..467b1b02a6 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -274,6 +274,10 @@ export interface CcMeta {*//** Automatic reply to a private Bot message; retained without unread attention. */botPrivateReply?: boolean;+ /** Main-owned input receipt, retained for audit; never an authorization grant. */+ botTaskCoordinationInput?: import('../../shared/botTaskCoordination').BotTaskCoordination;+ /** Accepted internal coordination turn, used to suppress successful completion attention. */+ botTaskCoordination?: boolean;/** Turn of a Bot's hidden group-chat lane; the group chat surfaces its result and failures. */botGroupLane?: boolean;botAuthorization?: import('../../shared/botAuthorization').BotAuthorizationCard;diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.tsindex ecb57fec45..8c0c71d30c 100644--- a/apps/desktop/src/shared/agentInputQueue.ts+++ b/apps/desktop/src/shared/agentInputQueue.ts@@ -1,3 +1,4 @@+import { coordinationModelPrefix, type BotTaskCoordination } from './botTaskCoordination.js';/*** Agent input queue wire contract.*@@ -248,6 +249,8 @@ export interface RecoveryCheckpoint {export const HOST_ONLY_AGENT_PREFIX = Symbol('host-only-agent-prefix');export interface AgentInputQueuedMessage {+ /** Main-owned delegation receipt; stripped from renderer/device-link input. */+ botTaskCoordination?: BotTaskCoordination;[HOST_ONLY_AGENT_PREFIX]?: string;/** Host-stamped attribution, retained in durable queue snapshots and messages. */sharedTaskAuthor?: SharedTaskAuthor;@@ -1110,7 +1113,8 @@ export function buildMakerUserMessage(? facingText.slice(UI_ACTION_TRIGGER_PREFIX.length): facingText;// Combine the host source with the latest body, including any Ghost rewrite.- const agentFacingText = (queued[HOST_ONLY_AGENT_PREFIX] ?? '') + authoredText;+ const agentFacingText = (queued.botTaskCoordination ? coordinationModelPrefix(queued.botTaskCoordination) : '')+ + (queued[HOST_ONLY_AGENT_PREFIX] ?? '') + authoredText;if (agentFacingText.length > 0) {blocks.push({ type: 'text', text: agentFacingText });}diff --git a/apps/desktop/src/shared/botTaskCoordination.ts b/apps/desktop/src/shared/botTaskCoordination.tsnew file mode 100644index 0000000000..2e6cb76c4a--- /dev/null+++ b/apps/desktop/src/shared/botTaskCoordination.ts@@ -0,0 +1,16 @@+/** Host-owned receipt. Never accepted from renderer/device-link input. */+export interface BotTaskCoordination {+ delegationId: string;+ runSequence: number;+ senderSessionId: string;+}++export type SessionMessagePurpose = 'coordination' | 'user-visible';++/** Per-input model instruction; never included in visible queue/history text. */+export function coordinationModelPrefix(receipt: BotTaskCoordination): string {+ return `[Internal task coordination from session ${receipt.senderSessionId}; delegation ${receipt.delegationId}; run ${receipt.runSequence}]\n`+ + 'Process this coordination and use tools as needed. Prose in this turn is internal. '+ + 'Use question/permission tools for necessary user decisions. For a user-facing result or a failure requiring user intervention, '+ + 'use send_to_session with message_purpose="user-visible". Normal task completion is delivered separately.\n\n';+}diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.tsindex d1e0b60d54..347f9a0c82 100644--- a/apps/mobile/src/__tests__/messageNormalize.test.ts+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts@@ -1604,3 +1604,17 @@ it.each(['steer', 'new', 'completion'])('pairs companion introduction across steconst ids = rows.map((row) => row.source.id);expect(ids.indexOf('task') > ids.indexOf('intro')).toBe(kind === 'steer');});++it('keeps durable coordination hidden on phone history without hiding user-facing inputs or results', () => {+ const rows = [+ message({ id: 'coordination', role: 'user', content: '[UI_ACTION_TRIGGER]File ownership agreement', agentMeta: { origin: { kind: 'session', senderSessionId: 'child' } } }),+ message({ id: 'requested-status', role: 'user', content: 'Requested status', agentMeta: { origin: { kind: 'session', senderSessionId: 'child' } } }),+ message({ id: 'result', role: 'assistant', content: 'Final result', agentMeta: { turnCompleted: true } }),+ ];+ const normalized = normalizeRemoteMessages(JSON.parse(JSON.stringify(rows)));+ expect(normalized[0]).toMatchObject({ isSyntheticTrigger: true, body: '' });+ const rendered = buildMobileMessageRenderItems(rows);+ expect(JSON.stringify(rendered)).not.toContain('File ownership agreement');+ expect(JSON.stringify(rendered)).toContain('Requested status');+ expect(JSON.stringify(rendered)).toContain('Final result');+});diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex d8fc8979d3..009edd3f57 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -382,6 +382,11 @@ Session 任务遵守同一套机制与呈现契约:`cancelling/unconfirmed` 不是已停,原生终态或状态回读确认空闲后才收口为 cancelled。超时终态也必须检查旧引擎是否已停,仍活跃时不得通过续接启动第二份执行。+委派子任务向发起伙伴发送文件分工等内部协调时,使用 `send_to_session` 的协调用途,+其默认识别、来源核验、静默范围和历史兼容遵守 [message-source.md](message-source.md#委派任务的内部协调)。+这条路径仍唤醒伙伴消费输入,不创建公开进度答复;正常完成结果、必要交互与错误继续保留。+普通任务来信和明确 `user-visible` 的发送不受此静默规则影响。+`send_to_agent` 是另一条更轻的伙伴间通讯通道,不得伪装成任务:- `list_agents` 按需读取本机名册和同账号已授权设备的 Remote Resource 名册;远程目标用diff --git a/docs/product-rules/message-source.md b/docs/product-rules/message-source.mdindex 69c24c3c48..52c9e9f7aa 100644--- a/docs/product-rules/message-source.md+++ b/docs/product-rules/message-source.md@@ -44,3 +44,24 @@- Hook 消息显示渠道,不显示「由自动化「Hook · …」发送」。- 机器发来的排队消息只能删除和调整顺序;合成指令行只显示标签,不显示原文。- 分享图片不显示任何消息来源。++## 委派任务的内部协调++`send_to_session` 的 `message_purpose` 区分 `coordination` 与 `user-visible`。+只有宿主从当前账号数据库核实「委派子任务 → 该委派的发起伙伴 canonical 任务」时,+省略用途才默认内部协调;其它任务来信仍默认可见。显式 `coordination` 没有匹配关系时拒绝,+显式 `user-visible` 保留给用户的结果与必要介入。群专线不是 canonical 收件人,不套用这个默认值。+来源标签不能作为关系证明,MCP 调用方身份来自绑定的任务上下文。++内部输入沿既有持久队列消费,落库保留来源与宿主委派回执,正文使用既有隐藏输入标记;+当次模型输入另附协调用途和发送方身份。排队恢复与派发前重新核实委派执行代次;+校验失败沿正常错误/重试路径处理,不能丢弃后假报送达。用途回执不接受 renderer/device-link 自报,+也不为工具执行提供新授权;共享访客投影移除回执里的私有标识。++宿主只对该协调输入所启动的文字答复与思考做静默投影,成功结束不产生通知/未读;+工具审计、交互、权限请求、错误和宿主恢复说明保留。需要用户决定时使用交互工具;+给用户的正文结果通过明确 `user-visible` 的发送提供。用户插话接管后的答复恢复可见。+委派正常完成仍走原本独立的结果记录和隐藏 completion 唤醒,不改成内部协调。++无需数据库迁移。旧消息不重新分类;新版宿主产生的隐藏输入和静默输出可由现有桌面/手机读取。+旧宿主不会因新客户端自行获得协调用途识别能力;降级不承诺继续执行新队列的静默语义。diff --git a/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts b/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.tsindex d71cf522cf..d6bad57266 100644--- a/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts+++ b/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts@@ -61,6 +61,13 @@ describe('send_to_session tool', () => {expect(control).not.toContain('send_to_session');});+ it.each(['coordination', 'user-visible'])('passes message purpose with the bound caller identity: %s', async purpose => {+ const { registry, sendToSession } = setup();+ const result = await registry.call('send_to_session', { target_session_id: 'parent', message: 'Update', message_purpose: purpose });+ expect(result.isError).toBeUndefined();+ expect(sendToSession).toHaveBeenCalledWith(expect.objectContaining({ targetSessionId: 'parent', messagePurpose: purpose, dispatcherSessionId: expect.any(String) }));+ });+it('缺 message → INVALID_ARGS, host 不被调', async () => {const { registry, sendToSession } = setup();const res = await registry.call('send_to_session', { title: 'x' });diff --git a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts b/packages/lizi-mcps/src/xdt-helper/send_to_session.tsindex 14b9a6a5af..17d531f8a3 100644--- a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts+++ b/packages/lizi-mcps/src/xdt-helper/send_to_session.ts@@ -22,6 +22,7 @@ export type SendToSessionCallback = (params: {targetSessionId?: string;message: string;dispatcherSessionId?: string;+ messagePurpose?: "coordination" | "user-visible";title?: string;/** create 模式可选:true = 为新 session 预建独立 git worktree 并以其为 workingDir(jump 忽略)。 */useWorktree?: boolean;@@ -150,6 +151,9 @@ export function registerSendToSessionTool(.describe("要 handoff 给目标 session 的消息正文(create 模式下作为新 session 的首条消息)。",),+ message_purpose: z.enum(["coordination", "user-visible"]).optional().describe(+ "委派子任务发给发起伙伴默认 coordination:送达模型但内部文字不进正文或通知。user-visible 用于用户要求的结果、需要用户介入的消息。其他普通任务默认保持可见;coordination 仅限宿主核实的委派关系。正常完成自动回传,无需重发。",+ ),title: z.string().optional()@@ -197,6 +201,7 @@ export function registerSendToSessionTool(handler: async ({target_session_id,message,+ message_purpose,title,use_worktree,working_dir,@@ -210,6 +215,7 @@ export function registerSendToSessionTool(targetSessionId: target_session_id,message,dispatcherSessionId: ctx.sessionId,+ ...(message_purpose !== undefined ? { messagePurpose: message_purpose } : {}),title,useWorktree: use_worktree,workingDir: working_dir,