Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 校验群内执行授权并补齐主人私聊 (#5587)
Chris Zhang0f6b989e2776
diff --git a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts b/apps/desktop/src/main/__tests__/agentInputQueue.test.tsindex 7cdfb5c999..86133b5e4e 100644--- a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts+++ b/apps/desktop/src/main/__tests__/agentInputQueue.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';import {+ HOST_ONLY_AGENT_PREFIX,ANNOTATED_IMAGE_NOTE,ANNOTATED_IMAGE_REGIONS_PREFIX,buildMakerUserMessage,@@ -61,6 +62,27 @@ describe('agentInputQueue', () => {expect(getAgentFacingText(rewritten)).toBe('Updated welcome.');});+ it.each([false, true])('preserves host-owned peer hiding through rewrite and persistence (attachments=%s)', attachments => {+ const body = '[UI_ACTION_TRIGGER]Original peer message';+ const images = [{ url: 'cindy-media://fixture', mimeType: 'image/png' }];+ const entry = { ...queuedMessage([]), text: body,+ persistedContent: attachments ? JSON.stringify({ text: body, images }) : body,+ agentOmitsTriggerPrefix: true as const,+ [HOST_ONLY_AGENT_PREFIX]: '[Group source: fixture]\n' };+ const rewritten = updateQueuedMessageText(entry, 'Rewritten peer message');+ const hiddenText = '[UI_ACTION_TRIGGER]Rewritten peer message';+ expect(rewritten.text).toBe(hiddenText);+ expect(rewritten.chatMessage.content).toBe(hiddenText);+ if (attachments) expect(JSON.parse(rewritten.persistedContent)).toMatchObject({ text: hiddenText, images });+ else expect(rewritten.persistedContent).toBe(hiddenText);+ expect(buildMakerUserMessage(rewritten)).toEqual({ type: 'user', content: '[Group source: fixture]\nRewritten peer message' });+ const snapshot = JSON.parse(JSON.stringify(sanitizeQueuedMessageForPersistence(rewritten)));+ expect(snapshot.text).toBe(hiddenText);+ expect(JSON.stringify(snapshot)).not.toContain('Group source');+ expect(updateQueuedMessageText(rewritten, hiddenText).text).toBe(hiddenText);+ expect(buildMakerUserMessage(snapshot)).toEqual({ type: 'user', content: 'Rewritten peer message' });+ });+it('keeps the hidden-row prefix on host receipts but omits it from the model input', () => {const body = '[任务回执] 后台任务已完成。task_id: d-1';const text = `[UI_ACTION_TRIGGER]${body}`;diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.tsindex 800385e9c6..81c1ed16f9 100644--- a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts@@ -403,6 +403,7 @@ describe('stripMainOnlySendOpts(直连路径消毒)', () => {messageUuid: 'u',sourceDevice: { deviceId: 'forged', platform: 'mobile' },sourcePlugin: { pluginId: 'forged' },+ sourceGroup: { groupId: 'forged-group' },sourceOrigin: { kind: 'session', senderSessionId: 'forged' },sharedTaskAuthor: { memberId: 'forged' },persistUserMessage: {@@ -411,6 +412,7 @@ describe('stripMainOnlySendOpts(直连路径消毒)', () => {origin: { kind: 'session', senderSessionId: 'forged' },sourceDevice: { deviceId: 'forged', platform: 'mobile' },sourcePlugin: { pluginId: 'forged' },+ sourceGroup: { groupId: 'forged-group' },},};expect(stripMainOnlySendOpts(forged)).toEqual({diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.tsindex 468872b8b9..336b3816e5 100644--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts@@ -864,7 +864,7 @@ describe('session runtime control wiring', () => {it('fails closed when non-UI runtime selection requires model-window confirmation', () => {const setRuntime = handlerBody(registerSource,- 'setSessionRuntime: async ({ targetSessionId, expectedGeneration, patch }) => {',+ 'setSessionRuntime: async ({ targetSessionId, expectedGeneration, patch, beforeMutation }) => {','assertExternalInputAllowed: assertReviewExternalInputAllowed,',);const setRuntimeGuard = setRuntime.indexOf(diff --git a/apps/desktop/src/main/__tests__/worktreeSessionTransfer.test.ts b/apps/desktop/src/main/__tests__/worktreeSessionTransfer.test.tsindex 5294da64b3..259a0f1cdf 100644--- a/apps/desktop/src/main/__tests__/worktreeSessionTransfer.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeSessionTransfer.test.ts@@ -76,6 +76,30 @@ afterEach(() => {});describe('durable task worktree transfer', () => {+ it('rechecks caller authority after recovery reads and before the registry write', async () => {+ await store.replace('previous', 'previous', intent(), meta);+ commitChild();+ const registryBefore = readFileSync(path.join(root, 'worktrees.json'), 'utf8');+ const originalReplace = store.replace;+ const replacement = vi.spyOn(store, 'replace');+ let revoked = false;+ replacement.mockImplementationOnce(async (...args) => {+ revoked = true;+ return originalReplace(...args);+ });+ const check = vi.fn(async () => { if (revoked) throw new Error('GROUP_AUTHORIZATION_REQUIRED'); });+ try {+ await expect(manager.reconcileSessionTransfer('next', check)).rejects.toThrow('GROUP_AUTHORIZATION_REQUIRED');+ expect(check).toHaveBeenCalledOnce();+ expect(readFileSync(path.join(root, 'worktrees.json'), 'utf8')).toBe(registryBefore);+ expect(store.get('previous')).toEqual(intent());+ expect(store.get('next')).toBeNull();+ revoked = false;+ await manager.reconcileSessionTransfer('next', check);+ expect(store.get('next')?.sessionId).toBe('next');+ } finally { replacement.mockRestore(); }+ });+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());diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.tsindex 3402de84eb..9aac65e527 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts@@ -220,6 +220,20 @@ describe('shared task guests never see the owner private message sources', () =>expect(sent.get('own-task')).toEqual(projection);});+ it('keeps group private delivery visible in guest pushes without its source identity', () => {+ const transport = client();+ __testing.setActiveClient(transport as never);+ subscriptions.subscribe(guestA, ['session:task-a']);+ subscriptions.subscribe('own-task', ['session:task-a']);+ const message = { clientId: 'private-delivery', sessionId: 'task-a', role: 'assistant', content: 'Private reply',+ agentMeta: { sourceGroup: { groupId: 'secret-group', name: 'Secret group' } } };+ __testing.forwardPush('local-db:messages:created', { sessionId: 'task-a', message });+ const sent = new Map(transport.sendPush.mock.calls.map(call => [call[0], call[2]]));+ expect(sent.get(guestA).message.agentMeta).toEqual({ explicitDelivery: true });+ expect(JSON.stringify(sent.get(guestA))).not.toMatch(/secret-group|Secret group|sourceGroup/);+ expect(sent.get('own-task').message).toEqual(message);+ });+it('hides owner devices, plugins and automation identities from the guest only', async () => {const transport = client();__testing.setActiveClient(transport as never);@@ -228,7 +242,7 @@ describe('shared task guests never see the owner private message sources', () =>const sourceDevice = { deviceId: 'owner-phone', name: 'Owner iPhone', platform: 'mobile' };const sourcePlugin = { pluginId: 'owner-plugin', name: 'Owner Plugin' };const schedulerOrigin = { kind: 'scheduler', scheduleId: 'owner-schedule', scheduleName: 'Owner nightly', runId: 'run-1' };- const deviceRow = { clientId: 'm2', sessionId: 'task-a', role: 'user', content: 'hi', agentMeta: { sourceDevice, uuid: 'u2' } };+ const deviceRow = { clientId: 'm2', sessionId: 'task-a', role: 'user', content: 'hi', agentMeta: { sourceDevice, sourceGroup: { groupId: 'owner-group', name: 'Private group' }, uuid: 'u2' } };const scheduledRow = {clientId: 'm3', sessionId: 'task-a', role: 'user', content: 'nightly',agentMeta: { origin: schedulerOrigin, sourcePlugin },@@ -268,7 +282,7 @@ describe('shared task guests never see the owner private message sources', () =>expect(guestQueue[1].origin).toEqual({ kind: 'scheduler' });expect(guestQueue[1].text).toBe('nightly');expect(JSON.stringify(guestPushes)).not.toMatch(- /owner-phone|Owner iPhone|owner-plugin|Owner Plugin|owner-schedule|Owner nightly|run-1|owner-conn|Owner Slack/,+ /owner-phone|Owner iPhone|owner-plugin|Owner Plugin|owner-group|Private group|owner-schedule|Owner nightly|run-1|owner-conn|Owner Slack/,);// Same-account controllers keep the full attribution.expect(ownPushes.filter((payload) => payload.message).map((payload) => payload.message.agentMeta))diff --git a/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts b/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.tsindex 54ebb3e5bf..2ce7e21951 100644--- a/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts+++ b/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts@@ -1,8 +1,9 @@+import { readMessageSourceGroup } from '@cindy/maker-shared/message-source';import { queueItemVisibleText } from '@cindy/maker-shared/queue';const HOOK_SCHEDULE_ID_PREFIX = 'hook:';-const GUEST_HIDDEN_META_KEYS = ['agentFacingWireContent', 'sourceDevice', 'sourcePlugin'] as const;+const GUEST_HIDDEN_META_KEYS = ['agentFacingWireContent', 'sourceDevice', 'sourcePlugin', 'sourceGroup'] as const;function redactOriginForSharedGuest(origin: Record<string, unknown>): Record<string, unknown> | null {if (origin.kind === 'session') return { kind: 'session' };@@ -55,7 +56,12 @@ export function redactMessageOriginForSharedGuest(agentMeta: unknown): unknown {export function redactMessageRowForSharedGuest<T>(message: T): T {if (!message || typeof message !== 'object' || Array.isArray(message)) return message;const record = message as Record<string, unknown>;- const agentMeta = redactMessageOriginForSharedGuest(record.agentMeta);+ let agentMeta = redactMessageOriginForSharedGuest(record.agentMeta);+ // Preserve independent reply visibility without disclosing source identity+ // or sealing unrelated prose in the canonical model turn.+ if (record.role === 'assistant' && readMessageSourceGroup(record.agentMeta)) {+ agentMeta = { ...(agentMeta as Record<string, unknown>), explicitDelivery: true };+ }return agentMeta === record.agentMeta ? message : ({ ...record, agentMeta } as T);}diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex f1effecce7..ac497cb019 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -778,7 +778,28 @@ function messageInsert(readyDb, args) {: expectNumber(payload.expectedClearBoundaryMs, 'expectedClearBoundaryMs');return readyDb.transaction(() => {let changes = 0;- if (guarded) {+ // Connection-local stages never enter history, counts or persistent FTS.+ // SQLite discards them automatically when this worker exits.+ if (payload.publication) {+ readyDb.exec('CREATE TEMP TABLE IF NOT EXISTS cindy_pending_message_publications (id TEXT PRIMARY KEY, client_id TEXT NOT NULL, session_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, tool_use_id TEXT, agent_meta TEXT, agent_kind TEXT, created_at INTEGER NOT NULL)');+ }+ if (payload.publication === 'publish') {+ changes = readyDb.prepare(+ 'INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at) SELECT id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at FROM temp.cindy_pending_message_publications WHERE id = ? AND session_id = ? AND client_id = ?',+ ).run(id, sessionId, clientId).changes;+ if (changes > 0) readyDb.prepare('DELETE FROM temp.cindy_pending_message_publications WHERE id = ? AND session_id = ?').run(id, sessionId);+ } else if (payload.publication === 'rollback') {+ // CAS the complete published row; never remove a replacement or edited row.+ changes = readyDb.prepare(+ 'DELETE FROM messages WHERE id = ? AND session_id = ? AND client_id = ? AND role = ? AND content = ? AND tool_use_id IS ? AND agent_meta IS ? AND agent_kind IS ? AND created_at = ? AND rewind_at IS NULL',+ ).run(id, sessionId, clientId, role, content, toolUseId, agentMeta, agentKind, createdAt).changes;+ } else if (payload.publication === 'discard') {+ changes = readyDb.prepare('DELETE FROM temp.cindy_pending_message_publications WHERE id = ? AND session_id = ? AND client_id = ?').run(id, sessionId, clientId).changes;+ } else if (payload.publication === 'stage') {+ changes = readyDb.prepare(+ 'INSERT INTO temp.cindy_pending_message_publications (id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',+ ).run(id, clientId, sessionId, role, content, toolUseId, agentMeta, agentKind, createdAt).changes;+ } else if (guarded) {changes = readyDb.prepare('INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ? FROM sessions AS s WHERE s.id = ? AND COALESCE(s.cleared_at, -1) = COALESCE(?, -1) ON CONFLICT(session_id, client_id) DO NOTHING',).run(id, clientId, sessionId, role, content, toolUseId, agentMeta, agentKind, createdAt, sessionId, expected).changes;@@ -787,7 +808,7 @@ function messageInsert(readyDb, args) {'INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',).run(id, clientId, sessionId, role, content, toolUseId, agentMeta, agentKind, createdAt).changes;}- if (changes > 0) {+ if (changes > 0 && (!payload.publication || payload.publication === 'publish' || payload.publication === 'rollback')) {if (role === 'user' || role === 'assistant') {readyDb.prepare('UPDATE sessions SET list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?',diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex d70ab0a321..6fc68b530d 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -962,6 +962,74 @@ describe('db worker tx handlers', () => {});});+ it.each([false, true])('stages message publication without exposing live history or list changes (inline=%s)', async useInlineWorker => {+ await withClient(async client => {+ await seedSession(client, 's1');+ await client.exec("UPDATE sessions SET list_preview='keep', list_message_count=7 WHERE id='s1'");+ const args = { id: 'staged', clientId: 'private', sessionId: 's1', role: 'assistant', content: 'private result',+ toolUseId: null, agentMeta: null, agentKind: null, createdAt: 100, guarded: false };+ await expect(client.tx('message.insert', { ...args, publication: 'stage' })).resolves.toEqual({ changes: 1 });+ await expect(client.queryOne('SELECT COUNT(*) AS count FROM messages')).resolves.toEqual({ count: 0 });+ await expect(client.queryOne("SELECT list_preview, list_message_count FROM sessions WHERE id='s1'"))+ .resolves.toEqual({ list_preview: 'keep', list_message_count: 7 });+ await expect(client.tx('message.insert', { ...args, publication: 'publish' })).resolves.toEqual({ changes: 1 });+ await expect(client.queryOne('SELECT client_id, content, rewind_at FROM messages'))+ .resolves.toEqual({ client_id: 'private', content: 'private result', rewind_at: null });+ await expect(client.queryOne("SELECT list_preview, list_message_count FROM sessions WHERE id='s1'"))+ .resolves.toEqual({ list_preview: null, list_message_count: null });+ await expect(client.tx('message.insert', { ...args, publication: 'publish' })).resolves.toEqual({ changes: 0 });+ }, { useInlineWorker });+ });++ it.each([false, true])('rolls back only the exact published row and invalidates cached projections (inline=%s)', async useInlineWorker => {+ await withClient(async client => {+ await seedSession(client, 's1');+ const args = { id: 'published', clientId: 'private', sessionId: 's1', role: 'assistant', content: 'private result',+ toolUseId: null, agentMeta: null, agentKind: null, createdAt: 100, guarded: false };+ await client.tx('message.insert', { ...args, publication: 'stage' });+ await client.tx('message.insert', { ...args, publication: 'publish' });+ // An unrelated row and a changed payload are outside this rollback's authority.+ await client.tx('message.insert', { ...args, id: 'other', clientId: 'other' });+ for (const mismatch of [{ id: 'old-id' }, { sessionId: 'other-session' }, { clientId: 'old-key' },+ { role: 'user' }, { content: 'old body' }, { toolUseId: 'old-tool' }, { agentMeta: '{}' },+ { agentKind: 'pi' }, { createdAt: 99 }]) {+ await expect(client.tx('message.insert', { ...args, ...mismatch, publication: 'rollback' }))+ .resolves.toEqual({ changes: 0 });+ }+ await client.exec("UPDATE sessions SET list_preview='private result', list_message_count=2 WHERE id='s1'");+ await expect(client.tx('message.insert', { ...args, publication: 'rollback' })).resolves.toEqual({ changes: 1 });+ await expect(client.query('SELECT id FROM messages')).resolves.toEqual([{ id: 'other' }]);+ await expect(client.queryOne("SELECT list_preview, list_message_count FROM sessions WHERE id='s1'"))+ .resolves.toEqual({ list_preview: null, list_message_count: null });+ await expect(client.tx('message.insert', { ...args, publication: 'rollback' })).resolves.toEqual({ changes: 0 });+ await client.tx('message.insert', { ...args, id: 'replacement' });+ await expect(client.tx('message.insert', { ...args, publication: 'rollback' })).resolves.toEqual({ changes: 0 });+ await expect(client.queryOne("SELECT id FROM messages WHERE client_id='private'"))+ .resolves.toEqual({ id: 'replacement' });+ }, { useInlineWorker });+ });++ it.each([false, true])('drops abandoned publication stages on worker restart without phantom history (inline=%s)', async useInlineWorker => {+ await withClient(async (client, reopen) => {+ await seedSession(client, 's1');+ const args = { id: 'abandoned', clientId: 'private', sessionId: 's1', role: 'assistant', content: 'never published',+ toolUseId: null, agentMeta: null, agentKind: null, createdAt: 100, guarded: false };+ for (let attempt = 0; attempt < 3; attempt++) {+ await client.tx('message.insert', { ...args, id: 'abandoned-' + attempt, publication: 'stage' });+ }+ await expect(client.queryOne('SELECT COUNT(*) AS count FROM messages')).resolves.toEqual({ count: 0 });+ const restarted = await reopen();+ await expect(restarted.queryOne('SELECT COUNT(*) AS count FROM messages')).resolves.toEqual({ count: 0 });+ await expect(restarted.queryOne("SELECT COUNT(*) AS count FROM sqlite_temp_master WHERE name='cindy_pending_message_publications'"))+ .resolves.toEqual({ count: 0 });+ await expect(restarted.tx('message.insert', { ...args, id: 'abandoned-0', publication: 'publish' })).resolves.toEqual({ changes: 0 });+ await restarted.tx('message.insert', { ...args, publication: 'stage' });+ await expect(restarted.tx('message.insert', { ...args, publication: 'publish' })).resolves.toEqual({ changes: 1 });+ await expect(restarted.queryOne('SELECT COUNT(*) AS count FROM messages')).resolves.toEqual({ count: 1 });+ await expect(restarted.queryOne('SELECT COUNT(*) AS count FROM temp.cindy_pending_message_publications')).resolves.toEqual({ count: 0 });+ }, { useInlineWorker });+ });+it.each([false, true])('message.insert invalidates list projection in the same transaction (inline=%s)',async (useInlineWorker) => {@@ -3604,7 +3672,7 @@ describe('db worker tx handlers', () => {});async function withClient(- fn: (client: DbClient) => Promise<void>,+ fn: (client: DbClient, reopen: () => Promise<DbClient>) => Promise<void>,opts: { useInlineWorker?: boolean; authorityProjection?: boolean } = {},): Promise<void> {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-db-tx-'));@@ -3631,7 +3699,15 @@ async function withClient(betterSqliteModulePath: require.resolve('better-sqlite3'),...(opts.useInlineWorker ? { useInlineWorker: true } : { workerScriptPath }),});- await fn(client);+ await fn(client, async () => {+ await client!.dispose();+ client = await createDbClient({+ userId: 'test-user', dbPath, drizzleDir,+ betterSqliteModulePath: require.resolve('better-sqlite3'),+ ...(opts.useInlineWorker ? { useInlineWorker: true } : { workerScriptPath }),+ });+ return client;+ });} finally {if (client) {await client.dispose();diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 8d708811f7..517cda157d 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -408,6 +408,8 @@ export interface MessageInsertArgs {createdAt: number;guarded: boolean;expectedClearBoundaryMs?: number | null;+ /** Host-only publication; stages belong to a connection-local TEMP table. */+ publication?: 'stage' | 'publish' | 'discard' | 'rollback';}export interface MessageUpdateContentArgs {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex e575d1badc..7f5e499c48 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -1,3 +1,4 @@+import { AcceptedCallbackDispatchCancelled, runAcceptedCallback } from '../../../maker-ipc/acceptedCallbackRunner';import { setSessionOpeningModelAdmission } from '../../sessionOpening';import { ScriptTarget, transpileModule } from 'typescript';import { canResumeAfterRuntimeFallback } from '../../../maker-ipc/botCandidateRecovery';@@ -10,7 +11,7 @@ import Database from 'better-sqlite3';import { AgentInputCoordinator } from '../../../maker-ipc/agent-input-coordinator';import { createSessionQueueControlService } from '../../../maker-ipc/sessionQueueControl';import { createMessage } from '../messages';-import { authorizeSessionQueueItem, rebuildSessionQueueItem } from '../../../maker-ipc/sessionControlService';+import { authorizeSessionQueueItem, createSessionControlService, rebuildSessionQueueItem } from '../../../maker-ipc/sessionControlService';import type { AgentInputQueuedMessage } from '../../../../shared/agentInputQueue';import type { ProviderView } from '@cindy/model-providers';import { createHash } from 'node:crypto';@@ -24,7 +25,8 @@ import { normalizeWorkingDirForStorage } from '../../../../shared/workingDir';import { createBotModelRouteReconciler } from '../../../maker-ipc/botModelRouteReconciler';import type { BotModelRoute } from '../../../../shared/botModelChain';import type { AgentKind } from '@cindy/maker-core';-import { createBotCapabilityService, type BotCapabilityUpdate } from '../../../maker-ipc/botCapabilityService';+import { createBotCapabilityService, type BotCapabilityServiceDeps, type BotCapabilityUpdate } from '../../../maker-ipc/botCapabilityService';+import { GroupToolAuthorizationError, registerGroupToolAuthority } from '../../../maker-ipc/botGroupToolAuthorization';import { buildBotMcpCatalog } from '../../../maker-host/botMcpCatalog';import { CustomMcpProvider } from '../../../mcp-integrations/custom-mcp-provider';import type { McpProvider } from '@cindy/maker-core';@@ -3696,6 +3698,7 @@ describe('Bot Session task end-to-end runtime', () => {}function createDelegationRuntime(options: {+ decorateDispatch?: (dispatch: Parameters<typeof createBotDelegationService>[0]['dispatch']) => Parameters<typeof createBotDelegationService>[0]['dispatch'];discardDelegationQueuedInputs?: Parameters<typeof createBotDelegationService>[0]['discardDelegationQueuedInputs'];collectArtifacts?: Parameters<typeof createBotDelegationService>[0]['collectArtifacts'];readSessionExecution?: Parameters<typeof createBotDelegationService>[0]['readSessionExecution'];@@ -3708,6 +3711,7 @@ describe('Bot Session task end-to-end runtime', () => {taskQueue?: Parameters<typeof createBotDelegationService>[0]['taskQueue'];taskRoute?: Parameters<typeof createBotDelegationService>[0]['taskRoute'];taskControl?: boolean;+ maxActiveChildren?: number;queueSnapshots?: Map<string, AgentInputQueuedMessage[]>;onNativeStarted?: (sessionId: string) => void;beforeNativeAcceptance?: (sessionId: string) => void;@@ -3935,7 +3939,7 @@ describe('Bot Session task end-to-end runtime', () => {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+ const stopTurn = vi.fn<NonNullable<Parameters<typeof createBotDelegationService>[0]['taskControl']>['stop']>(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);@@ -3943,6 +3947,7 @@ describe('Bot Session task end-to-end runtime', () => {const flushInput = vi.fn(async (): Promise<void> => undefined);const closeSession = vi.fn(options.closeSession ?? (async () => undefined));const delegation = createBotDelegationService({+ maxActiveChildren: options.maxActiveChildren,readSessionExecution: options.readSessionExecution,collectArtifacts: options.collectArtifacts,discardDelegationQueuedInputs: options.discardDelegationQueuedInputs ?? (coordinator@@ -3986,7 +3991,7 @@ describe('Bot Session task end-to-end runtime', () => {await options.onResultReceiptPersisted?.();}} : undefined,- dispatch,+ dispatch: options.decorateDispatch?.(dispatch) ?? dispatch,abortSession,closeSession,broadcastSessionCreated: vi.fn(),@@ -4077,6 +4082,1064 @@ describe('Bot Session task end-to-end runtime', () => {});}+ function seedGroupLane(id = 'group-lane', route = 'group:fixture:access:owner:2') {+ h.sqlite!.prepare(`INSERT INTO sessions (id, source, status, working_dir, model, agent_kind, provider_id, permission_mode, created_at, updated_at)+ SELECT ?, source, status, working_dir, model, agent_kind, provider_id, permission_mode, created_at, updated_at FROM sessions WHERE id='session-1'`).run(id);+ h.sqlite!.prepare(`INSERT INTO bot_session_links (id, bot_id, session_id, profile_version, role, route_key, created_at)+ VALUES (?, 'bot-a', ?, 1, 'group', ?, 1)`).run(`${id}-link`, id, route);+ }++ it('starts owner-authorized group work without impersonation and returns cards/results to the owner private chat', async () => {+ await seedPair(); seedGroupLane();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ const readCallerPermission = vi.fn(() => ({ mode: 'auto' as const, generation: 2 }));+ const runtime = createDelegationRuntime({ readCallerPermission });+ try {+ const result = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture-only development task' });+ expect(result).toMatchObject({ ok: true, completionDestination: 'teammate-private-chat' });+ if (!result.ok) throw new Error(result.message);+ expect(readCallerPermission).toHaveBeenCalledWith('group-lane');+ const row = h.sqlite!.prepare('SELECT parent_session_id, permission_snapshot_json FROM bot_delegations WHERE id=?').get(result.delegationId) as { parent_session_id: string; permission_snapshot_json: string };+ expect(row.parent_session_id).toBe('session-1');+ expect(JSON.parse(row.permission_snapshot_json)).toMatchObject({ groupOriginRoute: 'group:fixture:access:owner:2', groupOriginSessionId: 'group-lane', permission: { mode: 'auto' } });+ expect(runtime.dispatch).toHaveBeenCalledWith(expect.objectContaining({ targetSessionId: result.childSessionId, dispatcherSessionId: 'group-lane' }));+ expect(h.sqlite!.prepare('SELECT role FROM bot_session_links WHERE session_id=?').get('group-lane')).toEqual({ role: 'group' });+ expect(h.sqlite!.prepare('SELECT session_id FROM messages WHERE client_id=?').get(`bot-delegation-request:${result.delegationId}`)).toEqual({ session_id: 'session-1' });+ await runtime.runPendingTurns();+ expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === 'session-1')).toBe(true);+ expect(await runtime.delegation.getSessionTask('group-lane', result.delegationId)).toMatchObject({ ok: true });+ seedGroupLane('other-group', 'group:other:access:owner:2');+ const releaseOther = registerGroupToolAuthority('other-group', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ try {+ expect(await runtime.delegation.getSessionTask('other-group', result.delegationId)).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ } finally { releaseOther(); }+ release();+ expect(await runtime.delegation.getSessionTask('group-lane', result.delegationId)).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ // The owner retains control of work already started in their private chat.+ expect(await runtime.delegation.getSessionTask('session-1', result.delegationId)).toMatchObject({ ok: true });+ } finally { release(); runtime.dispose(); }+ });++ it.each(['retry', 'replay', 'restart'] as const)('continues admitted group work after the originating execution ends during %s', async recovery => {+ await seedPair(); seedGroupLane();+ vi.useFakeTimers();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ let unavailable = true;+ let permission: string | null = 'auto';+ let runtime = createDelegationRuntime({ transientUnavailable: () => unavailable, readCallerPermission: () => permission });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture queued independent work' });+ expect(task).toMatchObject({ ok: true, status: 'queued', completionDestination: 'teammate-private-chat' });+ if (!task.ok) throw new Error(task.message);+ if (recovery === 'replay') {+ h.sqlite!.prepare('INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)')+ .run('unaccepted-start', `bot-delegation-start:${task.delegationId}`, task.childSessionId, 'user', 'Fixture queued independent work', 1);+ }+ release(); permission = null; unavailable = false;+ if (recovery === 'restart') {+ runtime.dispose();+ runtime = createDelegationRuntime({ readCallerPermission: () => permission });+ await runtime.delegation.restore();+ } else await vi.advanceTimersByTimeAsync(2_000);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'running' } });+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(1);+ expect(h.sqlite!.prepare('SELECT permission_mode FROM sessions WHERE id=?').pluck().get(task.childSessionId)).toBe('auto');+ expect(await runtime.delegation.getSessionTask('group-lane', task.delegationId)).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ await runtime.runPendingTurns();+ expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === 'session-1')).toBe(true);+ } finally { release(); runtime.dispose(); vi.useRealTimers(); }+ });++ it.each(['retry', 'restart'] as const)('continues admitted reopened group work after the group ends during %s', async recovery => {+ await seedPair(); seedGroupLane();+ vi.useFakeTimers();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ const originalTx = h.tx!;+ let reopened = false;+ let transferPending = true;+ h.tx = async (name, args) => {+ const result = await originalTx(name, args);+ if (name === 'bots.reopenDelegation') reopened = true;+ return result;+ };+ let runtime = createDelegationRuntime({ reconcileWorktree: async () => {+ if (reopened && transferPending) throw new Error('Fixture worktree reconciliation pending');+ } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Finish initial work.' });+ if (!task.ok) throw new Error(task.message);+ await runtime.settleChild(task.childSessionId, 'Initial work done.');+ runtime.started.length = 0;+ expect(await runtime.delegation.messageSessionTask('group-lane', task.delegationId,+ { kind: 'message', text: 'Continue with new independent work.' }))+ .toMatchObject({ ok: true, resumed: true, queued: true });+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(0);+ release(); transferPending = false;+ if (recovery === 'restart') {+ runtime.dispose(); runtime = createDelegationRuntime();+ await runtime.delegation.restore();+ } else await vi.advanceTimersByTimeAsync(2_000);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'running' } });+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(1);+ expect(h.sqlite!.prepare('SELECT run_sequence FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).toBe(2);+ expect(await runtime.delegation.getSessionTask('group-lane', task.delegationId)).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ await runtime.runPendingTurns();+ expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === 'session-1')).toBe(true);+ } finally { h.tx = originalTx; release(); runtime.dispose(); vi.useRealTimers(); }+ });++ it.each(['before-commit', 'after-commit'] as const)('rejects group task reopening revoked %s before independent admission', async boundary => {+ await seedPair(); seedGroupLane();+ let revoked = false;+ let reopening = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const originalTx = h.tx!;+ h.tx = async (name, args) => {+ const result = await originalTx(name, args);+ if (name === 'bots.reopenDelegation' && boundary === 'after-commit') revoked = true;+ return result;+ };+ const runtime = createDelegationRuntime({ reconcileWorktree: async () => {+ if (reopening && boundary === 'before-commit') revoked = true;+ } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Finish initial work.' });+ if (!task.ok) throw new Error(task.message);+ await runtime.settleChild(task.childSessionId, 'Done.');+ runtime.started.length = 0;+ reopening = true;+ expect(await runtime.delegation.messageSessionTask('group-lane', task.delegationId, { kind: 'message', text: 'Must not be admitted.' }))+ .toMatchObject({ ok: false, errorCode: boundary === 'before-commit' ? 'GROUP_AUTHORIZATION_REQUIRED' : 'CALLER_PERMISSION_UNAVAILABLE' });+ expect(runtime.started).toHaveLength(0);+ expect(h.sqlite!.prepare('SELECT status, run_sequence FROM bot_delegations WHERE id=?').get(task.delegationId))+ .toEqual({ status: boundary === 'before-commit' ? 'completed' : 'failed', run_sequence: boundary === 'before-commit' ? 1 : 2 });+ await runtime.delegation.restore();+ // The owner can receive the failure receipt; the child must never start.+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(0);+ } finally { h.tx = originalTx; release(); runtime.dispose(); }+ });++ it('rejects group work revoked after persistence but before independent admission', async () => {+ await seedPair(); seedGroupLane();+ let revoked = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const originalTx = h.tx!;+ h.tx = async (name, args) => {+ const result = await originalTx(name, args);+ if (name === 'bots.createDelegation') revoked = true;+ return result;+ };+ const runtime = createDelegationRuntime();+ try {+ expect(await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Must not be admitted' }))+ .toMatchObject({ ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE' });+ expect(runtime.started).toEqual([]);+ expect(h.sqlite!.prepare('SELECT status FROM bot_delegations').pluck().get()).toBe('failed');+ } finally { h.tx = originalTx; release(); runtime.dispose(); }+ });++ it.each(['none', 'chat', 'tools', 'revoked', 'wrong-bot'])(+ 'does not create an independent task for a group with %s authority', async mode => {+ await seedPair(); seedGroupLane();+ const release = mode === 'none' ? () => {} : registerGroupToolAuthority('group-lane', {+ botId: mode === 'wrong-bot' ? 'another-bot' : 'bot-a', mode: mode === 'chat' || mode === 'tools' ? mode : 'owner',+ isCurrent: () => mode !== 'revoked', validate: async () => {},+ });+ const runtime = createDelegationRuntime();+ try {+ expect(await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Must not start' })).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(runtime.started).toEqual([]);+ expect(h.sqlite!.prepare('SELECT COUNT(*) AS count FROM bot_delegations').get()).toEqual({ count: 0 });+ } finally { release(); runtime.dispose(); }+ });++ it.each([true, false])('counts an explicit group private send with subsequent tools (canonical running=%s)', async running => {+ await seedPair(); seedGroupLane();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner',+ sourceGroup: { groupId: 'fixture', name: 'Fixture group' }, isCurrent: () => true, validate: async () => {} });+ const dispatch = vi.fn();+ const service = createBotDirectMessageService({ dispatch });+ try {+ h.getSession.mockReturnValue({ isTurnRunning: () => running, compactSession: vi.fn() });+ const sent = await service.sendToUser({ callerSessionId: 'group-lane', message: 'Explicit private reply', idempotencyKey: 'visible-private-fixture' });+ if (!sent.ok) throw new Error(sent.message);+ const row = h.sqlite!.prepare('SELECT created_at AS createdAt, agent_meta AS meta FROM messages WHERE id=?').get(sent.messageId) as { createdAt: number; meta: string };+ expect(JSON.parse(row.meta).turnCompleted).toBeUndefined();+ await createMessage(sent.targetSessionId, { clientId: 'later-progress', role: 'assistant', content: 'Private turn still working', createdAt: row.createdAt + 1 });+ await createMessage(sent.targetSessionId, { clientId: 'later-tool', role: 'tool_use', content: { name: 'Read' }, createdAt: row.createdAt + 2 });+ const list = async (lastReadAt: number) => (await invoke('local-db:bots:list', { lastReadAtByBotId: { 'bot-a': lastReadAt } }) as Array<{ id: string; unreadCount: number; lastMessagePreview: string }>).find(bot => bot.id === 'bot-a')!;+ expect(await list(row.createdAt - 1)).toMatchObject({ unreadCount: 1, lastMessagePreview: 'Explicit private reply' });+ expect(await getBotRemoteResourceSource('bot-a')).toMatchObject({ lastReplyAt: row.createdAt, lastMessagePreview: 'Explicit private reply' });+ expect(await list(row.createdAt)).toMatchObject({ unreadCount: 0 });+ h.sqlite!.prepare('UPDATE messages SET rewind_at=? WHERE id=?').run(row.createdAt + 3, sent.messageId);+ expect(await list(row.createdAt - 1)).toMatchObject({ unreadCount: 0 });+ expect((await getBotRemoteResourceSource('bot-a')).lastReplyAt).toBe(0);+ h.sqlite!.prepare('UPDATE messages SET rewind_at=NULL WHERE id=?').run(sent.messageId);+ h.sqlite!.prepare('UPDATE sessions SET cleared_at=? WHERE id=?').run(row.createdAt + 3, sent.targetSessionId);+ expect(await list(row.createdAt - 1)).toMatchObject({ unreadCount: 0 });+ expect((await getBotRemoteResourceSource('bot-a')).lastReplyAt).toBe(0);+ expect(dispatch).not.toHaveBeenCalled();+ } finally { release(); }+ });++ it.each(['Private reply', '"Private reply"', '123', '{"reply":"ok"}', 'line one\nline two'])('compares exact persisted private text on retries: %s', async message => {+ await seedPair(); seedGroupLane();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner',+ sourceGroup: { groupId: 'fixture' }, isCurrent: () => true, validate: async () => {} });+ const dispatch = vi.fn();+ const service = createBotDirectMessageService({ dispatch });+ const input = { callerSessionId: 'group-lane', message, idempotencyKey: 'exact-text-fixture' };+ try {+ const first = await service.sendToUser(input);+ expect(first).toMatchObject({ ok: true, delivered: true });+ if (!first.ok) throw new Error(first.message);+ expect(h.sqlite!.prepare('SELECT content FROM messages WHERE id=?').pluck().get(first.messageId)).toBe(message);+ expect(await service.sendToUser(input)).toEqual(first);+ expect(await service.sendToUser({ ...input, message: message + ' changed' }))+ .toMatchObject({ ok: false, errorCode: 'IDEMPOTENCY_CONFLICT' });+ expect(h.sqlite!.prepare("SELECT count(*) FROM messages WHERE client_id LIKE 'bot-group-private:%'").pluck().get()).toBe(1);+ expect(dispatch).not.toHaveBeenCalled();+ } finally { release(); }+ });++ it.each((['missing', 'deleted'] as const).flatMap(state => [false, true].map(revoke => ({ state, revoke }))))(+ 'guards peer canonical recovery after its async lookup ($state, revoke=$revoke)', async ({ state, revoke }) => {+ await seedPair(); seedGroupLane();+ await invoke('local-db:bots:create', { id: 'bot-b', name: 'Peer', capabilities: { harness: 'pi', model: 'grok-4.5', providerId: PROVIDER } });+ const peer = await invoke('local-db:bots:create-canonical-session', { botId: 'bot-b', expectedCanonicalSessionId: null, expectedProfileVersion: 1 }) as { canonicalSessionId: string };+ if (state === 'missing') {+ h.sqlite!.pragma('foreign_keys = OFF');+ h.sqlite!.prepare('DELETE FROM sessions WHERE id=?').run(peer.canonicalSessionId);+ h.sqlite!.pragma('foreign_keys = ON');+ } else h.sqlite!.prepare("UPDATE sessions SET status='deleted' WHERE id=?").run(peer.canonicalSessionId);+ let revoked = false;+ let crossed = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner',+ sourceGroup: { groupId: 'fixture' }, isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const select = h.db!.select.bind(h.db!);+ const spy = vi.spyOn(h.db!, 'select').mockImplementation(fields => {+ const query = select(fields);+ if (fields?.role === botSessionLinks.role && fields?.status === sessions.status) {+ crossed = true;+ queueMicrotask(() => { revoked = revoke; });+ }+ return query;+ });+ const runtime = createDelegationRuntime();+ const service = createBotDirectMessageService({ dispatch: runtime.dispatch, ensureCanonicalSession: runtime.delegation.ensureCanonicalSession });+ const sessionCount = h.sqlite!.prepare('SELECT count(*) FROM sessions').pluck().get();+ try {+ const result = await service.messageAgent({ callerSessionId: 'group-lane', targetBotId: 'bot-b', message: 'Fixture peer request' });+ expect(crossed).toBe(true);+ if (revoke) {+ expect(result).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(h.sqlite!.prepare('SELECT count(*) FROM sessions').pluck().get()).toBe(sessionCount);+ expect(h.sqlite!.prepare("SELECT session_id FROM bot_session_links WHERE bot_id='bot-b' AND role='canonical' AND archived_at IS NULL").pluck().get()).toBe(peer.canonicalSessionId);+ expect(runtime.dispatch).not.toHaveBeenCalled();+ expect(h.sqlite!.prepare('SELECT count(*) FROM bot_direct_messages').pluck().get()).toBe(0);+ } else {+ expect(result).toMatchObject({ ok: true });+ if (!result.ok) throw new Error(result.message);+ expect(result.targetSessionId).not.toBe(peer.canonicalSessionId);+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id=?').pluck().get(result.targetSessionId)).toBe('active');+ }+ } finally { spy.mockRestore(); release(); runtime.dispose(); }+ });++ it.each(['missing', 'deleted'] as const)('repairs a %s canonical chat for group private messages and independent tasks', async state => {+ await seedPair(); seedGroupLane();+ if (state === 'missing') {+ h.sqlite!.pragma('foreign_keys = OFF');+ h.sqlite!.prepare("DELETE FROM sessions WHERE id='session-1'").run();+ h.sqlite!.pragma('foreign_keys = ON');+ } else h.sqlite!.prepare("UPDATE sessions SET status='deleted' WHERE id='session-1'").run();+ const release = registerGroupToolAuthority('group-lane', {+ botId: 'bot-a', mode: 'owner', sourceGroup: { groupId: 'fixture' }, isCurrent: () => true, validate: async () => {},+ });+ const runtime = createDelegationRuntime();+ const direct = createBotDirectMessageService({ dispatch: runtime.dispatch, ensureCanonicalSession: runtime.delegation.ensureCanonicalSession });+ try {+ const sent = await direct.sendToUser({ callerSessionId: 'group-lane', message: 'Recovered private chat', idempotencyKey: 'recovery-fixture' });+ expect(sent).toMatchObject({ ok: true, delivered: true });+ if (!sent.ok) throw new Error(sent.message);+ expect(sent.targetSessionId).not.toBe('session-1');+ expect(h.sqlite!.prepare('SELECT role,session_id FROM messages WHERE id=?').get(sent.messageId))+ .toEqual({ role: 'assistant', session_id: sent.targetSessionId });+ expect(runtime.dispatch).not.toHaveBeenCalled();+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture task after private-chat recovery' });+ expect(task).toMatchObject({ ok: true, completionDestination: 'teammate-private-chat' });+ if (!task.ok) throw new Error(task.message);+ expect(h.sqlite!.prepare('SELECT parent_session_id FROM bot_delegations WHERE id=?').get(task.delegationId))+ .toEqual({ parent_session_id: sent.targetSessionId });+ expect(await direct.sendToUser({ callerSessionId: 'group-lane', message: 'Recovered private chat', idempotencyKey: 'recovery-fixture' }))+ .toMatchObject({ ok: true, messageId: sent.messageId, targetSessionId: sent.targetSessionId });+ } finally { release(); runtime.dispose(); }+ });++ it.each(['revoked', 'owner-changed'] as const)('removes an unpublished group private message when %s during persistence', async failure => {+ await seedPair(); seedGroupLane();+ let revoked = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner',+ sourceGroup: { groupId: 'fixture' }, isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const originalTx = h.tx!;+ h.tx = async (name, args) => {+ const result = await originalTx(name, args);+ if (name === 'message.insert' && (args as { publication?: string }).publication === 'stage') {+ expect(h.sqlite!.prepare("SELECT count(*) FROM messages WHERE content = 'Must stay private' AND rewind_at IS NULL").pluck().get()).toBe(0);+ if (failure === 'revoked') revoked = true;+ else h.ownerScopeKey = 'owner-b:2';+ }+ return result;+ };+ const dispatch = vi.fn();+ const service = createBotDirectMessageService({ dispatch,+ captureOwnerScope: () => ({ ownerScopeKey: h.ownerScopeKey, ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 } }),+ isOwnerScopeCurrent: scope => scope.ownerScopeKey === h.ownerScopeKey });+ try {+ expect(await service.sendToUser({ callerSessionId: 'group-lane', message: 'Must stay private', idempotencyKey: 'post-write-revoke' }))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(h.sqlite!.prepare("SELECT count(*) FROM messages WHERE content = 'Must stay private'").pluck().get()).toBe(0);+ expect(dispatch).not.toHaveBeenCalled();+ } finally { h.tx = originalTx; release(); }+ });++ it.each(['healthy', 'missing'] as const)('keeps or repairs the %s owner chat when group work is the first entry', async state => {+ await seedPair(); seedGroupLane();+ if (state === 'missing') {+ h.sqlite!.pragma('foreign_keys = OFF');+ h.sqlite!.prepare("DELETE FROM sessions WHERE id='session-1'").run();+ h.sqlite!.pragma('foreign_keys = ON');+ }+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ const runtime = createDelegationRuntime();+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture task as first recovery entry' });+ expect(task).toMatchObject({ ok: true });+ if (!task.ok) throw new Error(task.message);+ const parent = h.sqlite!.prepare('SELECT parent_session_id FROM bot_delegations WHERE id=?').pluck().get(task.delegationId);+ if (state === 'healthy') expect(parent).toBe('session-1');+ else expect(parent).not.toBe('session-1');+ expect(h.sqlite!.prepare("SELECT session_id FROM bot_session_links WHERE bot_id='bot-a' AND role='canonical' AND archived_at IS NULL").all())+ .toEqual([{ session_id: parent }]);+ } finally { release(); runtime.dispose(); }+ });++ it.each([['private-message', 'revoked'], ['independent-task', 'revoked'], ['private-message', 'account'], ['independent-task', 'account']] as const)('does not deliver %s after %s during canonical recovery', async (operation, interruption) => {+ await seedPair(); seedGroupLane();+ h.sqlite!.pragma('foreign_keys = OFF');+ h.sqlite!.prepare("DELETE FROM sessions WHERE id='session-1'").run();+ h.sqlite!.pragma('foreign_keys = ON');+ let revoked = false;+ h.ensureGit.mockImplementationOnce(async () => { revoked = true; if (interruption === 'account') h.ownerScopeKey = 'owner-b:2'; });+ const release = registerGroupToolAuthority('group-lane', {+ botId: 'bot-a', mode: 'owner', sourceGroup: { groupId: 'fixture' }, isCurrent: () => h.ownerScopeKey === 'owner-a:1',+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); },+ });+ const runtime = createDelegationRuntime();+ const direct = createBotDirectMessageService({ dispatch: runtime.dispatch, ensureCanonicalSession: runtime.delegation.ensureCanonicalSession });+ const before = h.sqlite!.prepare('SELECT id FROM sessions ORDER BY id').all();+ const links = h.sqlite!.prepare('SELECT * FROM bot_session_links ORDER BY id').all();+ try {+ const result = operation === 'private-message'+ ? await direct.sendToUser({ callerSessionId: 'group-lane', message: 'Must not deliver', idempotencyKey: 'revoke-fixture' })+ : await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Must not start' });+ expect(revoked).toBe(true);+ expect(result).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(runtime.dispatch).not.toHaveBeenCalled();+ expect(h.sqlite!.prepare('SELECT id FROM sessions ORDER BY id').all()).toEqual(before);+ expect(h.sqlite!.prepare('SELECT * FROM bot_session_links ORDER BY id').all()).toEqual(links);+ expect(h.sqlite!.prepare("SELECT canonical_session_id FROM bot_profiles WHERE id='bot-a'").pluck().get()).toBe('session-1');+ expect(h.sqlite!.prepare('SELECT COUNT(*) AS count FROM bot_delegations').get()).toEqual({ count: 0 });+ expect(h.sqlite!.prepare("SELECT COUNT(*) AS count FROM messages WHERE client_id LIKE 'bot-group-private:%'").get()).toEqual({ count: 0 });+ } finally { release(); runtime.dispose(); }+ });++ it.each((['private-message', 'peer-message', 'independent-task'] as const).flatMap(operation =>+ (['deleted', 'unlinked'] as const).map(state => ({ operation, state }))))('does not commit $state canonical recovery for $operation after preparation revokes the grant', async ({ operation, state }) => {+ await seedPair(); seedGroupLane();+ const targetBotId = operation === 'peer-message' ? 'bot-b' : 'bot-a';+ let canonicalSessionId = 'session-1';+ if (operation === 'peer-message') {+ await invoke('local-db:bots:create', { id: targetBotId, name: 'Peer', capabilities: { harness: 'pi', model: 'grok-4.5', providerId: PROVIDER } });+ const peer = await invoke('local-db:bots:create-canonical-session', { botId: targetBotId, expectedCanonicalSessionId: null, expectedProfileVersion: 1 });+ canonicalSessionId = peer.canonicalSessionId;+ }+ h.sqlite!.prepare("UPDATE sessions SET status='deleted' WHERE id=?").run(canonicalSessionId);+ if (state === 'unlinked') {+ h.sqlite!.prepare("DELETE FROM bot_session_links WHERE bot_id=? AND role='canonical'").run(targetBotId);+ h.sqlite!.prepare('UPDATE bot_profiles SET canonical_session_id=NULL WHERE id=?').run(targetBotId);+ }+ const sessionsBefore = h.sqlite!.prepare('SELECT id,status FROM sessions ORDER BY id').all();+ const linksBefore = h.sqlite!.prepare('SELECT * FROM bot_session_links ORDER BY id').all();+ const profilesBefore = h.sqlite!.prepare('SELECT id,canonical_session_id FROM bot_profiles ORDER BY id').all();+ let revoked = false;+ h.ensureGit.mockImplementationOnce(async () => { revoked = true; });+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner',+ sourceGroup: { groupId: 'fixture' }, isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const baseTx = h.tx!;+ const tx = vi.fn(baseTx);+ h.tx = tx;+ const runtime = createDelegationRuntime();+ const service = createBotDirectMessageService({ dispatch: runtime.dispatch, ensureCanonicalSession: runtime.delegation.ensureCanonicalSession });+ try {+ const result = operation === 'private-message'+ ? await service.sendToUser({ callerSessionId: 'group-lane', message: 'Fixture', idempotencyKey: 'no-recovery-commit' })+ : operation === 'peer-message'+ ? await service.messageAgent({ callerSessionId: 'group-lane', targetBotId, message: 'Fixture' })+ : await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture' });+ expect(revoked).toBe(true);+ expect(result).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(tx.mock.calls.map(([name]) => name)).not.toContain('bots.replaceCanonicalSession');+ expect(tx.mock.calls.map(([name]) => name)).not.toContain('bots.reparentDelegations');+ expect(h.sqlite!.prepare('SELECT id,status FROM sessions ORDER BY id').all()).toEqual(sessionsBefore);+ expect(h.sqlite!.prepare('SELECT * FROM bot_session_links ORDER BY id').all()).toEqual(linksBefore);+ expect(h.sqlite!.prepare('SELECT id,canonical_session_id FROM bot_profiles ORDER BY id').all()).toEqual(profilesBefore);+ expect(runtime.dispatch).not.toHaveBeenCalled();+ expect(h.sqlite!.prepare('SELECT count(*) FROM bot_delegations').pluck().get()).toBe(0);+ } finally { h.tx = baseTx; release(); runtime.dispose(); }+ });++ it('rejects revoked group authority after asynchronous worktree preparation, before any task exists', async () => {+ await seedPair(); seedGroupLane();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ const discardUnusedWorktree = vi.fn(async () => {});+ const runtime = createDelegationRuntime({ discardUnusedWorktree, prepareWorktree: async () => {+ release();+ return { ok: true, sessionId: 'prepared-fixture', workingDir: h.userDataDir };+ } });+ try {+ expect(await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Must not start after revoke', workingDir: h.userDataDir, useWorktree: true }))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(runtime.started).toEqual([]);+ expect(h.sqlite!.prepare('SELECT COUNT(*) AS count FROM bot_delegations').get()).toEqual({ count: 0 });+ expect(discardUnusedWorktree).toHaveBeenCalledWith('prepared-fixture');+ } finally { release(); runtime.dispose(); }+ });++ it('lets a tools-authorized group inspect its own profile and skills without permitting profile mutation', async () => {+ await seedPair(); seedGroupLane();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'tools', isCurrent: () => true, validate: async () => {} });+ const service = createBotCapabilityService(capabilityDeps);+ try {+ expect(await service.inspect({ callerSessionId: 'group-lane' })).toMatchObject({ ok: true, state: { profile: { id: 'bot-a' }, session: { id: 'group-lane' } } });+ expect(await listBotSkillsForSession({ callerSessionId: 'group-lane' })).toMatchObject({ ok: true });+ expect(await service.updateProfile({ callerSessionId: 'group-lane', expectedVersion: 1, name: 'Unapproved rename' })).toMatchObject({ ok: false });+ release();+ expect(await service.inspect({ callerSessionId: 'group-lane' })).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ } finally { release(); }+ });++ it.each((['resume', 'reopen'] as const).flatMap(mode =>+ (['requester-read', 'child-read', 'reconcile'] as const).map(boundary => ({ mode, boundary }))))+ ('rejects $mode preparation revoked during $boundary', async ({ mode, boundary }) => {+ await seedPair(); seedGroupLane();+ let armed = false;+ let revoked = false;+ let reconciliations = 0;+ const mutation = vi.fn();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const runtime = createDelegationRuntime({ taskControl: true, reconcileWorktree: async (_id, beforeMutation) => {+ if (armed && ++reconciliations === 2 && boundary === 'reconcile') {+ revoked = true;+ await beforeMutation?.();+ mutation();+ throw new Error('Private worktree failure');+ }+ } });+ let read: ReturnType<typeof vi.spyOn> | undefined;+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Preparation fixture' });+ if (!task.ok) throw new Error(task.message);+ if (mode === 'resume') await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ await runtime.settleChild(task.childSessionId, 'Finished turn');+ const before = h.sqlite!.prepare('SELECT * FROM bot_delegations WHERE id=?').get(task.delegationId);+ const select = h.db!.select.bind(h.db!);+ read = vi.spyOn(h.db!, 'select').mockImplementation(fields => {+ const query = select(fields);+ const keys = Object.keys(fields ?? {});+ if ((boundary === 'requester-read' && keys.length === 4 && keys.includes('profileStatus'))+ || (boundary === 'child-read' && keys.includes('source') && keys.includes('status')+ && (mode === 'reopen' ? keys.includes('workingDir') : keys.length === 2))) {+ // Force the private-state failure branch, rather than relying on a+ // later mutation check to reject an otherwise valid preparation.+ h.sqlite!.prepare("UPDATE sessions SET status='archived' WHERE id=?")+ .run(boundary === 'requester-read' ? 'session-1' : task.childSessionId);+ queueMicrotask(() => { revoked = true; });+ }+ return query;+ });+ runtime.dispatch.mockClear();+ armed = true;+ expect(await runtime.delegation.messageSessionTask('group-lane', task.delegationId,+ mode === 'resume' ? { kind: 'resume' } : { kind: 'message', text: 'Continue work' }))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(revoked).toBe(true);+ expect(mutation).not.toHaveBeenCalled();+ if (mode === 'reopen' && boundary !== 'reconcile') expect(reconciliations).toBe(1);+ expect(runtime.dispatch).not.toHaveBeenCalled();+ expect(h.sqlite!.prepare('SELECT * FROM bot_delegations WHERE id=?').get(task.delegationId)).toEqual(before);+ } finally { read?.mockRestore(); release(); runtime.dispose(); }+ });++ it.each(['reconciliation', 'resume-flush', 'resume-commit', 'release'] as const)('keeps a paused task held if group authority is revoked during %s', async boundary => {+ await seedPair(); seedGroupLane();+ let revoke = false;+ let live = true;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => live, validate: async () => {} });+ const runtime = createDelegationRuntime({ taskControl: true, queueSnapshots: new Map(),+ appliedOnResume: () => { if (revoke && boundary === 'release') live = false; return []; },+ reconcileWorktree: async () => { if (revoke && boundary === 'reconciliation') live = false; } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture-only paused task' });+ if (!task.ok) throw new Error(task.message);+ await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ await runtime.settleChild(task.childSessionId, 'Paused');+ const paused = h.sqlite!.prepare('SELECT status, permission_snapshot_json FROM bot_delegations WHERE id=?').get(task.delegationId) as { status: string; permission_snapshot_json: string };+ revoke = true;+ if (boundary === 'resume-flush') runtime.flushInput.mockImplementationOnce(async () => { live = false; });+ if (boundary === 'resume-commit') {+ h.sqlite!.function('revoke_group_resume', () => { queueMicrotask(() => { live = false; }); return 1; });+ h.sqlite!.exec(`CREATE TEMP TRIGGER revoke_resume AFTER UPDATE OF permission_snapshot_json ON bot_delegations+ WHEN json_extract(OLD.permission_snapshot_json, '$.taskPause') IS NOT NULL+ AND json_extract(NEW.permission_snapshot_json, '$.taskPause') IS NULL+ BEGIN SELECT revoke_group_resume(); END`);+ }+ const before = runtime.started.length;+ expect(await runtime.delegation.messageSessionTask('group-lane', task.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(true);+ expect(runtime.started).toHaveLength(before);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ ok: true, task: { control: { state: 'paused', queue_held: true } } });+ const restored = h.sqlite!.prepare('SELECT status, permission_snapshot_json FROM bot_delegations WHERE id=?').get(task.delegationId) as typeof paused;+ expect(restored.status).toBe(paused.status);+ expect(JSON.parse(restored.permission_snapshot_json).taskPause).toEqual(JSON.parse(paused.permission_snapshot_json).taskPause);+ expect(JSON.parse(restored.permission_snapshot_json).taskResume).toBeUndefined();+ h.sqlite!.exec('DROP TRIGGER IF EXISTS revoke_resume');+ // The owner can retry with the same queued receipt; no stuck resuming card+ // or replacement group lease is required to release the original pause.+ revoke = false;+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'resume' }))+ .toMatchObject({ ok: true, resumed: true });+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(false);+ } finally { h.sqlite!.exec('DROP TRIGGER IF EXISTS revoke_resume'); release(); runtime.dispose(); }+ });++ it.each(['pause', 'cancel', 'request-stop'] as const)('does not %s the runtime after losing group authority at the reservation boundary', async mode => {+ await seedPair(); seedGroupLane();+ let live = true;+ let revoke = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => live, validate: async () => {} });+ const runtime = createDelegationRuntime({ taskControl: true, withSessionLock: async (_id, operation) => {+ if (revoke) live = false;+ await operation();+ } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture-only control task' });+ if (!task.ok) throw new Error(task.message);+ const before = h.sqlite!.prepare('SELECT * FROM bot_delegations WHERE id=?').get(task.delegationId);+ revoke = true;+ expect(await runtime.delegation.stopSessionTask('group-lane', task.delegationId, mode))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(runtime.stopTurn).not.toHaveBeenCalled();+ expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(false);+ expect(h.sqlite!.prepare('SELECT * FROM bot_delegations WHERE id=?').get(task.delegationId)).toEqual(before);+ } finally { release(); runtime.dispose(); }+ });++ it.each((['pause', 'cancel'] as const).flatMap(mode =>+ (['running', 'queued', 'paused'] as const).flatMap(state =>+ (['intent-write', 'input-boundary'] as const).map(boundary => ({ mode, state, boundary })))))+ ('restores $state task state when group $mode loses authority during $boundary', async ({ mode, state, boundary }) => {+ await seedPair(); seedGroupLane();+ vi.useFakeTimers();+ let revoked = false;+ let unavailable = state === 'queued';+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const runtime = createDelegationRuntime({ taskControl: true, transientUnavailable: () => unavailable });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Keep independent work running.', timeoutMs: 10_000 });+ if (!task.ok) throw new Error(task.message);+ if (state === 'paused') await runtime.delegation.stopSessionTask('session-1', task.delegationId, 'pause');+ runtime.stopTurn.mockClear();+ const before = h.sqlite!.prepare('SELECT * FROM bot_delegations WHERE id=?').get(task.delegationId);+ const cardBefore = await runtime.delegation.getSessionTask('session-1', task.delegationId);+ if (boundary === 'intent-write') {+ h.sqlite!.function('revoke_group_control', () => { queueMicrotask(() => { revoked = true; }); return 1; });+ h.sqlite!.exec("CREATE TEMP TRIGGER revoke_control AFTER UPDATE OF permission_snapshot_json ON bot_delegations BEGIN SELECT revoke_group_control(); END");+ } else {+ runtime.waitForInputBoundary.mockImplementationOnce(async () => { revoked = true; });+ }+ expect(await runtime.delegation.stopSessionTask('group-lane', task.delegationId, mode))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ h.sqlite!.exec('DROP TRIGGER IF EXISTS revoke_control');+ expect(revoked).toBe(true);+ expect(runtime.stopTurn).not.toHaveBeenCalled();+ expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(state === 'paused');+ expect(h.sqlite!.prepare('SELECT * FROM bot_delegations WHERE id=?').get(task.delegationId)).toEqual(before);+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toEqual(cardBefore);+ 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 revoke_control');+ release(); runtime.dispose(); vi.useRealTimers();+ }+ });++ it.each(['caller-read', 'profile-read', 'model-invalid', 'model-error', 'model-workspace', 'model-directory'] as const)+ ('rejects revoked group start preflight at %s without private results or workspace writes', async boundary => {+ await seedPair({ taskModelOverride: { harness: 'pi', model: 'grok-4.5', providerId: PROVIDER, effort: 'high', fastMode: false } }); seedGroupLane();+ let revoked = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const model = { harness: 'pi' as const, model: 'grok-4.5', providerId: PROVIDER, effort: 'high', fastMode: false };+ const runtime = createDelegationRuntime({+ validateTaskModel: async () => { if (boundary === 'model-invalid') { revoked = true; return false; } return true; },+ resolveTaskModelSelection: async () => { revoked = true; if (boundary === 'model-error') throw new Error('Private model unavailable'); return model; },+ });+ const before = h.sqlite!.prepare('SELECT count(*) FROM sessions').pluck().get();+ const mkdir = vi.spyOn(fsPromises, 'mkdir');+ const select = h.db!.select.bind(h.db!);+ const read = vi.spyOn(h.db!, 'select').mockImplementation(fields => {+ const query = select(fields);+ if ((boundary === 'caller-read' && fields && Object.keys(fields).includes('fastMode') && Object.keys(fields).includes('model'))+ || (boundary === 'profile-read' && fields && Object.keys(fields).length === 1 && Object.keys(fields)[0] === 'config')) {+ queueMicrotask(() => { revoked = true; });+ }+ return query;+ });+ try {+ expect(await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Preflight fixture',+ ...(boundary.startsWith('model-') && boundary !== 'model-invalid' ? { modelSelection: { id: 'fixture' } } : {}),+ ...(boundary === 'model-directory' ? { workingDir: 'not-an-absolute-directory' } : {}),+ })).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(revoked).toBe(true);+ expect(mkdir).not.toHaveBeenCalled();+ expect(runtime.dispatch).not.toHaveBeenCalled();+ expect(h.sqlite!.prepare('SELECT count(*) FROM sessions').pluck().get()).toBe(before);+ expect(h.sqlite!.prepare('SELECT count(*) FROM bot_delegations').pluck().get()).toBe(0);+ } finally { read.mockRestore(); mkdir.mockRestore(); release(); runtime.dispose(); }+ });++ it.each(['valid', 'revoked', 'ended'] as const)('cancels group delegation input at the actual host accepted adapter: %s', async condition => {+ await seedPair(); seedGroupLane();+ let draining = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner',+ isCurrent: () => !(draining && condition === 'ended'),+ validate: async () => { if (draining && condition === 'revoked') throw new GroupToolAuthorizationError(); } });+ const source = readFileSync(resolve(__dirname, '../../../maker-ipc/register.ts'), 'utf8');+ const start = source.indexOf(' dispatch: ({ targetSessionId, message, persistedContent, clientId, onAccepted, dispatcherSessionId }) =>');+ const end = source.indexOf(' discardDelegationQueuedInputs:', start);+ expect(start).toBeGreaterThan(0); expect(end).toBeGreaterThan(start);+ const adapter = transpileModule(`return ({${source.slice(start, end)}}).dispatch;`, { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText;+ type Dispatch = Parameters<typeof createBotDelegationService>[0]['dispatch'];+ let input: Parameters<Dispatch>[0] | undefined;+ let armed = false;+ const runtime = createDelegationRuntime({ decorateDispatch: dispatch => {+ const capture: Dispatch = async params => { input = params; return { ok: true, targetSessionId: params.targetSessionId, wakeKind: 'queued' }; };+ const host = new Function('dispatchBotSessionMessage', 'AcceptedCallbackDispatchCancelled', 'GroupToolAuthorizationError', adapter)(capture, AcceptedCallbackDispatchCancelled, GroupToolAuthorizationError) as Dispatch;+ return params => armed ? host(params) : dispatch(params);+ } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Accepted boundary fixture.' });+ if (!task.ok) throw new Error(task.message);+ armed = true;+ await runtime.delegation.messageSessionTask('group-lane', task.delegationId, { kind: 'message', text: 'Follow-up input.' });+ expect(input?.onAccepted).toBeTypeOf('function');+ const vendor = vi.fn();+ draining = true;+ const drain = async () => { await runAcceptedCallback(input!.onAccepted, input!.targetSessionId, input!.clientId!, { warn: vi.fn() }); vendor(); };+ if (condition === 'valid') { await drain(); expect(vendor).toHaveBeenCalledOnce(); }+ else { await expect(drain()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled); expect(vendor).not.toHaveBeenCalled(); }+ } finally { release(); runtime.dispose(); }+ });++ it.each(['target-read', 'input-check', 'item-build', 'valid'] as const)('revalidates group steer after %s', async boundary => {+ await seedPair(); seedGroupLane();+ let revoked = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const inject = vi.fn(async () => true);+ const live = { agentKind: 'pi' as const, capabilities: { sameTurnSteer: { supported: true } },+ isTurnRunning: () => true, getTurnGeneration: () => 1, requestGracefulStop: vi.fn(), getTurnControlSnapshot: vi.fn() };+ let targetChecked = false;+ const controls = createSessionControlService({+ getLiveSession: () => boundary === 'target-read' && !targetChecked ? null : live,+ sessionExists: async () => { targetChecked = true; if (boundary === 'target-read') revoked = true; return true; },+ assertExternalInputAllowed: async () => { if (boundary === 'input-check') revoked = true; },+ createQueuedMessage: async () => { if (boundary === 'item-build') revoked = true; return {} as AgentInputQueuedMessage; },+ steerQueuedMessage: inject, getQueueSnapshot: vi.fn(), replaceQueuedMessage: vi.fn(), removeQueuedMessage: vi.fn(),+ getSessionActivitySnapshot: vi.fn(), getSessionRuntimeDetails: vi.fn(), setSessionRuntime: vi.fn(),+ steerStoredQueuedMessage: vi.fn(), moveQueuedMessage: vi.fn(), createId: () => 'steer-fixture',+ });+ const runtime = createDelegationRuntime({ taskControl: true });+ runtime.steer.mockImplementation(params => controls.steerSession(params));+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Steer boundary fixture.' });+ if (!task.ok) throw new Error(task.message);+ const result = await runtime.delegation.messageSessionTask('group-lane', task.delegationId, { kind: 'message', mode: 'steer', text: 'Same-turn input.' });+ if (boundary === 'valid') { expect(result).toMatchObject({ ok: true }); expect(inject).toHaveBeenCalledOnce(); }+ else { expect(result).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' }); expect(inject).not.toHaveBeenCalled(); }+ } finally { release(); runtime.dispose(); }+ });++ it.each((['request-stop', 'pause'] as const).flatMap(mode =>+ [true, false].map(revoke => ({ mode, revoke }))))+ ('revalidates $mode after the native stop target lookup (revoked=$revoke)', async ({ mode, revoke }) => {+ await seedPair(); seedGroupLane();+ let revoked = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const nativeStop = vi.fn(async () => ({ status: 'requested' as const, turnGeneration: 1 }));+ const live = { agentKind: 'pi' as const, requestGracefulStop: nativeStop };+ let targetChecked = false;+ const controls = createSessionControlService({+ getLiveSession: () => targetChecked ? live : null,+ sessionExists: async () => { targetChecked = true; revoked = revoke; return true; },+ } as never);+ const runtime = createDelegationRuntime({ taskControl: true });+ runtime.stopTurn.mockImplementation(params => controls.stopSessionTurn(params));+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Native stop admission fixture.' });+ if (!task.ok) throw new Error(task.message);+ const before = h.sqlite!.prepare('SELECT status, permission_snapshot_json FROM bot_delegations WHERE id=?').get(task.delegationId);+ const result = await runtime.delegation.stopSessionTask('group-lane', task.delegationId, mode);+ if (revoke) {+ expect(result).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(nativeStop).not.toHaveBeenCalled();+ expect(runtime.preparePause).not.toHaveBeenCalled();+ expect(runtime.flushInput).not.toHaveBeenCalled();+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(false);+ expect(h.sqlite!.prepare('SELECT status, permission_snapshot_json FROM bot_delegations WHERE id=?').get(task.delegationId)).toEqual(before);+ } else {+ expect(result).toMatchObject({ ok: true });+ expect(nativeStop).toHaveBeenCalledOnce();+ expect(runtime.heldInputs.has(task.childSessionId)).toBe(mode === 'pause');+ }+ } finally { release(); runtime.dispose(); }+ });++ it.each((['edit', 'withdraw'] as const).flatMap(operation =>+ (['target-read', 'queue-read', 'valid'] as const).map(boundary => ({ operation, boundary }))))+ ('checks group authority at the $operation queue mutation after $boundary', async ({ operation, boundary }) => {+ await seedPair(); seedGroupLane();+ let revoked = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const original: AgentInputQueuedMessage = {+ clientId: 'fixture-queued', text: 'Original input', persistedContent: 'Original input',+ model: 'grok-4.5', effort: 'high', permissionMode: 'auto', workingDir: h.userDataDir,+ chatMessage: { clientId: 'fixture-queued', role: 'user', content: 'Original input' },+ createOpts: { agentKind: 'pi', model: 'grok-4.5', effort: 'high', permissionMode: 'auto', workingDir: h.userDataDir },+ origin: { kind: 'session', senderSessionId: 'group-lane', displayText: 'Original input' },+ };+ let queue = [original];+ const replace = vi.fn((_session: string, _id: string, next: AgentInputQueuedMessage) => { queue = [next]; return true; });+ const remove = vi.fn(() => { queue = []; return true; });+ const queueControl = createSessionControlService({+ getLiveSession: () => null,+ sessionExists: async () => { if (boundary === 'target-read') revoked = true; return true; },+ getQueueSnapshot: async () => { if (boundary === 'queue-read') revoked = true; return { pendingQueue: queue, consumingClientIds: [] }; },+ replaceQueuedMessage: replace, removeQueuedMessage: remove,+ getSessionActivitySnapshot: vi.fn(), getSessionRuntimeDetails: vi.fn(), setSessionRuntime: vi.fn(),+ assertExternalInputAllowed: vi.fn(), createQueuedMessage: vi.fn(), steerQueuedMessage: vi.fn(),+ steerStoredQueuedMessage: vi.fn(), moveQueuedMessage: vi.fn(), createId: () => 'unused',+ });+ const runtime = createDelegationRuntime({ taskControl: true, taskQueue: {+ inspect: vi.fn(), update: params => queueControl.updateQueuedMessage(params),+ cancel: params => queueControl.cancelQueuedMessage(params),+ } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Queue controls fixture.' });+ if (!task.ok) throw new Error(task.message);+ const result = await runtime.delegation.messageSessionTask('group-lane', task.delegationId,+ operation === 'edit' ? { kind: 'edit', queuedMessageId: 'fixture-queued', text: 'Updated input' }+ : { kind: 'withdraw', queuedMessageId: 'fixture-queued' });+ if (boundary === 'valid') {+ expect(result).toMatchObject({ ok: true });+ expect(operation === 'edit' ? replace : remove).toHaveBeenCalledOnce();+ if (operation === 'edit') expect(queue[0].persistedContent).toBe('Updated input');+ else expect(queue).toEqual([]);+ expect(runtime.flushInput).toHaveBeenCalledOnce();+ } else {+ expect(revoked).toBe(true);+ expect(result).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(queue).toEqual([original]);+ expect(replace).not.toHaveBeenCalled(); expect(remove).not.toHaveBeenCalled();+ expect(runtime.flushInput).not.toHaveBeenCalled();+ }+ } finally { release(); runtime.dispose(); }+ });++ it.each([+ { path: 'preflight', read: 1, expected: 'CONCURRENCY_LIMIT' },+ { path: 'cancel', read: 1, expected: 'ALREADY_TERMINAL' },+ { path: 'reply', read: 2, expected: 'WRONG_REPLY_KIND' },+ { path: 'interject', read: 3, expected: 'SESSION_TASK_NOT_READY' },+ ])('revalidates after the $path task read before returning $expected', async ({ path, read, expected }) => {+ await seedPair(); seedGroupLane();+ let revoked = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const runtime = createDelegationRuntime({ maxActiveChildren: 1 });+ let restore = () => {};+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Private task state fixture.' });+ if (!task.ok) throw new Error(task.message);+ if (path === 'cancel') h.sqlite!.prepare("UPDATE bot_delegations SET status='completed' WHERE id=?").run(task.delegationId);+ if (path === 'interject') h.sqlite!.prepare("UPDATE bot_delegations SET status='queued' WHERE id=?").run(task.delegationId);+ if (path === 'reply') await runtime.delegation.handleInteractionStart(task.childSessionId,+ { kind: 'permission', requestId: 'fixture-private-approval', toolName: 'write_file', input: {} });+ const call = () => path === 'preflight'+ ? runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Another task.' })+ : path === 'cancel' ? runtime.delegation.cancelDelegation('group-lane', task.delegationId)+ : runtime.delegation.messageSessionTask('group-lane', task.delegationId, { kind: 'message', text: 'Follow-up.' });+ expect(await call()).toMatchObject({ ok: false, errorCode: expected });+ runtime.dispatch.mockClear(); runtime.abortSession.mockClear();+ const before = h.sqlite!.prepare('SELECT * FROM bot_delegations WHERE id=?').get(task.delegationId);+ let taskReads = 0;+ const select = h.db!.select.bind(h.db!);+ const spy = vi.spyOn(h.db!, 'select').mockImplementation(fields => {+ const query = select(fields);+ const from = query.from.bind(query);+ vi.spyOn(query, 'from').mockImplementation(table => {+ const result = from(table);+ if (table === botDelegations && ++taskReads === read) queueMicrotask(() => { revoked = true; });+ return result;+ });+ return query;+ });+ restore = () => spy.mockRestore();+ expect(await call()).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(taskReads).toBe(read); expect(revoked).toBe(true);+ expect(runtime.dispatch).not.toHaveBeenCalled(); expect(runtime.abortSession).not.toHaveBeenCalled();+ expect(h.sqlite!.prepare('SELECT * FROM bot_delegations WHERE id=?').get(task.delegationId)).toEqual(before);+ } finally { restore(); release(); runtime.dispose(); }+ });++ it.each((['inspect', 'advance'] as const).flatMap(operation =>+ (['NOT_FOUND', 'UNSUPPORTED_CAPABILITY', 'CHILD_SESSION_INVALID', 'TASK_ACTIVE', 'route-result'] as const)+ .map(branch => ({ operation, branch }))))('revalidates group authority before $operation returns $branch', async ({ operation, branch }) => {+ await seedPair(); seedGroupLane();+ let revoked = false;+ let revokeDuringRead = false;+ let crossed = false;+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const inspect = vi.fn(async () => {+ if (branch === 'route-result' && revokeDuringRead) { crossed = true; revoked = true; }+ return { ok: false as const, errorCode: 'UNSUPPORTED_CAPABILITY', message: 'Fixture route result' };+ });+ const advance = vi.fn(async () => ({ ok: true as const, status: 'applied' as const, generation: 8 }));+ const runtime = createDelegationRuntime({ taskRoute: branch === 'UNSUPPORTED_CAPABILITY' ? undefined : { inspect, advance } });+ let restore = () => {};+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture-only route reads' });+ if (!task.ok) throw new Error(task.message);+ if (branch === 'route-result') await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'error', error: 'Fixture stop' });+ if (branch === 'CHILD_SESSION_INVALID') h.sqlite!.prepare("UPDATE sessions SET status='deleted' WHERE id=?").run(task.childSessionId);+ const taskId = branch === 'NOT_FOUND' ? 'absent-fixture-task' : task.delegationId;+ const call = () => operation === 'inspect'+ ? runtime.delegation.inspectSessionTaskRoute('group-lane', taskId)+ : runtime.delegation.advanceSessionTaskRoute('group-lane', taskId, 7, 'fixture-token');+ expect(await call()).toMatchObject({ ok: false, errorCode: branch === 'route-result' ? 'UNSUPPORTED_CAPABILITY' : branch });+ const select = h.db!.select.bind(h.db!);+ const spy = vi.spyOn(h.db!, 'select').mockImplementation(fields => {+ const query = select(fields);+ const from = query.from.bind(query);+ vi.spyOn(query, 'from').mockImplementation(table => {+ const result = from(table);+ const atTaskRead = branch === 'NOT_FOUND' || branch === 'UNSUPPORTED_CAPABILITY';+ if (branch !== 'route-result' && (atTaskRead ? table === botDelegations : fields?.status === sessions.status && Object.keys(fields).length === 1)) {+ crossed = true;+ queueMicrotask(() => { revoked = true; });+ }+ return result;+ });+ return query;+ });+ restore = () => spy.mockRestore();+ revokeDuringRead = true;+ expect(await call()).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(crossed).toBe(true);+ expect(advance).not.toHaveBeenCalled();+ } finally { restore(); release(); runtime.dispose(); }+ });++ it('rejects changing a task model when the originating group execution is replaced during route inspection', async () => {+ await seedPair(); seedGroupLane();+ const grant = { botId: 'bot-a', mode: 'owner' as const, isCurrent: () => true, validate: async () => {} };+ const release = registerGroupToolAuthority('group-lane', grant);+ let releaseReplacement = () => {};+ let replace = false;+ const current = { agentKind: 'codex' as const, model: 'same-model', providerId: 'subscription', effort: null, fastMode: false };+ const next = { ...current, providerId: 'paid' };+ const advance = vi.fn(async () => ({ ok: true as const, status: 'applied' as const, generation: 8 }));+ const runtime = createDelegationRuntime({ taskRoute: { advance, inspect: async () => {+ if (replace) releaseReplacement = registerGroupToolAuthority('group-lane', { ...grant });+ return { ok: true, generation: 7, current, next };+ } } });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture-only model control' });+ if (!task.ok) throw new Error(task.message);+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome: 'error', error: 'Fixture stop' });+ const preview = await runtime.delegation.inspectSessionTaskRoute('group-lane', task.delegationId);+ if (!preview.ok) throw new Error(preview.message);+ replace = true;+ expect(await runtime.delegation.advanceSessionTaskRoute('group-lane', task.delegationId, 7, preview.selectionToken!))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(advance).not.toHaveBeenCalled();+ } finally { release(); releaseReplacement(); runtime.dispose(); }+ });++ it('does not let a non-owner tools grant enumerate application capabilities or model routes', async () => {+ await seedPair(); seedGroupLane();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'tools', isCurrent: () => true, validate: async () => {} });+ const listMcpServers = vi.fn(capabilityDeps.listMcpServers);+ const getPluginRegistry = vi.fn(capabilityDeps.getPluginRegistry);+ const service = createBotCapabilityService({ ...capabilityDeps, listMcpServers, getPluginRegistry });+ try {+ for (const kind of ['skill', 'mcp', 'toolset'] as const)+ expect(await service.list({ callerSessionId: 'group-lane', kind }))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(await service.models({ callerSessionId: 'group-lane' }))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(listMcpServers).not.toHaveBeenCalled();+ expect(getPluginRegistry).not.toHaveBeenCalled();+ // The owner can still discover their own configuration through a fresh owner execution.+ release();+ const releaseOwner = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ try {+ expect(await service.list({ callerSessionId: 'group-lane', kind: 'mcp' })).toMatchObject({ ok: true });+ expect(listMcpServers).toHaveBeenCalledOnce();+ } finally { releaseOwner(); }+ } finally { release(); }+ });++ it.each([+ { label: 'null override', config: { modelChainOverride: null } },+ { label: 'legacy default marker', config: { modelOverride: null, model: 'stale-profile-model' } },+ { label: 'no explicit route', config: {} },+ { label: 'empty chains', config: { modelChainOverride: [], modelChain: [] } },+ { label: 'invalid override', config: { modelChainOverride: [{ harness: 'pi' }] } },+ ])('keeps inherited application models private for group self-read: $label', async ({ config }) => {+ await seedPair(); seedGroupLane();+ h.sqlite!.prepare("UPDATE bot_profile_versions SET capabilities_json=? WHERE bot_id='bot-a'").run(JSON.stringify(config));+ const settings = await import('../../../maker-host/bot-model-chain-settings-store.js');+ const resolve = vi.spyOn(settings, 'readEffectiveBotModelChain');+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'tools', isCurrent: () => true, validate: async () => {} });+ let releaseOwner = () => {};+ const service = createBotCapabilityService(capabilityDeps);+ try {+ expect(await service.inspect({ callerSessionId: 'group-lane' })).toMatchObject({+ ok: true, state: { profile: { id: 'bot-a' }, model: { source: 'default', candidates: [] }, memory: { scope: 'self' } },+ });+ expect(resolve).not.toHaveBeenCalled();+ release();+ releaseOwner = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ const owner = await service.inspect({ callerSessionId: 'group-lane' });+ expect(owner).toMatchObject({ ok: true });+ expect(resolve).toHaveBeenCalledOnce();+ const canonical = await service.inspect({ callerSessionId: 'session-1' });+ if (!owner.ok || !canonical.ok) throw new Error('Owner state unavailable');+ expect(owner.state.model.candidates.length).toBeGreaterThan(0);+ expect(owner.state.model).toEqual(canonical.state.model);+ } finally { release(); releaseOwner(); resolve.mockRestore(); }+ });++ it.each([+ { modelChainOverride: [{ harness: 'pi', model: 'own-model', providerId: 'own-provider' }] },+ { modelChain: [{ harness: 'pi', model: 'own-model', providerId: 'own-provider' }] },+ { harness: 'pi', model: 'own-model', providerId: 'own-provider' },+ ])('preserves explicit Profile model selection in authorized group self-reads: %j', async config => {+ await seedPair(); seedGroupLane();+ h.sqlite!.prepare("UPDATE bot_profile_versions SET capabilities_json=? WHERE bot_id='bot-a'").run(JSON.stringify(config));+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'tools', isCurrent: () => true, validate: async () => {} });+ h.listProviders.mockClear();+ try {+ expect(await createBotCapabilityService(capabilityDeps).inspect({ callerSessionId: 'group-lane' })).toMatchObject({+ ok: true, state: { model: { source: 'override', candidates: [expect.objectContaining({ harness: 'pi', model: 'own-model', providerId: 'own-provider' })] } },+ });+ expect(h.listProviders).not.toHaveBeenCalled();+ } finally { release(); }+ });++ it.each(['skill', 'mcp', 'toolset', 'models', 'profile', 'own-skills'] as const)(+ 'revalidates server authority after reading %s even while the local execution remains current', async surface => {+ await seedPair(); seedGroupLane();+ let serverAuthorized = true;+ let revokeDuringRead = false;+ const readFinished = vi.fn(() => { if (revokeDuringRead) serverAuthorized = false; });+ const validate = vi.fn(async () => { if (!serverAuthorized) throw new GroupToolAuthorizationError(); });+ const release = registerGroupToolAuthority('group-lane', {+ botId: 'bot-a', mode: surface === 'profile' || surface === 'own-skills' ? 'tools' : 'owner',+ isCurrent: () => true, validate,+ });+ const afterRead = async <T,>(read: () => Promise<T>): Promise<T> => {+ const result = await read();+ readFinished();+ return result;+ };+ const deps: BotCapabilityServiceDeps = { ...capabilityDeps };+ const restore: Array<() => void> = [];+ if (surface === 'skill') deps.getMaker = () => ({+ listAgentSkills: (...args) => afterRead(() => getMaker().listAgentSkills(...args)),+ });+ if (surface === 'mcp') deps.listMcpServers = input => afterRead(() => capabilityDeps.listMcpServers(input));+ if (surface === 'toolset') deps.getPluginRegistry = () => ({+ getPlugins: () => getPluginRegistry().getPlugins(),+ getEnableState: (...args) => afterRead(() => getPluginRegistry().getEnableState(...args)),+ });+ if (surface === 'models') {+ h.listProviders.mockImplementation(async () => afterRead(async () => h.providers));+ restore.push(() => h.listProviders.mockImplementation(async () => h.providers));+ }+ if (surface === 'profile') {+ const settings = await import('../../../maker-host/bot-model-chain-settings-store.js');+ const read = settings.readEffectiveBotModelChain;+ const spy = vi.spyOn(settings, 'readEffectiveBotModelChain').mockImplementation((...args) => afterRead(() => read(...args)));+ restore.push(() => spy.mockRestore());+ }+ if (surface === 'own-skills') {+ const index = await import('../../../maker-ipc/botSkillQueryIndex.js');+ const read = index.queryBotSkillIndex;+ const spy = vi.spyOn(index, 'queryBotSkillIndex').mockImplementation((...args) => afterRead(() => read(...args)));+ restore.push(() => spy.mockRestore());+ }+ const service = createBotCapabilityService(deps);+ const read = () => surface === 'models' ? service.models({ callerSessionId: 'group-lane' })+ : surface === 'profile' ? service.inspect({ callerSessionId: 'group-lane' })+ : surface === 'own-skills' ? listBotSkillsForSession({ callerSessionId: 'group-lane' })+ : service.list({ callerSessionId: 'group-lane', kind: surface });+ try {+ expect(await read()).toMatchObject({ ok: true });+ expect(readFinished).toHaveBeenCalled();+ expect(validate).toHaveBeenCalledTimes(2);+ readFinished.mockClear(); validate.mockClear();+ revokeDuringRead = true;+ expect(await read()).toEqual({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED', message: expect.any(String) });+ expect(readFinished).toHaveBeenCalled();+ expect(validate).toHaveBeenCalledTimes(2);+ } finally { release(); for (const reset of restore) reset(); }+ },+ );+it.each(['delete-first', 'message-first'])('serializes shared-history writes and deletion (%s)', async (order) => {await seedPair();const target = await invoke('local-db:bots:create-canonical-session', {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesWriteReadback.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesWriteReadback.test.tsindex 0dfc440817..2d3eb87cac 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesWriteReadback.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesWriteReadback.test.ts@@ -121,6 +121,117 @@ describe('message write paths avoid large-content readback', () => {setupDb();});+ it.each([false, true])('publishes only after the post-write guard succeeds (revoked=%s)', async revoked => {+ const { tapWindowBroadcast } = await import('../../../device-link/broadcast-tap');+ const { onMessageCreated } = await import('../../../embedders/chat-history-embedder');+ const { recordPrRefsForMessage } = await import('../../../git-context/prRefsStore');+ vi.mocked(tapWindowBroadcast).mockClear();+ vi.mocked(onMessageCreated).mockClear();+ vi.mocked(recordPrRefsForMessage).mockClear();+ const beforePublish = vi.fn(async () => {+ const published = beforePublish.mock.calls.length === 2;+ expect(h.sqlite!.prepare('SELECT count(*) FROM messages').pluck().get()).toBe(published ? 1 : 0);+ expect(h.sqlite!.prepare('SELECT count(*) FROM temp.cindy_pending_message_publications').pluck().get()).toBe(published ? 0 : 1);+ expect(tapWindowBroadcast).not.toHaveBeenCalled();+ expect(h.mediaRefCalls).toEqual([]);+ expect(onMessageCreated).not.toHaveBeenCalled();+ expect(recordPrRefsForMessage).not.toHaveBeenCalled();+ if (revoked) throw new Error('revoked at server');+ });+ const sending = createMessage('s1', { clientId: 'private-message', role: 'assistant', content: 'Private result' }, { beforePublish });+ if (revoked) {+ await expect(sending).rejects.toThrow('revoked at server');+ expect(h.sqlite!.prepare('SELECT count(*) FROM messages').pluck().get()).toBe(0);+ expect(tapWindowBroadcast).not.toHaveBeenCalled();+ expect(h.mediaRefCalls).toEqual([]);+ expect(onMessageCreated).not.toHaveBeenCalled();+ expect(recordPrRefsForMessage).not.toHaveBeenCalled();+ } else {+ await expect(sending).resolves.toMatchObject({ clientId: 'private-message', content: 'Private result' });+ expect(h.sqlite!.prepare('SELECT client_id, rewind_at FROM messages').get()).toEqual({ client_id: 'private-message', rewind_at: null });+ expect(tapWindowBroadcast).toHaveBeenCalledWith('local-db:messages:created', expect.anything());+ expect(h.mediaRefCalls).toHaveLength(1);+ await createMessage('s1', { clientId: 'private-message', role: 'assistant', content: 'Private result' }, { beforePublish });+ expect(beforePublish).toHaveBeenCalledTimes(2);+ expect(h.sqlite!.prepare('SELECT count(*) FROM messages').pluck().get()).toBe(1);+ }+ expect(h.sqlite!.prepare('SELECT count(*) FROM temp.cindy_pending_message_publications').pluck().get()).toBe(0);+ });++ it.each([false, true])('rolls back a publication revoked during commit before delivery hooks (lostReceipt=%s)', async lostReceipt => {+ const { tapWindowBroadcast } = await import('../../../device-link/broadcast-tap');+ const { onMessageCreated } = await import('../../../embedders/chat-history-embedder');+ const { recordPrRefsForMessage } = await import('../../../git-context/prRefsStore');+ vi.mocked(tapWindowBroadcast).mockClear();+ vi.mocked(onMessageCreated).mockClear();+ vi.mocked(recordPrRefsForMessage).mockClear();+ let revoked = false;+ h.client.tx.mockImplementation(async (name: string, args: { publication?: string }) => {+ const result = runInprocTx(h.sqlite!, { name, args });+ if (args.publication === 'publish') {+ revoked = true;+ if (lostReceipt) throw new Error('Publication receipt lost');+ }+ return result;+ });+ const beforePublish = vi.fn(async () => {+ if (revoked) throw new Error('revoked during commit');+ });+ const body = { clientId: 'revoked-publication', role: 'assistant' as const, content: 'Private result' };+ await expect(createMessage('s1', body, { beforePublish })).rejects.toThrow('revoked during commit');+ expect(beforePublish).toHaveBeenCalledTimes(2);+ expect(h.sqlite!.prepare('SELECT count(*) FROM messages').pluck().get()).toBe(0);+ expect(h.sqlite!.prepare('SELECT count(*) FROM temp.cindy_pending_message_publications').pluck().get()).toBe(0);+ expect(tapWindowBroadcast).not.toHaveBeenCalled();+ expect(h.mediaRefCalls).toEqual([]);+ expect(onMessageCreated).not.toHaveBeenCalled();+ expect(recordPrRefsForMessage).not.toHaveBeenCalled();+ // The same client receipt can be retried once permission is available again.+ h.client.tx.mockImplementation(async (name: string, args: unknown) => runInprocTx(h.sqlite!, { name, args }));+ revoked = false;+ await expect(createMessage('s1', body, { beforePublish })).resolves.toMatchObject(body);+ expect(h.sqlite!.prepare('SELECT count(*) FROM messages').pluck().get()).toBe(1);+ expect(onMessageCreated).toHaveBeenCalledOnce();+ });++ it.each(['committed', 'not-committed', 'mismatched'] as const)('recovers only an exact committed publication after a lost receipt: %s', async outcome => {+ const { tapWindowBroadcast } = await import('../../../device-link/broadcast-tap');+ const { onMessageCreated } = await import('../../../embedders/chat-history-embedder');+ const { recordPrRefsForMessage } = await import('../../../git-context/prRefsStore');+ vi.mocked(tapWindowBroadcast).mockClear();+ vi.mocked(onMessageCreated).mockClear();+ vi.mocked(recordPrRefsForMessage).mockClear();+ h.client.tx.mockImplementation(async (name: string, args: { publication?: string }) => {+ if (args.publication !== 'publish') return runInprocTx(h.sqlite!, { name, args });+ if (outcome !== 'not-committed') {+ runInprocTx(h.sqlite!, { name, args });+ if (outcome === 'mismatched') h.sqlite!.prepare("UPDATE messages SET content='Different result'").run();+ }+ throw new Error('Publication receipt lost');+ });+ const beforePublish = vi.fn(async () => {});+ const body = { clientId: 'lost-receipt', role: 'assistant' as const, content: 'Private result' };+ const sending = createMessage('s1', body, { beforePublish });+ if (outcome === 'committed') {+ const receipt = await sending;+ expect(receipt).toMatchObject(body);+ expect(await createMessage('s1', body, { beforePublish })).toEqual(receipt);+ expect(beforePublish).toHaveBeenCalledTimes(2);+ expect(vi.mocked(tapWindowBroadcast).mock.calls.filter(([channel]) => channel === 'local-db:messages:created')).toHaveLength(1);+ expect(h.mediaRefCalls).toHaveLength(1);+ expect(onMessageCreated).toHaveBeenCalledOnce();+ expect(recordPrRefsForMessage).toHaveBeenCalledOnce();+ } else {+ await expect(sending).rejects.toThrow('Publication receipt lost');+ expect(tapWindowBroadcast).not.toHaveBeenCalled();+ expect(h.mediaRefCalls).toEqual([]);+ expect(onMessageCreated).not.toHaveBeenCalled();+ expect(recordPrRefsForMessage).not.toHaveBeenCalled();+ }+ expect(h.sqlite!.prepare('SELECT count(*) FROM messages').pluck().get()).toBe(outcome === 'not-committed' ? 0 : 1);+ expect(h.sqlite!.prepare('SELECT count(*) FROM temp.cindy_pending_message_publications').pluck().get()).toBe(0);+ });+describe('createMessage happy path', () => {it('issues no SELECT after the INSERT and returns the inserted row', async () => {const msg = await createMessage('s1', {diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex f6e51c3027..80a8c10aa0 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -276,19 +276,21 @@ type CanonicalLinkReconciliation = {};let createBotCanonicalSessionImpl:- ((input: CreateBotCanonicalSessionInput) => Promise<CreateBotCanonicalSessionResult>) | null =+ ((input: CreateBotCanonicalSessionInput, beforeCommit?: () => Promise<void>) => Promise<CreateBotCanonicalSessionResult>) | null =null;/** Main-side canonical creator shared by first creation, restore and missing-task repair. */export async function createBotCanonicalSession(input: CreateBotCanonicalSessionInput,+ // Host-only guard, never accepted from the IPC payload or serialized to the worker.+ beforeCommit?: () => Promise<void>,): Promise<CreateBotCanonicalSessionResult> {if (!createBotCanonicalSessionImpl) {throwIpcError('PRECONDITION_FAILED', 'Bot 数据服务尚未初始化');}const owner = captureBotOperationOwner();owner.assertCurrent();- const result = await createBotCanonicalSessionImpl(input);+ const result = await createBotCanonicalSessionImpl(input, beforeCommit);owner.assertCurrent();return result;}@@ -593,12 +595,15 @@ function normalizeBotModelCapabilitiesOrThrow(/** How many candidate rows the preview query inspects (see below). */const CANONICAL_PREVIEW_SCAN = 100;-/** The transcript also accepts persisted usage/cost as a legacy turn seal. */+/** Explicit group deliveries are complete replies independent of the canonical turn.+ * The transcript also accepts persisted usage/cost as a legacy turn seal. */function canonicalReplyCompleted() {return sql`(json_extract(${messages.agentMeta}, '$.turnCompleted') = 1OR json_extract(${messages.agentMeta}, '$.turnMoney.amount') > 0OR json_extract(${messages.agentMeta}, '$.turnCostUsd') > 0- OR json_type(${messages.agentMeta}, '$.turnUsageDetails') IS NOT NULL)`;+ OR json_type(${messages.agentMeta}, '$.turnUsageDetails') IS NOT NULL+ OR (json_type(${messages.agentMeta}, '$.sourceGroup.groupId') = 'text'+ AND length(trim(json_extract(${messages.agentMeta}, '$.sourceGroup.groupId'))) > 0))`;}/** Visibility shared by the local unread count and remote reply watermark. */@@ -1835,6 +1840,7 @@ export function registerBotIpc(): void {const createBotCanonicalSessionUnlocked = async (input: CreateBotCanonicalSessionInput,+ beforeCommit?: () => Promise<void>,): Promise<CreateBotCanonicalSessionResult> => {const botId = readText(input.botId, 'botId', 128, true);const expectedCanonicalSessionId = input.expectedCanonicalSessionId;@@ -1929,6 +1935,9 @@ export function registerBotIpc(): void {let canonicalSessionId: string | null = null;let archivedCanonicalSessionId: string | null = null;let created = false;+ // Profile/model/workspace preparation can outlive the originating group+ // grant. Revalidate immediately before committing the Session/link CAS.+ await beforeCommit?.();owner.assertCurrent();const result = await client.tx<BotsReplaceCanonicalSessionResult>('bots.replaceCanonicalSession',@@ -2035,7 +2044,7 @@ export function registerBotIpc(): void {};};- const createBotCanonicalSessionPrepared = async (input: CreateBotCanonicalSessionInput) => {+ const createBotCanonicalSessionPrepared = async (input: CreateBotCanonicalSessionInput, beforeCommit?: () => Promise<void>) => {const owner = captureBotOperationOwner();// Bring legacy pointer-only profiles into the link registry before any// create/replace CAS. Once a canonical link exists, the worker transaction@@ -2043,13 +2052,13 @@ export function registerBotIpc(): void {await reconcileCanonicalLink(input.botId);owner.assertCurrent();const previousSessionId = input.expectedCanonicalSessionId;- if (!previousSessionId) return createBotCanonicalSessionUnlocked(input);+ if (!previousSessionId) return createBotCanonicalSessionUnlocked(input, beforeCommit);return coordinateBotCanonicalReplacement(previousSessionId, () =>- createBotCanonicalSessionUnlocked(input),+ createBotCanonicalSessionUnlocked(input, beforeCommit),);};- createBotCanonicalSessionImpl = async (input) => {+ createBotCanonicalSessionImpl = async (input, beforeCommit) => {const owner = captureBotOperationOwner();/*解析主任务前先把家里的文件收进来。用户拿编辑器改完 SOUL.md、@@ -2061,14 +2070,14 @@ export function registerBotIpc(): void {*/const derived = await reconcileBotProfileFolder(input.botId);owner.assertCurrent();- if (!derived) return createBotCanonicalSessionPrepared(input);+ if (!derived) return createBotCanonicalSessionPrepared(input, beforeCommit);// The host itself just folded the user's file edit into a new version. A caller// that saw the version before it is not racing a concurrent change; any other// mismatch still loses the create CAS.broadcastBotProfileChanged({ botId: input.botId, change: 'updated' });return createBotCanonicalSessionPrepared(input.expectedProfileVersion === derived.from? { ...input, expectedProfileVersion: derived.to }- : input);+ : input, beforeCommit);};ipcMain.handle('local-db:bots:create-canonical-session', async (event, raw: unknown) => {diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex 9fdbeb5b02..f1a9951767 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -1578,6 +1578,9 @@ export async function createMessage(* final "is this still current?" check is actually meaningful.*/shouldBroadcast?: () => boolean;+ /** Host-only admission guard, checked before and after the publication transaction.+ * Must be repeatable. A failed final check rolls back this exact row before delivery hooks. */+ beforePublish?: () => Promise<void>;/*** Optional clear-boundary compare-and-set for optimistic user sends. The* insert is accepted only while the session still has this exact@@ -1618,6 +1621,7 @@ export async function createMessage(if (existing.length > 0) return messageToCamel(existing[0]);}+ if (guarded && opts?.beforePublish) throw new Error('Publication guard cannot be combined with optimistic input');const id = createId();const now = Date.now();const visibleCreatedAt =@@ -1625,20 +1629,48 @@ export async function createMessage(? Math.max(body.createdAt ?? now, expected + 1): (body.createdAt ?? now);const insertRow = messageCreateToRow(id, sessionId, body, visibleCreatedAt);+ const insertArgs = {+ id: insertRow.id,+ clientId: insertRow.clientId,+ sessionId,+ role: insertRow.role,+ content: insertRow.content,+ toolUseId: insertRow.toolUseId ?? null,+ agentMeta: insertRow.agentMeta ?? null,+ agentKind: insertRow.agentKind ?? null,+ createdAt: insertRow.createdAt,+ guarded,+ expectedClearBoundaryMs: guarded ? (expected ?? null) : undefined,+ };try {- const inserted = await dbClient.tx('message.insert', {- id: insertRow.id,- clientId: insertRow.clientId,- sessionId,- role: insertRow.role,- content: insertRow.content,- toolUseId: insertRow.toolUseId ?? null,- agentMeta: insertRow.agentMeta ?? null,- agentKind: insertRow.agentKind ?? null,- createdAt: insertRow.createdAt,- guarded,- expectedClearBoundaryMs: guarded ? (expected ?? null) : undefined,+ const inserted = await dbClient.tx('message.insert', { ...insertArgs,+ ...(opts?.beforePublish ? { publication: 'stage' as const } : {}),});+ if (opts?.beforePublish) {+ await opts.beforePublish();+ try {+ const published = await dbClient.tx('message.insert', { ...insertArgs, publication: 'publish' });+ if (published.changes !== 1) throw new Error('Message publication lost its pending row');+ } catch (error) {+ // The worker can commit before its receipt is lost. Recover only this+ // exact publication, then run the same delivery/indexing hooks below.+ const [committed] = await db.select().from(messages)+ .where(and(eq(messages.id, id), eq(messages.sessionId, sessionId), eq(messages.clientId, body.clientId)))+ .limit(1);+ if (!committed || committed.role !== insertArgs.role || committed.content !== insertArgs.content+ || committed.toolUseId !== insertArgs.toolUseId || committed.agentMeta !== insertArgs.agentMeta+ || committed.agentKind !== insertArgs.agentKind || committed.createdAt !== insertArgs.createdAt+ || committed.rewindAt !== null) throw error;+ }+ // Keep this outside the lost-receipt recovery: a failed authorization+ // check must never be mistaken for a successful committed publication.+ try {+ await opts.beforePublish();+ } catch (error) {+ await dbClient.tx('message.insert', { ...insertArgs, publication: 'rollback' });+ throw error;+ }+ }if (guarded && inserted.changes === 0) {const [existingAfterGuard] = await db.select()@@ -1670,6 +1702,10 @@ export async function createMessage(throw new Error('Message insert skipped without a clear-boundary change');}} catch (err) {+ if (opts?.beforePublish) {+ await dbClient.tx('message.insert', { ...insertArgs, publication: 'discard' });+ throw err;+ }const after = await db.select().from(messages)diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 947171ce40..fd168724b9 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -1545,7 +1545,28 @@ function messageInsert(db: Database.Database, args: unknown): { changes: number: expectNumber(payload.expectedClearBoundaryMs, 'expectedClearBoundaryMs');const transaction = db.transaction(() => {let changes = 0;- if (guarded) {+ // Connection-local stages never enter history, counts or persistent FTS.+ // SQLite discards them automatically when this worker exits.+ if (payload.publication) {+ db.exec('CREATE TEMP TABLE IF NOT EXISTS cindy_pending_message_publications (id TEXT PRIMARY KEY, client_id TEXT NOT NULL, session_id TEXT NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, tool_use_id TEXT, agent_meta TEXT, agent_kind TEXT, created_at INTEGER NOT NULL)');+ }+ if (payload.publication === 'publish') {+ changes = db.prepare(+ 'INSERT INTO messages (id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at) SELECT id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at FROM temp.cindy_pending_message_publications WHERE id = ? AND session_id = ? AND client_id = ?',+ ).run(id, sessionId, clientId).changes;+ if (changes > 0) db.prepare('DELETE FROM temp.cindy_pending_message_publications WHERE id = ? AND session_id = ?').run(id, sessionId);+ } else if (payload.publication === 'rollback') {+ // CAS the complete published row; never remove a replacement or edited row.+ changes = db.prepare(+ 'DELETE FROM messages WHERE id = ? AND session_id = ? AND client_id = ? AND role = ? AND content = ? AND tool_use_id IS ? AND agent_meta IS ? AND agent_kind IS ? AND created_at = ? AND rewind_at IS NULL',+ ).run(id, sessionId, clientId, role, content, toolUseId, agentMeta, agentKind, createdAt).changes;+ } else if (payload.publication === 'discard') {+ changes = db.prepare('DELETE FROM temp.cindy_pending_message_publications WHERE id = ? AND session_id = ? AND client_id = ?').run(id, sessionId, clientId).changes;+ } else if (payload.publication === 'stage') {+ changes = db.prepare(+ 'INSERT INTO temp.cindy_pending_message_publications (id, client_id, session_id, role, content, tool_use_id, agent_meta, agent_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',+ ).run(id, clientId, sessionId, role, content, toolUseId, agentMeta, agentKind, createdAt).changes;+ } else if (guarded) {changes = db.prepare(`INSERT INTO messages (@@ -1582,7 +1603,7 @@ function messageInsert(db: Database.Database, args: unknown): { changes: number.run(id, clientId, sessionId, role, content, toolUseId, agentMeta, agentKind, createdAt).changes;}- if (changes > 0) {+ if (changes > 0 && (!payload.publication || payload.publication === 'publish' || payload.publication === 'rollback')) {if (role === 'user' || role === 'assistant') {db.prepare('UPDATE sessions SET list_preview = NULL, list_preview_role = NULL, list_message_count = NULL WHERE id = ?',diff --git a/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts b/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.tsindex 1e40c98546..bcf074b4ee 100644--- a/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts+++ b/apps/desktop/src/main/maker-host/bot-model-chain-settings-store.ts@@ -134,23 +134,27 @@ export async function resetBotModelChainSettings(return readBotModelChainSettingsState(options);}-/**- * A null override means the permanent Bot Profile follows the owner-scoped- * global route chain. Explicit per-Bot chains remain frozen in its profile.- */-export async function readEffectiveBotModelSelection(- config: Record<string, unknown>,- options?: Parameters<typeof readBotModelChainSettingsState>[0],-): Promise<{ chain: BotModelRoute[]; followsCindyDefault: boolean }> {+/** Read only Profile-owned routes; null means resolving this profile needs owner settings. */+export function readExplicitBotModelChain(config: Record<string, unknown>): BotModelRoute[] | null {if (Array.isArray(config.modelChainOverride)) {const explicit = normalizeBotModelChain(config.modelChainOverride);- if (explicit.length > 0) return { chain: explicit, followsCindyDefault: false };+ if (explicit.length > 0) return explicit;}// Preserve old explicit routes; null is the durable follow-default marker.if (config.modelChainOverride !== null && config.modelOverride !== null) {const legacy = normalizeBotModelChain(config.modelChain, config);- if (legacy.length || typeof config.model === 'string') return { chain: legacy, followsCindyDefault: false };+ if (legacy.length || typeof config.model === 'string') return legacy;}+ return null;+}++/** A null override follows owner settings; explicit per-Bot routes stay in its Profile. */+export async function readEffectiveBotModelSelection(+ config: Record<string, unknown>,+ options?: Parameters<typeof readBotModelChainSettingsState>[0],+): Promise<{ chain: BotModelRoute[]; followsCindyDefault: boolean }> {+ const explicit = readExplicitBotModelChain(config);+ if (explicit !== null) return { chain: explicit, followsCindyDefault: false };const state = await readBotModelChainSettingsState(options);return { chain: state.value.modelChain, followsCindyDefault: !state.isCustomized };}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 22da21b745..70c817221a 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@@ -1,3 +1,8 @@+import { BOT_GROUP_CLIENT_ID } from '../../../shared/botGroupChat.js';+import { authorizeGroupTool, registerGroupToolAuthority } from '../botGroupToolAuthorization.js';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { ScriptTarget, transpileModule } from 'typescript';import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, appendAutoReviewUserIntent } from '@cindy/maker-core';import { AUTO_REVIEW_DELEGATED_CONTINUATION, restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from '../autoReviewUserIntent.js';import { createPluginTaskReviewResolver, type PluginReviewSnapshot } from '../pluginTaskReviewContext.js';@@ -32,7 +37,7 @@ import type {AgentInputProjection,AgentInputQueuedMessage,} from '../../../shared/agentInputQueue.js';-import { USAGE_LIMIT_RESET_AUTO_RESUME_REASON } from '../../../shared/agentInputQueue.js';+import { HOST_ONLY_AGENT_PREFIX, USAGE_LIMIT_RESET_AUTO_RESUME_REASON } from '../../../shared/agentInputQueue.js';import {CONTINUE_AFTER_APP_EXIT_PROMPT,CONTINUE_AFTER_ERROR_PROMPT,@@ -6176,6 +6181,37 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {});describe('AgentInputCoordinator steer transaction', () => {+ it.each(['restore', 'screening', 'references', 'valid'] as const)('runs the host steer authority guard after %s', async boundary => {+ const h = createHarness();+ const sid = 'group-steer-guard';+ h.setRunning(true);+ let revoked = false;+ const failure = new Error('Fixture authority revoked');+ const beforeMutation = vi.fn(async () => { if (revoked) throw failure; });+ h.setScreenUserMessage(async () => { if (boundary === 'screening') revoked = true; return { action: 'allow' }; });+ h.resolveSessionReferences.mockImplementationOnce(async () => { if (boundary === 'references') revoked = true; return []; });+ const source = readFileSync(resolve(__dirname, '../register.ts'), 'utf8');+ const start = source.indexOf(' steerQueuedMessage: async (sessionId, item, expectedTurn) =>');+ const end = source.indexOf(' getQueueSnapshot:', start);+ expect(start).toBeGreaterThan(0); expect(end).toBeGreaterThan(start);+ const adapter = transpileModule(`return ({${source.slice(start, end)}}).steerQueuedMessage;`, { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText;+ const host = new Function('inputCoordinator', adapter)({+ ensureQueueRestored: async () => { if (boundary === 'restore') revoked = true; },+ steer: h.coordinator.steer.bind(h.coordinator),+ });+ const result = host(sid, makeItem('guarded-input', 'Private task input', { sessionRefs: [{ sessionId: 'reference' }] }),+ { session: h.getTurnSessionIdentity(), turnGeneration: 0, beforeMutation });+ if (boundary === 'valid') { await expect(result).resolves.toBe(true); expect(h.steerToAgent).toHaveBeenCalledOnce(); }+ else {+ await expect(result).rejects.toBe(failure);+ expect(h.steerToAgent).not.toHaveBeenCalled();+ expect(h.onSteerAccepted).not.toHaveBeenCalled();+ expect(h.coordinator.getQueueControlSnapshot(sid).pendingQueue).toEqual([]);+ expect(h.coordinator.getQueueControlSnapshot(sid).steeringQueueClientIds).toEqual([]);+ }+ expect(beforeMutation).toHaveBeenCalledTimes(boundary === 'restore' ? 1 : 2);+ });+it('rejects a control steer when screening crosses into a new turn generation', async () => {const h = createHarness();const sid = 'control-steer-screening-turn-race';@@ -9976,6 +10012,40 @@ describe('AgentInputCoordinator queue mutations', () => {});describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', () => {+ it.each(['member', 'plan'] as const)('drops restored %s group inputs before a new execution can use their lane', async kind => {+ const sid = 'reused-group-lane';+ const oldId = kind === 'member' ? BOT_GROUP_CLIENT_ID.memberTurn('room', 'old-execution', 'bot')+ : BOT_GROUP_CLIENT_ID.planStep('room', 'plan', 0, 'old-execution');+ const writer = createHarness();+ await writer.coordinator.ensureQueueRestored(sid);+ writer.setRunning(true);+ writer.coordinator.enqueue(sid, makeItem(oldId, 'Expired group request'));+ await flush();+ const snapshot = JSON.parse(JSON.stringify(writer.persistQueueSnapshot.mock.calls.at(-1)![1]));+ const reader = createHarness();+ reader.setLoadQueueSnapshot(async () => snapshot);+ const validate = vi.fn(async () => {});+ // Same lane, same group grant, but a different execution owns tool authority.+ const release = registerGroupToolAuthority(sid, { botId: 'bot', mode: 'owner', isCurrent: () => true, validate });+ try {+ await expect(authorizeGroupTool(sid, 'bot', 'owner-action')).resolves.toBeTruthy();+ await reader.coordinator.ensureQueueRestored(sid);+ await flush();+ expect(reader.coordinator.getQueueControlSnapshot(sid).pendingQueue).toEqual([]);+ expect(reader.onDiscardedQueuedMessage).toHaveBeenCalledWith(sid, expect.objectContaining({ clientId: oldId }));+ expect(latestSnapshotClientIds(reader.persistQueueSnapshot)).toEqual([]);+ reader.coordinator.resume(sid);+ await flush();+ expect(reader.sendToAgent).not.toHaveBeenCalled();+ const freshId = BOT_GROUP_CLIENT_ID.memberTurn('room', 'new-execution', 'bot');+ reader.coordinator.enqueue(sid, makeItem(freshId, 'Fresh group request'));+ await flush();+ expect(reader.sendToAgent).toHaveBeenCalledOnce();+ expect(reader.sendToAgent.mock.calls[0][3].persistUserMessage?.clientId).toBe(freshId);+ expect(reader.onAcceptedQueuedMessage).toHaveBeenCalledWith(sid, expect.objectContaining({ clientId: freshId }));+ } finally { release(); }+ });+it('restores the Main-owned authorization for an exact queued Desktop Pi command', async () => {const writer = createHarness();const sid = 'snapshot-desktop-pi-command';@@ -11576,6 +11646,40 @@ describe('AgentInputCoordinator replaceQueuedMessage(Orca lead 排队消息修},);+ it.each([false, true])('keeps a peer source in memory and uses the current body at dispatch (rewrite=%s)', async (rewrite) => {+ const h = createHarness();+ const sid = 'group-envelope-fixture';+ await h.coordinator.ensureQueueRestored(sid);+ h.setRunning(true);+ const body = '[UI_ACTION_TRIGGER]Bounded peer question';+ const prefix = '[Group source: Fixture Design (fixture-group); lane: fixture-lane]\n';+ const screen = vi.fn<NonNullable<AgentInputCoordinatorDeps['screenUserMessage']>>(async () => rewrite+ ? { action: 'rewrite' as const, ghostId: 'fixture-hook', ghostName: 'Fixture hook', text: 'Rewritten question' }+ : { action: 'allow' as const });+ h.setScreenUserMessage(screen);+ h.coordinator.enqueue(sid, { ...makeItem('bot-dm:fixture:message', body),+ [HOST_ONLY_AGENT_PREFIX]: prefix, agentOmitsTriggerPrefix: true,+ origin: { kind: 'session', senderSessionId: 'fixture-lane', displayText: body } });+ await flush();+ const snapshot = h.persistQueueSnapshot.mock.calls.at(-1)?.[1] ?? [];+ expect(snapshot).toHaveLength(1);+ expect(snapshot[0][HOST_ONLY_AGENT_PREFIX]).toBeUndefined();+ expect(snapshot[0].text).toBe(body);+ expect(JSON.stringify(snapshot)).not.toMatch(/Group source|Fixture Design|fixture-group/);+ const projection = h.coordinator.getProjection(sid).pendingQueue[0];+ expect(projection[HOST_ONLY_AGENT_PREFIX]).toBeUndefined();+ expect(projection.text).toBe(body);+ h.setRunning(false);+ h.coordinator.onTurnEvent(sid, 'done');+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledOnce();+ expect(screen).toHaveBeenCalledOnce();+ expect(screen.mock.calls[0]?.[1]).not.toContain('Group source');+ expect(h.sendToAgent.mock.calls[0]?.[1]).toEqual({ type: 'user', content: prefix + (rewrite ? 'Rewritten question' : 'Bounded peer question') });+ const message = mocks.createMessage.mock.calls.find(call => (call[1] as { clientId?: string }).clientId === 'bot-dm:fixture:message')?.[1];+ expect(message).toMatchObject({ content: rewrite ? '[UI_ACTION_TRIGGER]Rewritten question' : body });+ });+it('preserves typed plugin receipts from queue snapshot through durable persistence and review', async () => {const h = createHarness();const sid = 'plugin-empty-authorship';diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.tsindex 6750182556..aa591b3705 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts@@ -928,3 +928,11 @@ describe('buildHandoffText 超限收缩保住首尾', () => {expect(text.trimEnd().endsWith("== End of handoff note; the user's new message follows ==")).toBe(true);});});++it('keeps the group source of a private assistant reply when rebuilding model context', () => {+ const handoff = buildHandoffText([{ role: 'assistant', content: 'Private delivery', createdAt: 1,+ agentMeta: { sourceGroup: { groupId: 'group-1', name: 'Design' }, origin: {+ kind: 'session', senderSessionId: 'lane-1', senderBotId: 'bot-1', senderBotName: 'Helper',+ } } }], { fromLabel: 'Claude Code', toLabel: 'Codex' });+ expect(handoff).toContain('[Assistant · 由伙伴「Helper」(bot_id: bot-1) 从群聊「Design」(group_id: group-1)');+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botDirectMessageService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botDirectMessageService.test.tsindex 5d5581f58f..d4394a2514 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botDirectMessageService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botDirectMessageService.test.ts@@ -1,4 +1,7 @@import { AsyncLocalStorage } from 'node:async_hooks';+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, describe, expect, it, vi } from 'vitest';@@ -18,7 +21,14 @@ vi.mock('../../localDb/ipc/messages.js', () => ({}));import { createBotDirectMessageService } from '../botDirectMessageService.js';+import { botDirectMessages, botDirectMessageThreads } from '../../localDb/schema.js';import { createBotMessageTransport } from '../botMessageTransport.js';+import { GroupToolAuthorizationError, registerGroupToolAuthority } from '../botGroupToolAuthorization.js';+import { sessionQueueOriginForDispatcher } from '../sessionControlService.js';+import { redactMessageRowForSharedGuest, redactInputProjectionForSharedGuest } from '../../device-link/sharedTaskMessageOrigin.js';+import { HOST_ONLY_AGENT_PREFIX, buildMakerUserMessage, getAgentFacingText, sanitizeQueuedMessageForPersistence } from '../../../shared/agentInputQueue.js';+import { UI_ACTION_TRIGGER_PREFIX } from '../../../shared/interruptedTurn.js';+import { AcceptedCallbackDispatchCancelled, runAcceptedCallback, runAcceptedRollback } from '../acceptedCallbackRunner.js';function createDatabase(): Database.Database {const sqlite = new Database(':memory:');@@ -76,6 +86,7 @@ function createDatabase(): Database.Database {id TEXT PRIMARY KEY,session_id TEXT NOT NULL,client_id TEXT,+ content TEXT,rewind_at INTEGER);INSERT INTO bot_profiles (id, display_name, status, updated_at) VALUES@@ -106,6 +117,320 @@ describe('botDirectMessageService', () => {let sqlite: Database.Database;let dispatch: ReturnType<typeof vi.fn>;+ it('sends a group owner a real assistant message in their private chat, with stable retry receipts', async () => {+ sqlite.exec("INSERT INTO sessions VALUES ('a-group','bot','active'); INSERT INTO bot_session_links VALUES ('a-group-link','bot-a','a-group','group',NULL)");+ const release = registerGroupToolAuthority('a-group', { botId: 'bot-a', sourceGroup: { groupId: 'group-1', name: 'Design' }, mode: 'owner', isCurrent: () => true, validate: async () => {} });+ h.createMessage.mockImplementationOnce(async (sessionId, body) => {+ sqlite.prepare('INSERT INTO messages (id,session_id,client_id,content) VALUES (?,?,?,?)').run('private-message', sessionId, body.clientId, body.content);+ return { id: 'private-message' };+ });+ const service = createBotDirectMessageService({ dispatch });+ try {+ const input = { callerSessionId: 'a-group', message: 'Private reply for the owner', idempotencyKey: 'reply-request-1' };+ expect(await service.sendToUser(input)).toMatchObject({ ok: true, targetSessionId: 'a-main', messageId: 'private-message', delivered: true });+ expect(h.createMessage).toHaveBeenCalledWith('a-main', expect.objectContaining({ role: 'assistant', content: input.message,+ agentMeta: { sourceGroup: { groupId: 'group-1', name: 'Design' }, origin: { kind: 'session', senderSessionId: 'a-group', senderBotId: 'bot-a', senderBotName: '总控' } } }), expect.anything());+ expect(await service.sendToUser(input)).toMatchObject({ ok: true, messageId: 'private-message' });+ expect(await service.sendToUser({ ...input, message: 'Different message' })).toMatchObject({ ok: false, errorCode: 'IDEMPOTENCY_CONFLICT' });+ expect(h.createMessage).toHaveBeenCalledOnce();+ expect(dispatch).not.toHaveBeenCalled();+ expect(await service.messageAgent({ callerSessionId: 'a-group', targetBotId: 'bot-a', message: 'Never wake myself' })).toMatchObject({ ok: false, errorCode: 'SELF_MESSAGE' });+ } finally { release(); }+ });++ it.each(['deleted', 'archived'])('keeps the original private receipt after canonical recovery from %s', async status => {+ sqlite.exec("INSERT INTO sessions VALUES ('a-group','bot','active'); INSERT INTO bot_session_links VALUES ('a-group-link','bot-a','a-group','group',NULL)");+ const release = registerGroupToolAuthority('a-group', { botId: 'bot-a', sourceGroup: { groupId: 'group-1' },+ mode: 'owner', isCurrent: () => true, validate: async () => {} });+ const input = { callerSessionId: 'a-group', message: 'Private reply', idempotencyKey: 'stable-recovery-key' };+ const clientId = `bot-group-private:a-group:${input.idempotencyKey}`;+ // A matching key in another teammate's private history cannot claim this receipt.+ sqlite.prepare('INSERT INTO messages(id,session_id,client_id,content) VALUES(?,?,?,?)')+ .run('other-receipt', 'b-main', clientId, 'Different private content');+ h.createMessage.mockImplementationOnce(async (sessionId, body) => {+ sqlite.prepare('INSERT INTO messages(id,session_id,client_id,content) VALUES(?,?,?,?)')+ .run('original-receipt', sessionId, body.clientId, body.content);+ return { id: 'original-receipt' };+ });+ let recover = false;+ const ensureCanonicalSession = vi.fn(async (_botId: string, beforeRecovery?: () => Promise<void>) => {+ if (recover) {+ await beforeRecovery?.();+ sqlite.exec("UPDATE bot_session_links SET role='history', archived_at=1 WHERE session_id='a-main'; INSERT INTO sessions VALUES('a-restored','bot','active'); INSERT INTO bot_session_links VALUES('a-restored-link','bot-a','a-restored','canonical',NULL)");+ recover = false;+ }+ const target = sqlite.prepare("SELECT session_id AS sessionId FROM bot_session_links WHERE bot_id='bot-a' AND role='canonical'").get() as { sessionId: string };+ return { ok: true as const, sessionId: target.sessionId };+ });+ const service = createBotDirectMessageService({ dispatch, ensureCanonicalSession });+ try {+ const receipt = { ok: true, messageId: 'original-receipt', targetSessionId: 'a-main', delivered: true };+ expect(await service.sendToUser(input)).toEqual(receipt);+ sqlite.prepare('UPDATE sessions SET status=? WHERE id=?').run(status, 'a-main');+ recover = true;+ expect(await service.sendToUser(input)).toEqual(receipt);+ expect(await service.sendToUser({ ...input, message: 'Changed body' }))+ .toMatchObject({ ok: false, errorCode: 'IDEMPOTENCY_CONFLICT' });+ expect(h.createMessage).toHaveBeenCalledOnce();+ expect(sqlite.prepare("SELECT count(*) AS n FROM messages WHERE session_id='a-restored'").get()).toEqual({ n: 0 });+ expect(dispatch).not.toHaveBeenCalled();+ } finally { release(); }+ });++ it.each(['unregistered', 'tools', 'chat', 'revoked', 'other-bot', 'account'])(+ 'refuses a group private send with %s authority without changing messages', async condition => {+ sqlite.exec("INSERT INTO sessions VALUES ('a-group','bot','active'); INSERT INTO bot_session_links VALUES ('a-group-link','bot-a','a-group','group',NULL)");+ const release = condition === 'unregistered' ? () => {} : registerGroupToolAuthority('a-group', {+ botId: condition === 'other-bot' ? 'bot-b' : 'bot-a', mode: condition === 'tools' || condition === 'chat' ? condition : 'owner',+ isCurrent: () => condition !== 'revoked', validate: async () => {},+ });+ const service = createBotDirectMessageService({ dispatch,+ captureOwnerScope: () => ({ ownerScopeKey: 'owner-a' }), isOwnerScopeCurrent: () => condition !== 'account' });+ try {+ expect(await service.sendToUser({ callerSessionId: 'a-group', message: 'Do not send', idempotencyKey: 'request-123' })).toMatchObject({ ok: false });+ expect(h.createMessage).not.toHaveBeenCalled(); expect(dispatch).not.toHaveBeenCalled();+ } finally { release(); }+ });++ it('allows owner-authorized local peer messaging while retaining its group source', async () => {+ sqlite.exec("INSERT INTO sessions VALUES ('a-group','bot','active'); INSERT INTO bot_session_links VALUES ('a-group-link','bot-a','a-group','group',NULL)");+ const release = registerGroupToolAuthority('a-group', { botId: 'bot-a', sourceGroup: { groupId: 'group-1', name: 'Design' }, mode: 'owner', isCurrent: () => true, validate: async () => {} });+ const service = createBotDirectMessageService({ dispatch });+ try {+ expect(await service.listAgents('a-group')).toMatchObject({ ok: true, agents: expect.arrayContaining([{ id: 'bot-b', name: 'Dash Bot', local: true }]) });+ expect(await service.messageAgent({ callerSessionId: 'a-group', targetBotId: 'bot-b', message: 'Bounded peer question' })).toMatchObject({ ok: true, targetSessionId: 'b-main' });+ expect(sqlite.prepare('SELECT sender_session_id FROM bot_direct_messages').get()).toEqual({ sender_session_id: 'a-group' });+ expect(dispatch).toHaveBeenLastCalledWith(expect.objectContaining({+ dispatcherSessionId: 'a-group',+ message: expect.stringContaining('[Group source: Design (group-1); lane: a-group]'),+ persistedContent: `${UI_ACTION_TRIGGER_PREFIX}Bounded peer question`,+ }));+ const sent = dispatch.mock.calls.at(-1)![0];+ expect(sent.message).toContain('Replies go to the sender teammate');+ const origin = sessionQueueOriginForDispatcher(sent);+ const row = { sessionId: sent.targetSessionId, content: sent.persistedContent,+ agentMeta: { origin, agentFacingWireContent: { type: 'user', content: sent.message } } };+ const source = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8');+ const begin = source.indexOf(' async function buildSessionControlInputItem(');+ const end = source.indexOf(' const orcaInterAgentDispatcher:', begin);+ const js = ts.transpileModule(`${source.slice(begin, end)}\nreturn buildSessionControlInputItem;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ const build = new Function('buildCreateOptsForQueuedSession', 'permissionModeOrAsk', 'UI_ACTION_TRIGGER_PREFIX', 'HOST_ONLY_AGENT_PREFIX', js)(+ async () => ({ model: 'fixture', workingDir: '/fixture', permissionMode: 'ask' }), (mode: string) => mode,+ UI_ACTION_TRIGGER_PREFIX, HOST_ONLY_AGENT_PREFIX);+ const queued = await build({ ...sent, meta: {}, origin });+ expect(queued.text).toBe(sent.persistedContent);+ expect(getAgentFacingText(queued)).not.toContain('Group source');+ expect(buildMakerUserMessage(queued)).toEqual({ type: 'user', content: sent.message });+ const snapshot = sanitizeQueuedMessageForPersistence(queued);+ expect(snapshot[HOST_ONLY_AGENT_PREFIX]).toBeUndefined();+ expect(snapshot.text).toBe(sent.persistedContent);+ expect(JSON.stringify(snapshot)).not.toMatch(/Design|group-1|Group source/);+ expect(JSON.stringify(buildMakerUserMessage(JSON.parse(JSON.stringify(snapshot))))).not.toContain('Group source');+ const projection = { pendingQueue: [queued], recovery: { kind: 'active-turn', item: queued } };+ // These are the actual history/message-push and queue/read-recovery+ // redactors. The host's model input retains the full group source.+ const guestRow = redactMessageRowForSharedGuest(row);+ const guestProjection = redactInputProjectionForSharedGuest(projection);+ expect(guestRow.content).toBe(`${UI_ACTION_TRIGGER_PREFIX}Bounded peer question`);+ expect(JSON.stringify([guestRow, guestProjection])).not.toMatch(/Design|group-1|a-group|Group source/);+ expect(JSON.stringify(guestProjection)).toContain('Bounded peer question');+ expect(row.agentMeta.agentFacingWireContent.content).toContain('[Group source: Design (group-1); lane: a-group]');+ expect(queued[HOST_ONLY_AGENT_PREFIX]).toBe(sent.message.slice(0, -'Bounded peer question'.length));+ release();+ dispatch.mockImplementationOnce(async params => {+ await params.onAccepted?.();+ return { ok: true, targetSessionId: params.targetSessionId, wakeKind: 'resumed' };+ });+ expect(await service.messageAgent({ callerSessionId: 'b-main', targetBotId: 'bot-a', message: 'Reply about Design (group-1)' }))+ .toMatchObject({ ok: true, targetSessionId: 'a-main' });+ expect(dispatch).toHaveBeenLastCalledWith(expect.objectContaining({ targetSessionId: 'a-main' }));+ expect(dispatch.mock.calls.at(-1)?.[0]).not.toHaveProperty('dispatcherSessionId');+ } finally { release(); }+ });++ it.each(['valid', 'server-revoked', 'execution-ended'] as const)('uses the host cancellation adapter when a queued group DM drains: %s', async condition => {+ sqlite.exec("INSERT INTO sessions VALUES ('a-group','bot','active'); INSERT INTO bot_session_links VALUES ('a-group-link','bot-a','a-group','group',NULL)");+ let draining = false;+ const release = registerGroupToolAuthority('a-group', { botId: 'bot-a', mode: 'owner',+ isCurrent: () => !draining || condition !== 'execution-ended',+ validate: async () => { if (draining && condition === 'server-revoked') throw new GroupToolAuthorizationError(); } });+ // Compile the actual production adapter, including its error conversion;+ // invoking the service callback directly would bypass the boundary under review.+ const source = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8');+ const holder = source.indexOf('botDirectMessageServiceHolder = createBotDirectMessageService({');+ const start = source.indexOf(' dispatch: ({', holder);+ const end = source.indexOf(' ensureCanonicalSession:', start);+ expect(holder).toBeGreaterThan(0); expect(start).toBeGreaterThan(holder); expect(end).toBeGreaterThan(start);+ const adapter = ts.transpileModule(`return ({${source.slice(start, end)}}).dispatch;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },+ }).outputText;+ const enqueue = vi.fn(async (params: {+ targetSessionId: string; clientId: string; onAccepted: () => Promise<void>; onAcceptedRollback: () => Promise<void>;+ }) => ({ ok: true as const, targetSessionId: params.targetSessionId, wakeKind: 'queued' as const }));+ const hostDispatch = new Function('dispatchBotSessionMessage', 'AcceptedCallbackDispatchCancelled', adapter)(enqueue, AcceptedCallbackDispatchCancelled);+ const service = createBotDirectMessageService({ dispatch: hostDispatch });+ const vendorDispatch = vi.fn(async () => {});+ const log = { warn: vi.fn() };+ try {+ expect(await service.messageAgent({ callerSessionId: 'a-group', targetBotId: 'bot-b', message: 'Queued fixture' }))+ .toMatchObject({ ok: true, delivered: false });+ expect(sqlite.prepare('SELECT delivery_status FROM bot_direct_messages').pluck().get()).toBe('pending');+ expect(h.createMessage).not.toHaveBeenCalled();+ draining = true;+ const queued = enqueue.mock.calls[0][0];+ const drain = async () => {+ try {+ await runAcceptedCallback(queued.onAccepted, queued.targetSessionId, queued.clientId, log);+ await vendorDispatch();+ } catch (error) {+ await runAcceptedRollback(queued.onAcceptedRollback, queued.targetSessionId, queued.clientId, log);+ throw error;+ }+ };+ if (condition === 'valid') {+ await drain();+ expect(vendorDispatch).toHaveBeenCalledOnce();+ expect(sqlite.prepare('SELECT delivery_status FROM bot_direct_messages').pluck().get()).toBe('delivered');+ } else {+ await expect(drain()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);+ expect(vendorDispatch).not.toHaveBeenCalled();+ expect(h.createMessage).not.toHaveBeenCalled();+ expect(sqlite.prepare('SELECT delivery_status FROM bot_direct_messages').pluck().get()).toBe('failed');+ expect(sqlite.prepare('SELECT message_count FROM bot_direct_message_threads').pluck().get()).toBe(0);+ }+ } finally { release(); }+ });++ it.each(['group', 'group-receipt', 'missing-link', 'deleted-source', 'canonical'] as const)('checks durable sender provenance before restored DM dispatch: %s', async identity => {+ sqlite.exec("INSERT INTO sessions VALUES ('a-group','bot','active'); INSERT INTO bot_session_links VALUES ('a-group-link','bot-a','a-group','group',NULL)");+ const release = registerGroupToolAuthority('a-group', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ const enqueue = vi.fn(async (_params: Parameters<Parameters<typeof createBotDirectMessageService>[0]['dispatch']>[0]) =>+ ({ ok: true as const, targetSessionId: 'b-main', wakeKind: 'queued' as const }));+ const before = createBotDirectMessageService({ dispatch: enqueue });+ try {+ await before.messageAgent({ callerSessionId: identity === 'canonical' ? 'a-main' : 'a-group', targetBotId: 'bot-b', message: 'Persisted queue fixture' });+ release();+ if (identity === 'missing-link') sqlite.exec("DELETE FROM bot_session_links WHERE session_id='a-group'");+ if (identity === 'deleted-source') sqlite.exec("UPDATE bot_direct_messages SET sender_session_id=NULL; DELETE FROM bot_session_links WHERE session_id='a-group'");+ // Only the durable queue item survives, not its accepted/rollback closures.+ const item = JSON.parse(JSON.stringify({ clientId: enqueue.mock.calls[0][0].clientId }));+ if (identity === 'group-receipt') sqlite.prepare('INSERT INTO messages (id, session_id, client_id) VALUES (?, ?, ?)')+ .run('unaccepted-group-receipt', 'b-main', item.clientId);+ const discard = vi.fn(async () => {});+ const after = createBotDirectMessageService({ dispatch, hasQueuedDelivery: async () => true, discardQueuedDelivery: discard });+ const source = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8');+ const start = source.indexOf(' onAcceptedQueuedMessage: async (');+ const end = source.indexOf(' onUserMessagePersisting:', start);+ const hookSource = ts.transpileModule(`return ({${source.slice(start, end)}}).onAcceptedQueuedMessage;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },+ }).outputText;+ const acceptedHook = new Function('botDirectMessageServiceHolder', 'AcceptedCallbackDispatchCancelled',+ 'schedulerQueuedPromptDiscardWatchers', 'schedulerQueuedPromptPreparations', 'orcaInterAgentDispatcher',+ 'botDelegationServiceHolder', 'maker', 'pluginTaskServiceForCurrentOwner', hookSource)(after,+ AcceptedCallbackDispatchCancelled, new Map(), new Map(), { runQueuedOrcaInterAgentAcceptedCallback: async () => {} },+ null, { getSession: () => null }, null);+ const vendor = vi.fn(async () => {});+ const drain = async () => { await acceptedHook('b-main', item, true); await vendor(); };+ if (identity === 'canonical') {+ await after.restore(); await drain();+ expect(vendor).toHaveBeenCalledOnce(); expect(discard).not.toHaveBeenCalled();+ expect(sqlite.prepare('SELECT delivery_status FROM bot_direct_messages').pluck().get()).toBe('delivered');+ } else {+ // Fence works even if queue drain wins the startup race with DM restore.+ await expect(drain()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);+ await after.restore(); await after.restore();+ await expect(drain()).rejects.toBeInstanceOf(AcceptedCallbackDispatchCancelled);+ expect(vendor).not.toHaveBeenCalled(); expect(h.createMessage).not.toHaveBeenCalled();+ expect(discard).toHaveBeenCalledWith('b-main', item.clientId, expect.any(Function));+ expect(sqlite.prepare('SELECT id FROM messages WHERE client_id=?').get(item.clientId)).toBeUndefined();+ expect(sqlite.prepare('SELECT delivery_status FROM bot_direct_messages').pluck().get()).toBe('failed');+ expect(sqlite.prepare('SELECT message_count FROM bot_direct_message_threads').pluck().get()).toBe(0);+ }+ } finally { release(); }+ });++ it.each(['expiry', 'new-thread', 'cooldown', 'reservations', 'recent'] as const)('rejects group peer thread changes/state after revocation during %s read', async boundary => {+ sqlite.exec("INSERT INTO sessions VALUES ('a-group','bot','active'); INSERT INTO bot_session_links VALUES ('a-group-link','bot-a','a-group','group',NULL)");+ let revoked = false;+ const release = registerGroupToolAuthority('a-group', { botId: 'bot-a', mode: 'owner', isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ let id = 0;+ const service = createBotDirectMessageService({ dispatch, now: () => 1000, createId: () => `read-${++id}` });+ if (boundary !== 'new-thread') {+ await service.messageAgent({ callerSessionId: 'a-main', targetBotId: 'bot-b', message: 'Earlier message' });+ if (boundary === 'recent') await service.messageAgent({ callerSessionId: 'a-main', targetBotId: 'bot-b', message: 'Second message' });+ if (boundary === 'expiry') sqlite.exec('UPDATE bot_direct_message_threads SET expires_at=1');+ if (boundary === 'cooldown') sqlite.exec("UPDATE bot_direct_message_threads SET status='closed', close_reason='message-limit', blocked_until=99999");+ if (boundary === 'reservations') sqlite.exec('UPDATE bot_direct_message_threads SET message_count=9');+ }+ const threads = sqlite.prepare('SELECT * FROM bot_direct_message_threads').all();+ const deliveries = sqlite.prepare('SELECT * FROM bot_direct_messages').all();+ dispatch.mockClear();+ let threadReads = 0;+ const select = h.db!.select.bind(h.db!);+ const spy = vi.spyOn(h.db!, 'select').mockImplementation(fields => {+ const query = select(fields); const from = query.from.bind(query);+ vi.spyOn(query, 'from').mockImplementation(table => {+ const result = from(table);+ if (table === botDirectMessageThreads) threadReads++;+ const hit = table === botDirectMessageThreads && threadReads === (boundary === 'expiry' ? 1 : 2)+ && ['expiry', 'new-thread', 'cooldown'].includes(boundary)+ || table === botDirectMessages && (boundary === 'reservations' ? !!fields?.deliveryStatus : boundary === 'recent' && !!fields?.senderBotId);+ if (hit) queueMicrotask(() => { revoked = true; });+ return result;+ }); return query;+ });+ try {+ expect(await service.messageAgent({ callerSessionId: 'a-group', targetBotId: 'bot-b', message: 'Must not reserve' }))+ .toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(revoked).toBe(true); expect(dispatch).not.toHaveBeenCalled();+ expect(sqlite.prepare('SELECT * FROM bot_direct_message_threads').all()).toEqual(threads);+ expect(sqlite.prepare('SELECT * FROM bot_direct_messages').all()).toEqual(deliveries);+ } finally { spy.mockRestore(); release(); }+ });++ it.each(['list', 'failed-send'] as const)('revalidates group authority after the private roster read for %s', async operation => {+ sqlite.exec("INSERT INTO sessions VALUES ('a-group','bot','active'); INSERT INTO bot_session_links VALUES ('a-group-link','bot-a','a-group','group',NULL)");+ let serverAuthorized = true;+ let revokeDuringRead = false;+ const validate = vi.fn(async () => { if (!serverAuthorized) throw new GroupToolAuthorizationError(); });+ const release = registerGroupToolAuthority('a-group', {+ botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate,+ });+ const rosterRead = vi.fn(() => { if (revokeDuringRead) serverAuthorized = false; });+ const prepare = sqlite.prepare.bind(sqlite);+ const spy = vi.spyOn(sqlite, 'prepare').mockImplementation(sql => {+ const statement = prepare(sql);+ if (sql.includes('from "bot_profiles"') && sql.includes('order by')) {+ const all = statement.all.bind(statement);+ vi.spyOn(statement, 'all').mockImplementation((...args: unknown[]) => {+ const result = all(...args);+ rosterRead();+ return result;+ });+ }+ return statement;+ });+ const service = createBotDirectMessageService({ dispatch });+ const read = () => operation === 'list' ? service.listAgents('a-group')+ : service.messageAgent({ callerSessionId: 'a-group', targetBotId: 'missing-bot', message: 'Fixture only' });+ try {+ expect(await read()).toMatchObject(operation === 'list'+ ? { ok: true, agents: expect.arrayContaining([{ id: 'bot-b', name: 'Dash Bot', local: true }]) }+ : { ok: false, errorCode: 'TARGET_BOT_NOT_FOUND', availableBots: expect.arrayContaining([{ id: 'bot-b', name: 'Dash Bot' }]) });+ expect(rosterRead).toHaveBeenCalledOnce();+ expect(validate).toHaveBeenCalledTimes(2);+ revokeDuringRead = true;+ rosterRead.mockClear(); validate.mockClear();+ expect(await read()).toEqual({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED', message: expect.any(String) });+ expect(rosterRead).toHaveBeenCalledOnce();+ expect(validate).toHaveBeenCalledTimes(2);+ expect(dispatch).not.toHaveBeenCalled();+ } finally { release(); spy.mockRestore(); }+ });+beforeEach(() => {sqlite = createDatabase();h.db = drizzle(sqlite);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupToolAuthorization.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupToolAuthorization.test.tsnew file mode 100644index 0000000000..b867f952f7--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupToolAuthorization.test.ts@@ -0,0 +1,68 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { authorizeGroupTool, registerGroupToolAuthority, GroupToolAuthorizationError } from '../botGroupToolAuthorization.js';+import { setMainLocale } from '../../i18n.js';++const releases: Array<() => void> = [];+afterEach(() => { releases.splice(0).forEach(release => release()); setMainLocale('en'); });++describe('live group tool authority', () => {+ it.each(['owner', 'tools'] as const)('allows self inspection with %s authority', async mode => {+ const validate = vi.fn(async () => {});+ releases.push(registerGroupToolAuthority('lane', { botId: 'bot', mode, validate, isCurrent: () => true }));+ await expect(authorizeGroupTool('lane', 'bot', 'read-self')).resolves.toBeDefined();+ expect(validate).toHaveBeenCalledOnce();+ if (mode === 'tools') await expect(authorizeGroupTool('lane', 'bot', 'owner-action')).rejects.toMatchObject({ code: 'GROUP_AUTHORIZATION_REQUIRED' });+ });+ it('refuses persisted lanes, chat-only grants and another bot identity', async () => {+ await expect(authorizeGroupTool('lane', 'bot', 'owner-action')).rejects.toThrow();+ releases.push(registerGroupToolAuthority('lane', { botId: 'bot', mode: 'chat', validate: async () => {}, isCurrent: () => true }));+ await expect(authorizeGroupTool('lane', 'bot', 'read-self')).rejects.toThrow();+ releases.push(registerGroupToolAuthority('lane', { botId: 'bot', mode: 'owner', validate: async () => {}, isCurrent: () => true }));+ await expect(authorizeGroupTool('lane', 'other-bot', 'owner-action')).rejects.toThrow();+ });+ it('rejects stale completion after a new runtime replaces the same lane', async () => {+ let complete!: () => void;+ const oldRelease = registerGroupToolAuthority('lane', { botId: 'bot', mode: 'owner', isCurrent: () => true,+ validate: () => new Promise<void>(resolve => { complete = resolve; }) });+ releases.push(oldRelease);+ const pending = authorizeGroupTool('lane', 'bot', 'owner-action');+ releases.push(registerGroupToolAuthority('lane', { botId: 'bot', mode: 'owner', isCurrent: () => true, validate: async () => {} }));+ oldRelease(); complete();+ await expect(pending).rejects.toThrow();+ await expect(authorizeGroupTool('lane', 'bot', 'owner-action')).resolves.toBeDefined();+ });+ it('rechecks revocation and refuses authority after the execution ends', async () => {+ let live = true;+ let revoked = false;+ releases.push(registerGroupToolAuthority('lane', { botId: 'bot', mode: 'owner', isCurrent: () => live,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } }));+ const authority = await authorizeGroupTool('lane', 'bot', 'owner-action');+ live = false; expect(authority.assertCurrent).toThrow();+ live = true; revoked = true;+ await expect(authority.refresh()).rejects.toThrow();+ revoked = false; // Failed validation cannot revive the old execution.+ await expect(authorizeGroupTool('lane', 'bot', 'owner-action')).rejects.toThrow();+ });+ it('cannot refresh an old operation using a replacement execution for the same lane', async () => {+ const grant = { botId: 'bot', mode: 'owner' as const, isCurrent: () => true, validate: async () => {} };+ releases.push(registerGroupToolAuthority('lane', grant));+ const old = await authorizeGroupTool('lane', 'bot', 'owner-action');+ releases.push(registerGroupToolAuthority('lane', { ...grant }));+ await expect(old.refresh()).rejects.toThrow();+ await expect(authorizeGroupTool('lane', 'bot', 'owner-action')).resolves.toBeDefined();+ });+ it('denies transient failures but retries validation on the same live execution', async () => {+ const validate = vi.fn().mockRejectedValueOnce(new Error('network timeout')).mockResolvedValue(undefined);+ releases.push(registerGroupToolAuthority('lane', { botId: 'bot', mode: 'owner', isCurrent: () => true, validate }));+ await expect(authorizeGroupTool('lane', 'bot', 'owner-action')).rejects.toMatchObject({ code: 'GROUP_AUTHORIZATION_UNAVAILABLE' });+ await expect(authorizeGroupTool('lane', 'bot', 'owner-action')).resolves.toBeDefined();+ expect(validate).toHaveBeenCalledTimes(2);+ });+ it.each(['en', 'zh-CN', 'zh-TW', 'ja', 'ko'] as const)('localizes a denied call in %s', async locale => {+ setMainLocale(locale);+ expect(new GroupToolAuthorizationError(true).message).not.toContain('groupTools.');+ await expect(authorizeGroupTool('unregistered', 'bot', 'owner-action')).rejects.toMatchObject({+ code: 'GROUP_AUTHORIZATION_REQUIRED', message: expect.not.stringContaining('groupTools.'),+ });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSessionTaskRouteBridge.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSessionTaskRouteBridge.test.tsnew file mode 100644index 0000000000..de43180071--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSessionTaskRouteBridge.test.ts@@ -0,0 +1,21 @@+import { expect, it, vi } from 'vitest';+import { createBotSessionTaskRouteBridge } from '../botSessionTaskRouteBridge.js';+import { GroupToolAuthorizationError } from '../botGroupToolAuthorization.js';++it('checks the captured group grant after reading the task runtime and before changing it', async () => {+ let current = true;+ const route = { agentKind: 'codex' as const, model: 'model', providerId: 'provider', effort: null, fastMode: false };+ const setSessionRuntime = vi.fn();+ const bridge = createBotSessionTaskRouteBridge({+ getSessionRuntime: vi.fn(async () => {+ current = false;+ return { ok: true, runtime: { runtimeGeneration: 1, effectiveProfile: route } } as never;+ }),+ setSessionRuntime,+ readConfiguredCandidate: vi.fn(),+ });+ await expect(bridge.advance('child', 1, route, async () => {+ if (!current) throw new GroupToolAuthorizationError();+ })).rejects.toMatchObject({ code: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(setSessionRuntime).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex c5aa0874d3..16d840c2da 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -41,6 +41,7 @@ vi.mock('ws', async () => {} };});import { withChatServer } from '../chatServer.js';+import { authorizeGroupTool } from '../botGroupToolAuthorization.js';import type { BotGroupChatService, BotGroupChatServiceDeps } from '../botGroupChatService.js';describe('Chat Server production connection', () => {@@ -122,6 +123,65 @@ describe('Chat Server result delivery and refresh', () => {const terminal = { sessionId: 'lane', activeInputClientId: null, outcome: 'done' as const, resultText: 'Finished reply' };const deliveries = () => fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'complete');+ it.each([undefined, '60000000-0000-4000-8000-000000000001'])('does not replace execution requester %s with the source author', async requesterId => {+ fixture.handle.mockImplementation((route, method, body) => {+ if (route === '/executions/claim') {+ const next = claimed ? null : { ...execution, requester_id: requesterId, access_mode: 'owner' };+ claimed = true; return { body: { execution: next } };+ }+ if (route.endsWith('/members')) return { body: [+ { id: botId, kind: 'bot', ownerActorId: selfId, state: 'joined', accessRevision: 1, guestAccess: 'tools' },+ { id: selfId, kind: 'human', ownerActorId: selfId, state: 'joined', role: 'owner' },+ ] };+ if (route.endsWith(`/messages/${execution.source_message_id}`) || route.includes('/messages?')) {+ const source = { id: execution.source_message_id, seq: '1', authorId: selfId, author: { kind: 'human', name: 'Me' },+ content: [{ type: 'text', text: 'Original owner request' }], deleted: false, threadRootId: null };+ return { body: route.includes('/messages?') ? [source] : source };+ }+ return response(route);+ });+ await start();+ await expect(authorizeGroupTool('lane', 'local-bot', 'owner-action')).rejects.toMatchObject({ code: 'GROUP_AUTHORIZATION_REQUIRED' });+ });++ it.each(['revision', 'requester', 'companion-owner', 'left', 'lease', 'account', 'restart', 'temporary-members', 'temporary-heartbeat'])(+ 'checks the server execution at the tool boundary and rejects %s changes', async change => {+ let changed = false;+ let accountCurrent = true;+ deps.captureOwnerScope = () => ({}) as ReturnType<NonNullable<typeof deps.captureOwnerScope>>;+ deps.isOwnerScopeCurrent = () => accountCurrent;+ service.dispose();+ service = withChatServer({ listGroups: async () => ({ ok: true, groups: [] }), dispose: vi.fn() } as unknown as BotGroupChatService, deps);+ fixture.handle.mockImplementation((route, method, body) => {+ if (route === '/executions/claim') {+ const next = claimed ? null : { ...execution, requester_id: selfId, access_mode: 'owner' };+ claimed = true; return { body: { execution: next } };+ }+ if (changed && (change === 'temporary-members' && route.endsWith('/members')+ || change === 'temporary-heartbeat' && body?.action === 'heartbeat'))+ return { status: 503, body: { error: { code: 'UNAVAILABLE' } } };+ if (route.endsWith('/members')) return { body: [+ { id: botId, kind: 'bot', ownerActorId: changed && change === 'companion-owner' ? 'other-owner' : selfId,+ state: changed && change === 'left' ? 'left' : 'joined', accessRevision: changed && change === 'revision' ? 2 : 1, guestAccess: 'tools' },+ { id: selfId, kind: 'human', state: 'joined', role: 'owner', ownerActorId: changed && change === 'requester' ? 'other-owner' : selfId },+ ] };+ if (changed && change === 'lease' && body?.action === 'heartbeat') return { status: 409, body: { error: { code: 'STALE_EXECUTION' } } };+ return response(route);+ });+ await start();+ await expect(authorizeGroupTool('lane', 'local-bot', 'owner-action')).resolves.toBeDefined();+ expect(fixture.handle.mock.calls.some(([, , body]) => body?.action === 'heartbeat')).toBe(true);+ changed = true;+ if (change === 'account') accountCurrent = false;+ if (change === 'restart') service.dispose();+ await expect(authorizeGroupTool('lane', 'local-bot', 'owner-action')).rejects.toMatchObject({+ code: change.startsWith('temporary-') ? 'GROUP_AUTHORIZATION_UNAVAILABLE' : 'GROUP_AUTHORIZATION_REQUIRED' });+ if (change.startsWith('temporary-')) {+ changed = false;+ await expect(authorizeGroupTool('lane', 'local-bot', 'owner-action')).resolves.toBeDefined();+ }+ });+it('keeps server plan steps in a grant-specific chat-only lane without opening a project', async () => {fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];const planId = '70000000-0000-4000-8000-000000000001';diff --git a/apps/desktop/src/main/maker-ipc/__tests__/groupRuntimeRouteAuthorization.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/groupRuntimeRouteAuthorization.test.tsnew file mode 100644index 0000000000..5c467dcd9c--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/groupRuntimeRouteAuthorization.test.ts@@ -0,0 +1,144 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { ScriptTarget, transpileModule } from 'typescript';+import { afterEach, expect, it, vi } from 'vitest';+import { createBotSessionTaskRouteBridge } from '../botSessionTaskRouteBridge.js';+import { createSessionControlService } from '../sessionControlService.js';+import { GroupToolAuthorizationError, authorizeGroupTool, registerGroupToolAuthority } from '../botGroupToolAuthorization.js';+import { setSessionRuntimeHarness } from '../sessionRuntimeHarnessSelection.js';+import { createPendingAgentSwitchRegistry, performSessionAgentSwitch } from '../sessionAgentSwitchHandler.js';+import { applyRuntimeSetModelChange } from '../runtimeSetModel.js';+import { mergeSessionRuntimeProfilePatch } from '../sessionRuntimeControl.js';+import { clearSessionProvider, getSessionProvider, setSessionProvider } from '../../maker-host/session-provider-store.js';++const source = readFileSync(resolve(__dirname, '../register.ts'), 'utf8');+const start = source.indexOf(' setSessionRuntime: async ({ targetSessionId, expectedGeneration, patch, beforeMutation }) =>');+const end = source.indexOf(' assertExternalInputAllowed:', start);+const mutationStart = source.indexOf('? await applyRuntimeSetModelChange({');+const mutationEnd = source.indexOf('})', source.indexOf(' logger: log,', mutationStart)) + 2;+const mutation = transpileModule(`return (async () => ${source.slice(mutationStart + 2, mutationEnd)})();`, {+ compilerOptions: { target: ScriptTarget.ES2022 },+}).outputText;+const adapter = transpileModule(`return ({${source.slice(start, end)}}).setSessionRuntime;`, {+ compilerOptions: { target: ScriptTarget.ES2022 },+}).outputText;++afterEach(() => clearSessionProvider('route-child'));++it.each(['catalog', 'harness-read', 'native-preview', 'valid-harness', 'valid-model'] as const)(+ 'carries the group authority through the actual host runtime adapter: %s', async point => {+ let revoked = false;+ const release = registerGroupToolAuthority('route-group', { botId: 'bot-route', mode: 'owner',+ isCurrent: () => true,+ validate: async () => { if (revoked) throw new GroupToolAuthorizationError(); } });+ const current = { agentKind: 'pi' as const, model: 'old', providerId: 'provider', effort: null, fastMode: false };+ const next = { ...current, agentKind: point === 'native-preview' || point === 'valid-model' ? 'pi' as const : 'codex' as const, model: 'next' };+ const pending = createPendingAgentSwitchRegistry();+ const nativeSet = vi.fn(async () => {});+ const close = vi.fn();+ const supersede = vi.fn();+ const profile = { control: { generation: 1, pending: null }, effective: current };+ const runtime = { ok: true, runtime: { runtimeGeneration: 1, effectiveProfile: current } };+ const maker = {+ getSession: () => ({ agentKind: 'pi' as const, model: 'old', setModel: nativeSet,+ previewModelSwitch: async () => {+ if (point === 'native-preview') revoked = true;+ return { action: 'hot' as const, targetContextWindow: 100000, windowVerified: true };+ } }),+ listActiveSessions: () => [], closeSession: close,+ };+ setSessionProvider('route-child', 'provider');+ const deps = {+ setSessionRuntimeHarness, performSessionAgentSwitch,+ withSendToSessionLock: async (_id: string, fn: () => Promise<unknown>) => fn(),+ captureSessionRuntimeControlOwnerEpoch: () => 'owner',+ getSessionRuntimeControlSnapshot: () => ({ generation: 1, effectiveOverride: current, pending: null }),+ agentSwitchPending: pending,+ readSessionRuntimeProfiles: async () => profile,+ assertModelRouteUsable: async () => null,+ getActiveCatalog: () => ({}),+ getDesktopProviderService: () => ({ listProviders: async () => {+ if (point === 'catalog') revoked = true;+ return [{ id: 'provider', connected: true }];+ } }),+ findCatalogModel: () => ({}),+ resolveSessionRuntimeAxes: () => ({ ok: true, effort: null, fastMode: false }),+ mergeSessionRuntimeProfilePatch,+ runtimeSelectionRequiresModelWindowConfirmation: () => false,+ agentSwitchDeps: {+ getSessionRow: async () => {+ if (point === 'harness-read') revoked = true;+ return { id: 'route-child', agentKind: 'pi', status: 'active' };+ },+ pendingSwitches: pending, supersedePendingCredentialSwitch: supersede,+ log: { info: vi.fn() },+ },+ applySessionRuntimeSelection: async (_id: string, model: string, providerId: string, _selection: unknown, options: { beforeMutation?: () => Promise<void> }) => {+ // Execute the host's real native-mutation adapter as well, so dropping the+ // callback at either host boundary makes the revocation case fail.+ const mutationDeps = {+ applyRuntimeSetModelChange, maker, internalOptions: options, sessionId: 'route-child', model,+ effectiveProviderId: providerId, assertRuntimeOwnerCurrent: vi.fn(), assertSharedTaskCurrent: { admit: vi.fn() },+ piConfigurationRefresh: false, canTransferThread: false, atomicSelection: { effort: null, fastMode: false },+ rebuildLiveOrcaWorker: false, runtimeAgentKind: 'pi', runtimeRouteChanged: true,+ isSessionInTurn: () => false, registerPendingCredentialSwitchForSession: vi.fn(),+ clearPendingCredentialSwitchForSession: vi.fn(), getPendingCredentialSwitchTarget: () => null,+ getCodexProxyAuthInjectionState: () => null, log: { debug: vi.fn(), info: vi.fn() },+ };+ const result = await new Function(...Object.keys(mutationDeps), mutation)(...Object.values(mutationDeps));+ return { deferred: result.status === 'deferred', generation: 1 };+ },+ };+ const host = new Function(...Object.keys(deps), adapter)(...Object.values(deps));+ const control = createSessionControlService({ sessionExists: async () => true, getLiveSession: () => null, setSessionRuntime: host } as never);+ const bridge = createBotSessionTaskRouteBridge({ getSessionRuntime: async () => runtime as never,+ setSessionRuntime: params => control.setSessionRuntime(params), readConfiguredCandidate: vi.fn() });+ try {+ const authority = await authorizeGroupTool('route-group', 'bot-route', 'owner-action');+ const action = bridge.advance('route-child', 1, next, authority.refresh);+ if (point.startsWith('valid')) {+ expect(await action).toMatchObject({ ok: true, status: point === 'valid-harness' ? 'deferred' : 'applied' });+ if (point === 'valid-harness') expect(pending.get('route-child')).toMatchObject({ model: 'next' });+ else expect(nativeSet).toHaveBeenCalledOnce();+ } else {+ await expect(action).rejects.toMatchObject({ code: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(pending.get('route-child')).toBeUndefined();+ expect(nativeSet).not.toHaveBeenCalled();+ expect(supersede).not.toHaveBeenCalled();+ }+ expect(close).not.toHaveBeenCalled();+ expect(getSessionProvider('route-child')).toBe('provider');+ } finally { release(); }+ },+);++it.each([true, false])('refreshes after the final deferred-route read (revoked=%s)', async revoked => {+ // Execute the production deferred commit closure, with its asynchronous metadata boundary.+ const begin = source.indexOf(' const deferLockedSelection = async () => {');+ const finish = source.indexOf(' // 远端回合中不能 live', begin);+ const js = transpileModule(`${source.slice(begin, finish)}\nreturn deferLockedSelection;`, {+ compilerOptions: { target: ScriptTarget.ES2022 },+ }).outputText;+ let prepared = false;+ const accept = vi.fn(() => 2);+ const deps = {+ sessionId: 'route-child', model: 'next', effectiveProviderId: 'provider', routeExplicit: true, atomicSelection: undefined,+ internalOptions: { source: 'agent', beforeMutation: async () => {+ if (prepared && revoked) throw new GroupToolAuthorizationError();+ } },+ maker: { getSessionMeta: async () => { prepared = true; return { agentKind: 'pi' }; }, getSession: () => null },+ supersededByOwnerBoundary: () => false, assertSharedTaskCurrent: { admit: vi.fn() },+ acceptSessionRuntimeMutation: accept, buildDeferredRuntimeSelectionProfile: (p: unknown) => p,+ getSessionFastMode: () => false, getPendingCredentialSwitchTarget: () => null,+ broadcastSessionRuntimeProjection: vi.fn(async () => {}), normalizeSessionProviderId: (id: string) => id,+ };+ const run = new Function(...Object.keys(deps), js)(...Object.values(deps));+ if (revoked) {+ await expect(run()).rejects.toMatchObject({ code: 'GROUP_AUTHORIZATION_REQUIRED' });+ expect(accept).not.toHaveBeenCalled();+ expect(deps.broadcastSessionRuntimeProjection).not.toHaveBeenCalled();+ } else {+ expect(await run()).toMatchObject({ deferred: true, generation: 2 });+ expect(accept).toHaveBeenCalledOnce();+ }+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageSourceNote.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageSourceNote.test.tsindex 8bfef64486..964b6403fa 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/messageSourceNote.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageSourceNote.test.ts@@ -4,7 +4,10 @@*/import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import ts from 'typescript';import { describe, expect, it } from 'vitest';+import { HOST_ONLY_AGENT_PREFIX, buildMakerUserMessage, sanitizeQueuedMessageForPersistence } from '../../../shared/agentInputQueue';+import { UI_ACTION_TRIGGER_PREFIX } from '../../../shared/interruptedTurn';import {buildWireMessageSourceNote,@@ -164,15 +167,32 @@ describe('delivery-path wiring (source contract)', () => {expect(pluginDispatch).not.toContain('origin:');});- it('host receipts keep queue rows hidden: prefix stays on text, wire assembly drops it', () => {+ it.each(['receipt', 'group-peer', 'user'])('preserves %s queue visibility and final model content', async kind => {const builder = between(register,'async function buildSessionControlInputItem','const orcaInterAgentDispatcher',);- expect(builder).toContain(- 'text: hiddenTriggerForAgent ? params.persistedContent : params.message',- );- expect(builder).toContain('agentOmitsTriggerPrefix: true as const');+ // Execute the actual host builder with only its runtime dependencies stubbed.+ // This protects the behavior without fixing its conditional expression shape.+ const js = ts.transpileModule(`${builder}\nreturn buildSessionControlInputItem;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ const build = new Function('buildCreateOptsForQueuedSession', 'permissionModeOrAsk', 'UI_ACTION_TRIGGER_PREFIX', 'HOST_ONLY_AGENT_PREFIX', js)(+ async () => ({ model: 'fixture', workingDir: '/fixture', permissionMode: 'ask' }),+ (mode: string) => mode, UI_ACTION_TRIGGER_PREFIX, HOST_ONLY_AGENT_PREFIX);+ const body = 'Delivery body';+ const message = kind === 'group-peer' ? '[Group source: Design (group-1); lane: lane-1]\n\n' + body : body;+ const persistedContent = kind === 'user' ? body : UI_ACTION_TRIGGER_PREFIX + body;+ const queued = await build({ targetSessionId: 'target', meta: {}, message, persistedContent,+ clientId: kind === 'group-peer' ? 'bot-dm:fixture' : 'fixture' });+ expect(queued.text).toBe(persistedContent);+ expect(queued.agentOmitsTriggerPrefix).toBe(kind === 'user' ? undefined : true);+ expect(buildMakerUserMessage(queued)).toEqual({ type: 'user', content: message });+ const snapshot = sanitizeQueuedMessageForPersistence(queued);+ expect(snapshot.text).toBe(persistedContent);+ expect(snapshot.persistedContent).toBe(persistedContent);+ expect(snapshot[HOST_ONLY_AGENT_PREFIX]).toBeUndefined();+ expect(JSON.stringify(snapshot)).not.toMatch(/Group source|group-1|lane-1/);});});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.tsindex 694911d913..71e2ea5a5d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskAuthorshipWiring.test.ts@@ -3,6 +3,8 @@ import { resolve } from 'node:path';import ts from 'typescript';import { expect, it, vi } from 'vitest';import { appendAutoReviewUserIntent, AUTO_REVIEW_DELEGATED_CONTINUATION, AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT, MAIN_OWNED_SEND_CONTEXT, type SendOptions } from '@cindy/maker-core';+import { HOST_ONLY_AGENT_PREFIX, buildMakerUserMessage, sanitizeQueuedMessageForPersistence } from '../../../shared/agentInputQueue.js';+import { redactInputProjectionForSharedGuest } from '../../device-link/sharedTaskMessageOrigin.js';const source = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8');const compile = (code: string) => ts.transpileModule(code, {@@ -73,9 +75,9 @@ it('builds a durable queued plugin input without promoting plugin text to user iconst end = source.indexOf(' const orcaInterAgentDispatcher:', start);expect(start).toBeGreaterThan(0);const createOpts = { model: 'm', effort: 'high', permissionMode: 'auto', workingDir: '/answer' };- const build = new Function('buildCreateOptsForQueuedSession', 'permissionModeOrAsk', 'UI_ACTION_TRIGGER_PREFIX',+ const build = new Function('buildCreateOptsForQueuedSession', 'permissionModeOrAsk', 'UI_ACTION_TRIGGER_PREFIX', 'HOST_ONLY_AGENT_PREFIX',compile(source.slice(start, end) + '\nreturn buildSessionControlInputItem;'))(- vi.fn(async () => createOpts), (mode: string) => mode, '[UI_ACTION_TRIGGER]',+ vi.fn(async () => createOpts), (mode: string) => mode, '[UI_ACTION_TRIGGER]', HOST_ONLY_AGENT_PREFIX,);const base = { targetSessionId: 'lead', clientId: 'plugin-input', message: 'Plugin instructions', persistedContent: 'Plugin instructions', meta: {} };const queued = JSON.parse(JSON.stringify(await build({ ...base, autoReviewUserText: { kind: 'delegated-continuation' } })));@@ -92,9 +94,9 @@ it('keeps host receipts hidden in the queue while the model text omits the triggconst start = source.indexOf(' async function buildSessionControlInputItem(params: {');const end = source.indexOf(' const orcaInterAgentDispatcher:', start);const createOpts = { model: 'm', effort: 'high', permissionMode: 'auto', workingDir: '/answer' };- const build = new Function('buildCreateOptsForQueuedSession', 'permissionModeOrAsk', 'UI_ACTION_TRIGGER_PREFIX',+ const build = new Function('buildCreateOptsForQueuedSession', 'permissionModeOrAsk', 'UI_ACTION_TRIGGER_PREFIX', 'HOST_ONLY_AGENT_PREFIX',compile(source.slice(start, end) + '\nreturn buildSessionControlInputItem;'))(- vi.fn(async () => createOpts), (mode: string) => mode, '[UI_ACTION_TRIGGER]',+ vi.fn(async () => createOpts), (mode: string) => mode, '[UI_ACTION_TRIGGER]', HOST_ONLY_AGENT_PREFIX,);const receipt = '[任务回执] 后台任务已完成。task_id: d-1';const queued = await build({@@ -103,6 +105,24 @@ it('keeps host receipts hidden in the queue while the model text omits the trigg});// Queue rows mask on `text`; the prefix stays there and is dropped at wire assembly.expect(queued).toMatchObject({ text: `[UI_ACTION_TRIGGER]${receipt}`, persistedContent: `[UI_ACTION_TRIGGER]${receipt}`, agentOmitsTriggerPrefix: true });+ // A group DM has a private wire envelope and a separate safe durable body.+ // Keep the queue row hidden without substituting the safe body into the model input.+ const envelope = '[Group source: Private group (group-private); lane: private-lane]\n\nMessage body';+ const groupInput = await build({+ targetSessionId: 'lead', clientId: 'bot-dm:fixture', meta: {},+ message: envelope, persistedContent: '[UI_ACTION_TRIGGER]Message body',+ origin: { kind: 'session', senderSessionId: 'private-lane', displayText: envelope },+ });+ expect(groupInput).toMatchObject({ text: '[UI_ACTION_TRIGGER]Message body', agentOmitsTriggerPrefix: true,+ persistedContent: '[UI_ACTION_TRIGGER]Message body', chatMessage: { content: '[UI_ACTION_TRIGGER]Message body' } });+ expect(buildMakerUserMessage(groupInput)).toMatchObject({ content: envelope });+ const snapshot = sanitizeQueuedMessageForPersistence(groupInput);+ expect(snapshot[HOST_ONLY_AGENT_PREFIX]).toBeUndefined();+ expect(snapshot.text).toBe('[UI_ACTION_TRIGGER]Message body');+ expect(snapshot.origin).toMatchObject({ kind: 'session', displayText: '[UI_ACTION_TRIGGER]Message body' });+ expect(JSON.stringify(snapshot)).not.toContain('Group source:');+ const guest = redactInputProjectionForSharedGuest({ pendingQueue: [groupInput], recovery: { item: groupInput } });+ expect(JSON.stringify(guest)).not.toMatch(/Private group|group-private|private-lane|Group source/);// Ordinary prefixed synthetic input (continue prompts) is untouched.const continueItem = await build({targetSessionId: 'lead', clientId: 'c', meta: {},diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.tsindex bf00e91e5f..1d5e0542fd 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts@@ -56,7 +56,7 @@ function setup(running = false) {pendingRevision: (id) => pending.revision!(id),read: vi.fn(async () => effective),resolve: vi.fn(async (profile) => ({ ...profile, providerId: profile.providerId ?? 'openai' })),- stage: (id, profile, assertCurrent) =>+ stage: (id, profile, assertCurrent, beforeMutation) =>performSessionAgentSwitch(switchDeps, {sessionId: id,targetAgentKind: profile.agentKind,@@ -66,6 +66,7 @@ function setup(running = false) {fastMode: profile.fastMode,runtimeSource: 'agent',assertSelectionCurrent: assertCurrent,+ beforeMutation,}),pending: (id) => pending.get(id),};diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex ba06764131..88173aae76 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -1,6 +1,7 @@import { AUTO_REVIEW_SOURCE_CONTENT, AUTO_REVIEW_USER_INTENT } from '@cindy/maker-core';import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';import { assertSharedTaskQueueMutation } from './sharedTaskInput.js';+import { isBotGroupClientId } from '../../shared/botGroupChat.js';import { SchedulerQueuedPreparationError } from './schedulerQueuedPreparation.js';/*** AgentInputCoordinator — main 侧排队输入事务协调器。@@ -63,6 +64,7 @@ import type {RecoveryCheckpoint,} from '../../shared/agentInputQueue.js';import {+ HOST_ONLY_AGENT_PREFIX,buildMakerUserMessage,getAgentInputAttachmentBlockType,getAgentFacingText,@@ -959,6 +961,8 @@ interface SteerObservation {}interface SteerOptions {+ /** Host-only authority check after async preparation and before native injection. */+ beforeMutation?: () => Promise<void>;removeFromQueue?: boolean;touchUserSend?: boolean;/** 控制面插话不允许在 turn 结束竞态下退化成下一轮普通输入。 */@@ -1478,7 +1482,14 @@ export class AgentInputCoordinator {// 排队/直发,不丢任务只丢陈旧副本。const restorable = boundaryFilteredItems.filter((item) => !existingIds.has(item.clientId));const staleSchedulerItems = restorable.filter((item) => item.origin?.kind === 'scheduler');- const restored = restorable.filter((item) => item.origin?.kind !== 'scheduler');+ // A group lane is reusable, but an execution lease is not. Snapshot rows+ // have lost the originating execution's callbacks; a new claim on this+ // lane must never authorize their prompts (including restored plan inputs).+ const staleGroupItems = restorable.filter((item) => isBotGroupClientId(item.clientId));+ const restored = restorable.filter((item) => item.origin?.kind !== 'scheduler' && !isBotGroupClientId(item.clientId));+ for (const item of staleGroupItems) {+ if (item.origin?.kind !== 'scheduler') this.deps.onDiscardedQueuedMessage?.(sessionId, item);+ }if (staleSchedulerItems.length > 0) {for (const item of staleSchedulerItems) {this.deps.onDiscardedQueuedMessage?.(sessionId, item);@@ -2396,8 +2407,15 @@ export class AgentInputCoordinator {}}+ let authorizationFailed = false;try {const referenceContexts = await this.resolveReferenceContexts(item);+ try {+ await opts?.beforeMutation?.();+ } catch (error) {+ authorizationFailed = true;+ throw error;+ }// 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);@@ -2471,6 +2489,13 @@ export class AgentInputCoordinator {});this.clearSteerAbortController(sessionId, item.clientId, steerAbort);+ if (authorizationFailed) {+ if (markerStillPresent) this.clearDirectSteeringItem(latest, item.clientId);+ this.emit(sessionId);+ finishSteerRequest(false);+ throw err;+ }+if (isStaleTurnError(err)) {if (markerStillPresent) {this.clearDirectSteeringItem(latest, item.clientId);@@ -4270,6 +4295,7 @@ export class AgentInputCoordinator {/** Renderer projection may carry routing hints, but never quoted history bodies. */private toProjectedItem(item: AgentInputQueuedMessage): AgentInputQueuedMessage {const projected = { ...item };+ delete projected[HOST_ONLY_AGENT_PREFIX];delete projected.hostAcceptedAtMs;delete projected.autoReviewUserText;delete projected.fromDeviceLinkClient;diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.tsindex 9cbf526dc9..fbcf9fac5d 100644--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts@@ -16,6 +16,7 @@ import {describeMessageSourceSender,formatSourceRef,messageSourceSenderFromMeta,+ readMessageSourceGroup,readMessageSourceDevice,promptSafeSourceName,} from '@cindy/maker-shared/message-source';@@ -455,8 +456,11 @@ function splitTurns(messages: HandoffSourceMessage[], includeToolResults = falsecase 'assistant': {const text = extractPlainText(msg.content);if (text) {- current.detailLines.push(`[Assistant]\n${truncate(text, RECENT_TEXT_CAP)}`);- current.lastAssistantText = text;+ const groupSource = readMessageSourceGroup(parseJsonObjectString(msg.agentMeta))+ ? describeHandoffUserSource(msg) : null;+ const label = groupSource ? `[Assistant · ${groupSource}]` : '[Assistant]';+ current.detailLines.push(`${label}\n${truncate(text, RECENT_TEXT_CAP)}`);+ current.lastAssistantText = groupSource ? `${label} ${text}` : text;}break;}diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.tsindex 889b6e9a7e..aada988234 100644--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts@@ -13,8 +13,9 @@ import type { PluginRegistry } from '../maker-host/plugins/plugin-registry.js';import type { BotToolsetContext } from '../../shared/botRemoteCapabilities.js';import type { BotProfileRuntimeDeps } from './botProfileRuntime.js';import type { BotModelRoute } from '../../shared/botModelChain.js';-import { readEffectiveBotModelChain } from '../maker-host/bot-model-chain-settings-store.js';+import { readEffectiveBotModelChain, readExplicitBotModelChain } from '../maker-host/bot-model-chain-settings-store.js';import { throwIpcError } from '../utils/ipcValidate.js';+import { authorizeGroupTool, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';type Kind = 'skill' | 'mcp' | 'toolset';type Input = { callerSessionId: string; kind: Kind };@@ -41,7 +42,7 @@ const strings = (value: unknown): string[] =>Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];/** Only the live owner may select capabilities; no caller-supplied Bot or connection config. */-async function context(callerSessionId: string, opts?: { allowPaused?: boolean }) {+async function context(callerSessionId: string, opts?: { allowPaused?: boolean; readScope?: 'self' | 'owner' }) {const owner = activeOwnerScopeKey();const assertOwner = () => {if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner)@@ -79,14 +80,16 @@ async function context(callerSessionId: string, opts?: { allowPaused?: boolean }.where(eq(botSessionLinks.sessionId, callerSessionId)).limit(1);assertOwner();+ const groupAuthority = row?.role === 'group' && opts?.readScope+ ? await authorizeGroupTool(callerSessionId, row.botId, opts.readScope === 'self' ? 'read-self' : 'owner-action') : null;+ assertOwner();const profileAllowed =row?.profileStatus === 'active' ||(opts?.allowPaused === true && row?.profileStatus === 'paused');if (!row ||row.source !== 'bot' ||- row.role !== 'canonical' ||- row.canonicalSessionId !== callerSessionId ||+ (!groupAuthority && (row.role !== 'canonical' || row.canonicalSessionId !== callerSessionId)) ||row.archivedAt !== null ||row.sessionStatus !== 'active' ||!profileAllowed@@ -98,7 +101,13 @@ async function context(callerSessionId: string, opts?: { allowPaused?: boolean }parsed && typeof parsed === 'object' && !Array.isArray(parsed)? (parsed as Record<string, unknown>): {};- return { ...row, config: normalizeBotToolCapabilities(config), assertOwner };+ return { ...row, config: normalizeBotToolCapabilities(config), canReadOwnerModels: !groupAuthority || groupAuthority.mode === 'owner', assertOwner: () => {+ assertOwner(); groupAuthority?.assertCurrent();+ }, refresh: async () => {+ assertOwner();+ await groupAuthority?.refresh();+ assertOwner();+ } };}async function catalog(input: Input, ctx: Pick<Awaited<ReturnType<typeof context>>, 'config' | 'workingDir' | 'remoteHostId' | 'botId' | 'assertOwner'>, deps: BotCapabilityServiceDeps,@@ -173,14 +182,16 @@ async function catalog(input: Input, ctx: Pick<Awaited<ReturnType<typeof contextasync function findBotCapabilities(input: Input & { query?: string }, deps: BotCapabilityServiceDeps) {try {- const ctx = await context(input.callerSessionId);+ const ctx = await context(input.callerSessionId, { readScope: 'owner' });const query = input.query?.trim().toLocaleLowerCase() ?? '';const capabilities = (await catalog(input, ctx, deps)).filter((item) =>!query || `${item.id} ${item.name} ${item.description}`.toLocaleLowerCase().includes(query),);+ await ctx.refresh();return { ok: true as const, capabilities: capabilities.slice(0, 50) };- } catch {+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) return { ok: false as const, errorCode: error.code, message: error.message };return {ok: false as const,errorCode: 'CAPABILITY_DISCOVERY_FAILED',@@ -222,7 +233,8 @@ async function selectBotCapability(input: Input & { id: string; joined: boolean);ctx.assertOwner();return { ok: true as const, joined: input.joined, effective: 'next-turn' as const };- } catch {+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) return { ok: false as const, errorCode: error.code, message: error.message };return {ok: false as const,errorCode: 'CAPABILITY_SELECTION_FAILED',@@ -236,11 +248,12 @@ export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {return {async models(input: { callerSessionId: string }) {try {- const ctx = await context(input.callerSessionId);+ const ctx = await context(input.callerSessionId, { readScope: 'owner' });const selection = await inspectAppDefaultModel();- ctx.assertOwner();+ await ctx.refresh();return { ok: true as const, ...selection };- } catch {+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) return { ok: false as const, errorCode: error.code, message: error.message };return { ok: false as const, errorCode: 'MODEL_SETTINGS_UNAVAILABLE', message: '无法读取当前用户的默认模型和可用型号' };}},@@ -250,28 +263,31 @@ export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {const result = await changeAppDefaultModel(input.id, input.effort, ctx.assertOwner);ctx.assertOwner();return { ok: true as const, ...result };- } catch {+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) return { ok: false as const, errorCode: error.code, message: error.message };return { ok: false as const, errorCode: 'MODEL_DEFAULT_NOT_CONFIRMED', message: '默认模型未确认保存;型号可能已停用、账号或选择已变化,请重新查询当前设置。' };}},async inspect(input: { callerSessionId: string }) {try {- const ctx = await context(input.callerSessionId);- const candidates = await readEffectiveBotModelChain(ctx.config);- ctx.assertOwner();+ const ctx = await context(input.callerSessionId, { readScope: 'self' });+ const explicit = readExplicitBotModelChain(ctx.config);+ // A self-read may report inherited selection without exposing owner route IDs.+ const candidates = explicit === null && !ctx.canReadOwnerModels+ ? [] : await readEffectiveBotModelChain(ctx.config);+ await ctx.refresh();const state: BotControlState = {profile: { id: ctx.botId, name: ctx.displayName, description: ctx.description,identitySource: ctx.identitySource, version: ctx.version },session: { id: input.callerSessionId, workingDir: ctx.workingDir, remoteHostId: ctx.remoteHostId },- model: { source: Array.isArray(ctx.config.modelChainOverride) && ctx.config.modelChainOverride.length > 0 ? 'override'- : ctx.config.modelChainOverride === null || ctx.config.modelOverride === null- || (!Array.isArray(ctx.config.modelChainOverride) && !Array.isArray(ctx.config.modelChain) && typeof ctx.config.model !== 'string') ? 'default' : 'override', candidates },+ model: { source: explicit === null ? 'default' : 'override', candidates },memory: { enabled: ctx.config.memory !== false, scope: 'self' },references: { skills: strings(ctx.config.skills), mcpServers: strings(ctx.config.mcpServers),toolsets: strings(ctx.config.toolsets) },};return { ok: true as const, state };- } catch {+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) return { ok: false as const, errorCode: error.code, message: error.message };return { ok: false as const, errorCode: 'BOT_STATE_UNAVAILABLE', message: '无法读取当前伙伴状态,请稍后重试' };}},@@ -311,7 +327,8 @@ export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {}, input.expectedVersion);ctx.assertOwner();return { ok: true as const, effective: 'next-turn' as const };- } catch {+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) return { ok: false as const, errorCode: error.code, message: error.message };return { ok: false as const, errorCode: 'BOT_PROFILE_UPDATE_FAILED',message: '伙伴资料已变化,或所选模型及档位不可用;请重新读取伙伴状态和可用型号后重试' };}diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex dfa9f82a4a..fd3e68a9f3 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -1,4 +1,5 @@import { openSession } from '../localDb/sessionOpening.js';+import { authorizeGroupTool, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';import { existsSync, statSync } from 'node:fs';import type { AgentInputCoordinator } from './agent-input-coordinator.js';@@ -120,8 +121,8 @@ export interface BotDelegationServiceDeps {abortSession: (sessionId: string) => Promise<void>;discardDelegationQueuedInputs?: (sessionId: string, delegationId: string) => Promise<void>;taskControl?: {- steer(params: { callerSessionId: string; targetSessionId: string; message: string; queuedMessageId?: string }): Promise<SessionSteerResult>;- stop(params: { targetSessionId: string }): Promise<SessionStopResult>;+ steer(params: { callerSessionId: string; targetSessionId: string; message: string; queuedMessageId?: string; beforeMutation?: () => Promise<void> }): Promise<SessionSteerResult>;+ stop(params: { targetSessionId: string; beforeMutation?: () => Promise<void> }): 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. */@@ -134,7 +135,7 @@ export interface BotDelegationServiceDeps {};discardUnusedWorktree?: (sessionId: string) => Promise<void>;getWorktree?: (sessionId: string) => { path: string } | null;- reconcileWorktree?: (sessionId: string) => Promise<void>;+ reconcileWorktree?: (sessionId: string, beforeMutation?: () => Promise<void>) => Promise<void>;withTransferredWorktree?: <T extends { reopened: boolean }>(previousSessionId: string, sessionId: string, worktreePath: string, commit: () => Promise<T>,identity: { delegationId: string; requestingBotId: string },@@ -142,8 +143,8 @@ export interface BotDelegationServiceDeps {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>;+ update(params: { callerSessionId: string; targetSessionId: string; queuedMessageId: string; message: string; beforeMutation?: () => Promise<void> }): Promise<SessionQueuedMessageControlResult>;+ cancel(params: { callerSessionId: string; targetSessionId: string; queuedMessageId: string; beforeMutation?: () => Promise<void> }): Promise<SessionQueuedMessageControlResult>;};closeSession?: (sessionId: string) => Promise<void>;broadcastSessionCreated?: (sessionId: string) => void;@@ -185,7 +186,7 @@ export interface BotDelegationServiceDeps {| { ok: true; generation: number; current: SessionRuntimeProfile; next: SessionRuntimeProfile | null }| { ok: false; errorCode: string; message: string }>;- advance(childSessionId: string, expectedGeneration: number, route: SessionRuntimeProfile): Promise<+ advance(childSessionId: string, expectedGeneration: number, route: SessionRuntimeProfile, beforeApply?: () => Promise<void>): Promise<| { ok: true; status: 'applied' | 'deferred'; generation: number }| { ok: false; errorCode: string; message: string }>;@@ -543,6 +544,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {row: DelegationRow,input: { clientId: string; message: string; persistedContent?: string; dispatcherSessionId?: string },retryAttempt = false,+ groupAuthority?: Awaited<ReturnType<typeof authorizeGroupTool>> | null,): Promise<{ result: DispatchResult; row: DelegationRow; clientId: string }> => {const db = getDbClient().drizzle;const retry = parseRecord(row.permissionSnapshotJson).taskRecoveryRetry as@@ -551,8 +553,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {? retry.clientId : input.clientId;let replayed = false;let acceptedThisAttempt = false;+ await groupAuthority?.refresh();const result = await deps.dispatch({ ...input, clientId, targetSessionId: row.childSessionId!,onAccepted: async persisted => {+ await groupAuthority?.refresh();if (persisted) { replayed = true; return; }await acceptExecution(row, clientId, input.clientId);acceptedThisAttempt = true;@@ -593,9 +597,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {inArray(botDelegations.status, [...ACTIVE_DELEGATION_STATUSES]))).returning();if (!saved) return { clientId, row: current, result: { ok: false, errorCode: 'TASK_CHANGED', message: 'Task changed before recovery retry' } };if (retryAttempt) return { clientId, row: saved, result: { ok: false, errorCode: 'TEMPORARILY_UNAVAILABLE', message: 'Recovery input has not reached native acceptance' } };- const validation = await validateDispatchPlan(saved);+ const validation = await validateDispatchPlan(saved, groupAuthority);if (!validation.ok) return { clientId, row: saved, result: validation };- return dispatchTrackedInput(saved, input, true);+ return dispatchTrackedInput(saved, input, true, groupAuthority);};const cleanupChildSession = async (@@ -704,7 +708,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const ensureTargetCanonicalSession = async (target: {id: string;currentVersion: number;- }): Promise<BotDelegationResult<{ sessionId: string }>> => {+ }, beforeRecovery?: () => Promise<void>): Promise<BotDelegationResult<{ sessionId: string }>> => {const db = getDbClient().drizzle;const registered = await resolveBotCanonicalSession(target.id);let expectedCanonicalSessionId = registered.status === 'resolved'@@ -731,21 +735,25 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {) {return { ok: true, sessionId: expectedCanonicalSessionId };}+ await beforeRecovery?.();const replacement = await createBotCanonicalSession({botId: target.id,+ // This is an authoritative link CAS, including a dangling link. The+ // mirror-only recovery mode would incorrectly compare it against null.+ // The shared transaction still refuses to replace a healthy Session.expectedCanonicalSessionId,expectedProfileVersion: target.currentVersion,- recoverMissingOnly: current === undefined,- });+ }, beforeRecovery);if (replacement.created) deps.broadcastSessionCreated?.(replacement.canonicalSessionId);expectedCanonicalSessionId = replacement.canonicalSessionId;continue;}+ await beforeRecovery?.();const created = await createBotCanonicalSession({botId: target.id,expectedCanonicalSessionId: null,expectedProfileVersion: target.currentVersion,- });+ }, beforeRecovery);if (created.created) deps.broadcastSessionCreated?.(created.canonicalSessionId);expectedCanonicalSessionId = created.canonicalSessionId;}@@ -756,6 +764,19 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};};+ const ensureCanonicalSession = async (botId: string, beforeRecovery?: () => Promise<void>) => {+ const [profile] = await getDbClient().drizzle+ .select({ id: botProfiles.id, currentVersion: botProfiles.currentVersion, status: botProfiles.status })+ .from(botProfiles)+ .where(eq(botProfiles.id, botId))+ .limit(1);+ if (!profile || profile.status !== 'active') {+ return { ok: false as const, errorCode: 'TARGET_BOT_INACTIVE', message: '目标伙伴已暂停或归档' };+ }+ await beforeRecovery?.();+ return ensureTargetCanonicalSession({ id: profile.id, currentVersion: profile.currentVersion }, beforeRecovery);+ };+/*** 冻结这次协作双方的展示身份。名字后来改了不回填历史消息——消息流讲的是* 「当时谁把活交给了谁」,不是「他们现在叫什么」。@@ -1329,6 +1350,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.select({botId: botSessionLinks.botId,role: botSessionLinks.role,+ routeKey: botSessionLinks.routeKey,profileVersion: botSessionLinks.profileVersion,sessionStatus: sessions.status,sessionSource: sessions.source,@@ -1354,11 +1376,23 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {|| link.sessionSource !== 'bot'|| link.profileStatus !== 'active'|| link.linkArchivedAt !== null- || (link.role !== 'canonical' && link.role !== 'delegation')+ || !['canonical', 'delegation', 'group'].includes(link.role)) return null;- return link;+ // Delegating full independent work is an owner action, not a guest tool grant.+ const groupAuthority = link.role === 'group'+ ? await authorizeGroupTool(callerSessionId, link.botId, 'owner-action') : null;+ return { ...link, groupAuthority };};+ const callerTaskScope = (caller: { botId: string; role: string; routeKey: string | null }) => and(+ eq(botDelegations.requestingBotId, caller.botId),+ caller.role === 'group'+ ? sql`CASE WHEN json_valid(${botDelegations.permissionSnapshotJson}) THEN+ json_extract(${botDelegations.permissionSnapshotJson}, '$.groupOriginRoute') = ${caller.routeKey}+ ELSE 0 END`+ : undefined,+ );+const interactionSummary = (request: InteractionRequest): string => {if (request.kind === 'permission') {return (@@ -1584,9 +1618,17 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.filter(Boolean).join('\n\n');+ const reconcileTaskWorktree = async (sessionId: string, authority?: Awaited<ReturnType<typeof authorizeGroupTool>> | null) => {+ await authority?.refresh();+ try { await deps.reconcileWorktree?.(sessionId, authority?.refresh); }+ finally { await authority?.refresh(); }+ };+const validateDispatchPlan = async (row: DelegationRow,+ groupAuthority?: Awaited<ReturnType<typeof authorizeGroupTool>> | null,): Promise<BotDelegationResult> => {+ await groupAuthority?.refresh();const plan = parseBotDelegationPlanSnapshot(row.permissionSnapshotJson);if (!plan || plan.targetBotId !== row.targetBotId) {return {@@ -1598,13 +1640,14 @@ 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' }; }+ try { await reconcileTaskWorktree(row.childSessionId, groupAuthority); }+ catch (error) { if (error instanceof GroupToolAuthorizationError) throw error; return { ok: false, errorCode: 'WORKTREE_TRANSFER_PENDING', message: 'Task worktree ownership is awaiting reconciliation' }; }const db = getDbClient().drizzle;const liveRequesterSessionId = await requesterLiveSessionId(row.requestingBotId,row.parentSessionId,);+ await groupAuthority?.refresh();if (!liveRequesterSessionId) {return { ok: false, errorCode: 'PARENT_SESSION_INACTIVE', message: '发起任务已归档或删除' };}@@ -1622,6 +1665,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.from(sessions).where(eq(sessions.id, row.childSessionId)).limit(1);+ await groupAuthority?.refresh();if (child?.status !== 'active'|| child.source !== 'desktop') {return { ok: false, errorCode: 'CHILD_SESSION_INVALID', message: '后台任务已归档或删除' };@@ -1707,13 +1751,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const startClientId = `bot-delegation-start:${row.id}${row.runSequence > 1 ? `:${row.runSequence}` : ''}`;const clientId = retryReceipt?.runSequence === row.runSequence ? retryReceipt.clientId : startClientId;let persistedReplay = false;+ const groupOriginSessionId = parseRecord(row.permissionSnapshotJson).groupOriginSessionId;const dispatched = await deps.dispatch({targetSessionId: row.childSessionId,message: buildDelegationPrompt(row),persistedContent: readSessionTaskInput(row)?.followUp ?? row.objective,clientId,// 子任务首条消息标出发起委派的父任务,接收方据此渲染可跳转的来源标签。- ...(row.parentSessionId ? { dispatcherSessionId: row.parentSessionId } : {}),+ ...(row.parentSessionId ? { dispatcherSessionId: typeof groupOriginSessionId === 'string' ? groupOriginSessionId : row.parentSessionId } : {}),onAccepted: async replayed => {if (replayed) { persistedReplay = true; return; }const acceptedAt = now();@@ -2073,6 +2118,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {inArray(botDelegations.status, [...ACTIVE_DELEGATION_STATUSES]),),);+ await caller.groupAuthority?.refresh();if (active.length >= maxActiveChildren) {return {ok: false,@@ -2113,6 +2159,20 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {status: 'queued' | 'running' | 'failed';deadlineAt: number;}>> => {+ // The execution caller remains the group lane. Only its owner may create+ // independent work, whose durable cards/decisions return to that owner's+ // existing teammate chat rather than the hidden, short-lived group lane.+ let parentSessionId = input.callerSessionId;+ if (input.caller.role === 'group') {+ await input.caller.groupAuthority?.refresh();+ const ensured = await ensureCanonicalSession(input.caller.botId, input.caller.groupAuthority?.refresh)+ .finally(() => input.caller.groupAuthority?.refresh());+ if (!ensured.ok) return ensured;+ // Resolve the authoritative link again rather than trusting a stale recovery result.+ parentSessionId = await requesterLiveSessionId(input.caller.botId, null) ?? '';+ }+ if (!parentSessionId) return { ok: false, errorCode: 'TARGET_CANONICAL_UNAVAILABLE',+ message: new GroupToolAuthorizationError().message };const delegationId = createId();let childSessionId = resolveBusinessSessionId(undefined);if (input.useWorktree) {@@ -2130,9 +2190,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const createdAt = input.plan.createdAt;const { source: taskSource, ...sessionBody } = input.session;try {+ await input.caller.groupAuthority?.refresh();await openSession({ id: childSessionId, now: createdAt, source: taskSource,body: { ...sessionBody, workspaceKind: input.session.workspaceKind ?? 'dialogue' },finalize: () => {+ input.caller.groupAuthority?.assertCurrent();// Read stable authority after asynchronous preparation, with no await before// submitting creation. Both persisted records must use this same snapshot.const callerPermission = deps.readCallerPermission@@ -2143,6 +2205,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}permissionMode = permissionModeOrAsk(typeof callerPermission === 'string' ? callerPermission : callerPermission.mode);isCreationPermissionCurrent = (): boolean => {+ try { input.caller.groupAuthority?.assertCurrent(); } catch { return false; }if (!deps.readCallerPermission) return true;const current = deps.readCallerPermission(input.callerSessionId);if (current === null) return false;@@ -2152,6 +2215,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};plan = {...input.plan,+ completionTarget: { parentSessionId },permission: {mode: permissionMode,requesterMode: permissionMode,@@ -2161,11 +2225,12 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};permissionSnapshotJson = JSON.stringify({ ...plan,+ ...(input.caller.role === 'group' ? { groupOriginRoute: input.caller.routeKey, groupOriginSessionId: input.callerSessionId } : {}),...(input.taskModelOverride ? { taskModelOverride: input.taskModelOverride } : {}),taskInput: { runSequence: 1, originalObjective: input.objective, followUp: null } satisfies SessionTaskInputSnapshot,});- return { permissionMode, parentSessionId: input.callerSessionId };+ return { permissionMode, parentSessionId };},}, async childRow => {await getDbClient().tx('bots.createDelegation', {@@ -2182,7 +2247,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {agentKind: childRow.agentKind,remoteHostId: null,providerId: childRow.providerId ?? null,- parentSessionId: input.callerSessionId,+ parentSessionId,extraDirs: childRow.extraDirs,source: childRow.source,createdAt: childRow.createdAt,@@ -2192,7 +2257,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {id: delegationId,requestingBotId: input.caller.botId,targetBotId: null,- parentSessionId: input.callerSessionId,+ parentSessionId,childSessionId,objective: input.objective,contextRefsJson: JSON.stringify(input.contextRefs),@@ -2210,7 +2275,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {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()) {+ const groupPermissionCurrent = await input.caller.groupAuthority?.refresh().then(() => true, () => false) ?? true;+ if (!groupPermissionCurrent || !isCreationPermissionCurrent()) {await getDbClient().drizzle.update(sessions).set({ permissionMode: 'ask' }).where(eq(sessions.id, childSessionId));await updateTerminal({ delegationId, status: 'failed',@@ -2219,7 +2285,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}emitChanged({delegationId,- parentSessionId: input.callerSessionId,+ parentSessionId,childSessionId,status: 'queued',});@@ -2246,7 +2312,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {requestingBotId: input.caller.botId,targetBotId: null,objective: input.objective,- parentSessionId: input.callerSessionId,+ parentSessionId,childSessionId,permissionSnapshotJson,createdAt,@@ -2273,7 +2339,12 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}scheduleTimeout(delegationId, plan.limits.deadlineAt);- const dispatchResult = await withTaskOperation(delegationId, () => attemptDispatch(delegationId, 0, isCreationPermissionCurrent));+ // A group task is independently authorized by the post-commit check above.+ // Its persisted permission snapshot also governs retries/restoration; do not+ // retain the short-lived originating execution in its delivery retry closure.+ const dispatchResult = await withTaskOperation(delegationId, () => attemptDispatch(+ delegationId, 0, input.caller.role === 'group' ? undefined : isCreationPermissionCurrent,+ ));return {ok: true,delegationId,@@ -2290,6 +2361,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {input: SessionTaskInput,): Promise<BotDelegationResult<{modelRoute: BotModelRoute;+ completionDestination?: 'teammate-private-chat';delegationId: string;childSessionId: string;/**@@ -2329,6 +2401,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.from(sessions).where(eq(sessions.id, input.callerSessionId)).limit(1);+ await caller.groupAuthority?.refresh();if (!callerSession) {return { ok: false, errorCode: 'NOT_A_BOT_SESSION', message: '当前任务不属于任何伙伴' };}@@ -2338,15 +2411,22 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.innerJoin(botProfileVersions, and(eq(botProfileVersions.botId, botProfiles.id),eq(botProfileVersions.version, botProfiles.currentVersion))).where(eq(botProfiles.id, caller.botId)).limit(1);+ await caller.groupAuthority?.refresh();let taskModel: BotModelRoute | null;try {taskModel = input.modelSelection !== undefined? await (deps.resolveTaskModelSelection ?? resolveTaskModelSelection)(input.modelSelection): readBotTaskModelOverride(parseRecord(profile?.config).taskModelOverride);- if (input.modelSelection === undefined && taskModel && !await (deps.validateTaskModel ?? validateTaskModel)(taskModel)) {+ await caller.groupAuthority?.refresh();+ const valid = input.modelSelection !== undefined || !taskModel+ || await (deps.validateTaskModel ?? validateTaskModel)(taskModel);+ await caller.groupAuthority?.refresh();+ if (!valid) {return { ok: false, errorCode: 'TASK_MODEL_UNAVAILABLE', message: '任务模型不可用,请在伙伴模型设置中重新选择后重试' };}- } catch {+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) throw error;+ await caller.groupAuthority?.refresh();return { ok: false, errorCode: 'TASK_MODEL_UNAVAILABLE', message: '无法确认任务模型或参数,请重新查询可用模型并检查伙伴模型设置后重试' };}const taskRuntime = taskModel ? {@@ -2356,6 +2436,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {effort: taskModel.effort as typeof callerRuntime.effort,fastMode: taskModel.fastMode,} : callerRuntime;+ await caller.groupAuthority?.refresh();let workingDir = input.workingDir?.trim() || '';if (workingDir) {const isDirectory = (() => {@@ -2377,7 +2458,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {ownerScopedUserDataPath(),caller.botId,app.getPath('userData'),- );+ ).finally(() => caller.groupAuthority?.refresh());}const plan: Omit<BotDelegationPlanSnapshot, 'permission'> = {version: 1,@@ -2416,6 +2497,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {childSessionId: started.childSessionId,status: started.status,deadlineAt: started.deadlineAt,+ ...(caller.role === 'group' ? { completionDestination: 'teammate-private-chat' as const } : {}),modelRoute: {harness: taskRuntime.agentKind === 'codex' ? 'codex' : taskRuntime.agentKind === 'pi' ? 'pi' : 'claude',model: taskRuntime.model,@@ -2598,11 +2680,16 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const cancelDelegation = async (callerSessionId: string,delegationId: string,+ inheritedAuthority?: Awaited<ReturnType<typeof authorizeGroupTool>> | 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: '当前任务不属于任何伙伴' };}+ if (inheritedAuthority) {+ await inheritedAuthority.refresh();+ caller.groupAuthority = inheritedAuthority;+ }const db = getDbClient().drizzle;const [row] = await db.select()@@ -2610,10 +2697,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.where(and(eq(botDelegations.id, delegationId),- eq(botDelegations.requestingBotId, caller.botId),+ callerTaskScope(caller),),).limit(1);+ await caller.groupAuthority?.refresh();if (!row) return { ok: false, errorCode: 'NOT_FOUND', message: '后台任务不存在' };if (!ACTIVE_DELEGATION_STATUSES.includes(row.status as (typeof ACTIVE_DELEGATION_STATUSES)[number])) {return {@@ -2624,22 +2712,44 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}if (!matchesDelegatedExecution(row)) return finishCancelledDelegation(row);if (row.childSessionId) {+ const wasHeld = !!readTaskPause(row) || heldSessionIds.has(row.childSessionId);+ const snapshot = JSON.stringify({ ...parseRecord(row.permissionSnapshotJson), taskCancelRequested: true });+ let admitted = false;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));+ await db.update(botDelegations).set({ permissionSnapshotJson: snapshot })+ .where(eq(botDelegations.id, row.id));holdTaskInput(row.childSessionId, true);- clearTimer(row.id);- clearRetryTimer(row.id);- await deps.taskControl.waitForInputBoundary(row.childSessionId);+ if (!caller.groupAuthority) {+ clearTimer(row.id);+ clearRetryTimer(row.id);+ }}try {+ await deps.taskControl?.waitForInputBoundary(row.childSessionId);// A successful stop response means the active process has actually// accepted cancellation, not merely that the card changed color.- await controlDelegatedExecution(row, () => deps.abortSession(row.childSessionId!));+ await controlDelegatedExecution(row, async () => {+ await caller.groupAuthority?.refresh();+ admitted = true;+ clearTimer(row.id);+ clearRetryTimer(row.id);+ await deps.abortSession(row.childSessionId!);+ });} catch (error) {+ if (error instanceof GroupToolAuthorizationError) {+ if (!admitted && deps.taskControl) {+ // Rejected group control must not leave an independently running+ // task cancelling. Undo only our intent, never a newer task state.+ const [restored] = await db.update(botDelegations).set({ permissionSnapshotJson: row.permissionSnapshotJson })+ .where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence),+ eq(botDelegations.status, row.status), eq(botDelegations.permissionSnapshotJson, snapshot)))+ .returning({ id: botDelegations.id });+ if (restored) holdTaskInput(row.childSessionId, wasHeld);+ }+ throw error;+ }log.warn('Session task stop was not accepted by the child runtime', {delegationId,childSessionId: row.childSessionId,@@ -2680,6 +2790,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {delegationId: string,text: string,idempotencyToken?: string,+ inheritedAuthority?: Awaited<ReturnType<typeof authorizeGroupTool>> | null,): Promise<BotDelegationInterjectResult & { queuedMessageId?: string }> => {const trimmed = text.trim();if (!trimmed) {@@ -2696,6 +2807,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (!caller) {return { ok: false, errorCode: 'NOT_A_BOT_SESSION', message: '当前任务不属于任何伙伴' };}+ if (inheritedAuthority) {+ await inheritedAuthority.refresh();+ caller.groupAuthority = inheritedAuthority;+ }const db = getDbClient().drizzle;const [row] = await db.select()@@ -2703,10 +2818,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.where(and(eq(botDelegations.id, delegationId),- eq(botDelegations.requestingBotId, caller.botId),+ callerTaskScope(caller),),).limit(1);+ await caller.groupAuthority?.refresh();if (!row) return { ok: false, errorCode: 'NOT_FOUND', message: '后台任务不存在' };if (!isActiveDelegation(row.status as DelegationStatus)) {return {@@ -2739,7 +2855,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {message: trimmed,persistedContent: trimmed,clientId: BOT_DELEGATION_CLIENT_ID.interjection(delegationId, row.runSequence > 1 ? `${row.runSequence}:${token}` : token),- });+ }, false, caller.groupAuthority);const dispatched = recovered.result;if (!dispatched?.ok) {return {@@ -2789,6 +2905,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {callerBotId: string,row: DelegationRow,text: string,+ groupAuthority?: Awaited<ReturnType<typeof authorizeGroupTool>> | null,): Promise<BotDelegationResult<{delegationId: string;childSessionId: string;@@ -2838,6 +2955,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.from(sessions).where(eq(sessions.id, row.childSessionId)).limit(1);+ await groupAuthority?.refresh();if (!oldChild|| !oldChild.workingDir@@ -2855,7 +2973,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {message: oldChild.status === 'deleted' ? 'The Session was deleted and cannot be continued.' : 'Restore the existing Session before continuing this task.' };}- await deps.reconcileWorktree?.(row.childSessionId);+ await reconcileTaskWorktree(row.childSessionId, groupAuthority);const worktreePath = deps.getWorktree?.(row.childSessionId)?.path ?? oldChild.worktreePath;const reopenedAt = now();const deadlineAt = reopenedAt + Math.min(MAX_TIMEOUT_MS, oldPlan.limits.timeoutMs);@@ -2884,6 +3002,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {// Preserve unrecoverable legacy data, but never send its wrappers as a new goal.const continuationObjective = originalObjective ?? row.objective;const nextState: Record<string, unknown> = { ...nextPlan, taskInput, taskAcceptedInputIds: [] };+ const previousState = JSON.parse(row.permissionSnapshotJson) as Record<string, unknown>;+ if (typeof previousState.groupOriginRoute === 'string') nextState.groupOriginRoute = previousState.groupOriginRoute;+ if (typeof previousState.groupOriginSessionId === 'string') nextState.groupOriginSessionId = previousState.groupOriginSessionId;// Explicit new work may reopen a confirmed terminal run. Its old pause and// cancel intents must not hold the new input; run-scoped receipts stay intact.delete nextState.taskCancelRequested;@@ -2926,6 +3047,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {reopenedAt,worktreePath,});+ await groupAuthority?.refresh();const reopened = await commitReopen();if (!reopened.reopened) {await deliverCompletion({@@ -2942,6 +3064,15 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {message: '后台任务状态刚刚发生变化,请重新查看后再继续',};}+ // Reopening commits a new independent run. Validate that admission once+ // after the transaction, then let durable retries outlive the group turn.+ const groupPermissionCurrent = await groupAuthority?.refresh().then(() => true, () => false) ?? true;+ if (!groupPermissionCurrent) {+ await updateTerminal({ delegationId: row.id, status: 'failed',+ lastError: 'CALLER_PERMISSION_UNAVAILABLE', expectedRunSequence: row.runSequence + 1 });+ return { ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE',+ message: '伙伴权限正在切换或任务正在关闭,请稍后重试' };+ }clearCleanupRetryTimer(row.id);emitChanged({delegationId: row.id,@@ -2999,6 +3130,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {callerSessionId: string,delegationId: string,input: SessionTaskMessage,+ inheritedAuthority?: Awaited<ReturnType<typeof authorizeGroupTool>> | null,): Promise<BotDelegationResult<{delegationId: string;childSessionId: string | null;@@ -3010,6 +3142,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (!caller) {return { ok: false, errorCode: 'NOT_A_BOT_SESSION', message: '当前任务不属于任何伙伴' };}+ if (inheritedAuthority) {+ await inheritedAuthority.refresh();+ caller.groupAuthority = inheritedAuthority;+ }const db = getDbClient().drizzle;const [row] = await db.select()@@ -3017,10 +3153,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.where(and(eq(botDelegations.id, delegationId),- eq(botDelegations.requestingBotId, caller.botId),+ callerTaskScope(caller),),).limit(1);+ await caller.groupAuthority?.refresh();if (!row) return { ok: false, errorCode: 'NOT_FOUND', message: '后台任务不存在' };if (input.kind === 'resume') return { ok: false, errorCode: 'NOT_PAUSED', message: 'Task is not paused' };@@ -3049,6 +3186,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {message: `当前后台任务在等待 ${pending.request.kind},回复类型 ${input.kind} 不匹配`,};}+ await caller.groupAuthority?.refresh();if (!deps.resolveInteraction?.(pending.requestId, decision)) {await handleInteractionEndUnserialized(row.childSessionId ?? '', pending.request);return {@@ -3082,13 +3220,17 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}if (!isActiveDelegation(row.status as DelegationStatus)) {- return reopenTerminalDelegation(callerSessionId, caller.botId, row, input.text);+ const returnSessionId = caller.role === 'group' ? await requesterLiveSessionId(caller.botId, null) : callerSessionId;+ await caller.groupAuthority?.refresh();+ if (!returnSessionId) throw new GroupToolAuthorizationError();+ return reopenTerminalDelegation(returnSessionId, caller.botId, row, input.text, caller.groupAuthority);}const result = await interjectDelegation(callerSessionId,delegationId,input.text,input.idempotencyKey,+ caller.groupAuthority,);if (!result.ok) return result;return {@@ -3116,13 +3258,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.where(and(eq(botDelegations.id, taskId),- eq(botDelegations.requestingBotId, caller.botId),+ callerTaskScope(caller),isNull(botDelegations.targetBotId),),).limit(1);+ await caller.groupAuthority?.refresh();return row- ? { ok: true as const, row }+ ? { ok: true as const, row, groupAuthority: caller.groupAuthority }: { ok: false as const, errorCode: 'NOT_FOUND', message: '后台任务不存在' };};@@ -3132,6 +3275,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {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 found.groupAuthority?.refresh();await cancelDelegationTree(row, 'Cancelled by the requesting Bot.', true, true);const refreshed = await findOwnedSessionTask(callerSessionId, taskId);if (!refreshed.ok) return refreshed;@@ -3170,6 +3314,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}messageReceipt = { queued_message_id: queuedMessageId, state };}+ await found.groupAuthority?.refresh();return {ok: true as const,task: {@@ -3208,6 +3353,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}const [child] = await getDbClient().drizzle.select({ status: sessions.status }).from(sessions).where(eq(sessions.id, found.row.childSessionId)).limit(1);+ await found.groupAuthority?.refresh();if (child?.status !== 'active') {return { ok: false as const, errorCode: 'CHILD_SESSION_INVALID', message: 'Task Session is no longer active' };}@@ -3215,6 +3361,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {return { ok: false as const, errorCode: 'TASK_ACTIVE', message: 'Finish or stop the current execution before changing its model' };}const inspected = await deps.taskRoute.inspect(callerSessionId, found.row.childSessionId);+ await found.groupAuthority?.refresh();// An explicit task model has no backup chain. Freeze this at creation so a later// profile edit cannot offer the primary chain to an already-created task.if (inspected.ok && parseRecord(found.row.permissionSnapshotJson).taskModelOverride) {@@ -3235,6 +3382,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}const [child] = await getDbClient().drizzle.select({ status: sessions.status }).from(sessions).where(eq(sessions.id, row.childSessionId)).limit(1);+ await found.groupAuthority?.refresh();if (child?.status !== 'active') {return { ok: false as const, errorCode: 'CHILD_SESSION_INVALID', message: 'Task Session is no longer active' };}@@ -3242,6 +3390,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {return { ok: false as const, errorCode: 'TASK_ACTIVE', message: 'Finish or stop the current execution before changing its model' };}const inspected = await deps.taskRoute.inspect(callerSessionId, row.childSessionId);+ await found.groupAuthority?.refresh();if (!inspected.ok) return inspected;if (inspected.generation !== expectedGeneration) {return { ok: false as const, errorCode: 'CONFLICT', message: 'Task model changed; inspect it again before retrying' };@@ -3257,7 +3406,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {if (deps.taskControl?.isActive(row.childSessionId)) {return { ok: false as const, errorCode: 'TASK_ACTIVE', message: 'Task execution restarted before its model could change' };}- return deps.taskRoute.advance(row.childSessionId, expectedGeneration, inspected.next);+ await found.groupAuthority?.refresh();+ return found.groupAuthority+ ? deps.taskRoute.advance(row.childSessionId, expectedGeneration, inspected.next, found.groupAuthority.refresh)+ : deps.taskRoute.advance(row.childSessionId, expectedGeneration, inspected.next);});const taskControlView = (row: DelegationRow) => {@@ -3290,7 +3442,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};/** Release only a committed resume; repeat receipts never enqueue a second turn. */- const finishTaskResume = async (row: DelegationRow) => {+ const finishTaskResume = async (row: DelegationRow, groupAuthority?: Awaited<ReturnType<typeof authorizeGroupTool>> | null) => {+ await groupAuthority?.refresh();if (!row.childSessionId || !deps.taskControl) throw new Error('Missing task input control');let status = row.status as DelegationStatus;const control = deps.taskControl;@@ -3305,6 +3458,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {status = 'running';}const awaitingInteraction = pending && !pending.decisionApplied ? pending : null;+ try { await groupAuthority?.refresh(); } catch (error) {+ holdTaskInput(row.childSessionId, true);+ throw error;+ }await control.resumeInput(row.childSessionId);if (awaitingInteraction) await notifyRequesterOfInteraction(row, awaitingInteraction);else {@@ -3319,7 +3476,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {control: { state: 'active', queue_held: false } };};- const resumeTask = async (row: DelegationRow, text?: string) => {+ const resumeTask = async (row: DelegationRow, text?: string, groupAuthority?: Awaited<ReturnType<typeof authorizeGroupTool>> | null) => {+ await groupAuthority?.refresh();const pause = readTaskPause(row);const control = deps.taskControl;const receipt = parseRecord(row.permissionSnapshotJson).taskResume as { token?: string; text?: string } | undefined;@@ -3331,7 +3489,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {// 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 finishTaskResume(row, groupAuthority);}return { ok: true as const, childSessionId: row.childSessionId, resumed: true,delivery: 'accepted', control: taskControlView(row) };@@ -3347,18 +3505,22 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {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);+ const validation = await validateDispatchPlan(row, groupAuthority);if (!validation.ok) return validation;// Reassert the durable hold before restore/dispatch, including a cold caller.+ await groupAuthority?.refresh();holdTaskInput(row.childSessionId, true);await control.restoreInput(row.childSessionId);+ await groupAuthority?.refresh();const resumedAt = now();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);+ const dispatched = await attemptDispatch(row.id, 0, groupAuthority ? () => {+ try { groupAuthority.assertCurrent(); return true; } catch { return false; }+ } : undefined, true);if (!dispatched.ok) throw new Error('Initial task dispatch has not been accepted');status = dispatched.status === 'running' ? 'running' : 'queued';const [acceptedRow] = await getDbClient().drizzle.select().from(botDelegations)@@ -3370,12 +3532,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const recovered = await dispatchTrackedInput(row, {message: text?.trim() || 'Continue from the existing task history after the requested pause. Check what has already completed; do not replay the original request or repeat completed actions.',clientId: `bot-delegation-unpause:${row.id}:${pause.token}`,- });+ }, false, groupAuthority);if (!recovered.result.ok) throw new Error(recovered.result.message);row = recovered.row;}+ await groupAuthority?.refresh();await control.flushInput(row.childSessionId!);} catch (error) {+ if (error instanceof GroupToolAuthorizationError) throw 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) };}@@ -3387,6 +3551,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {snapshot.taskResume = { token: pause.token, text: text?.trim() ?? '' };// Keep the input barrier until the durable transition and continuation enqueue are complete.try {+ await groupAuthority?.refresh();const [resumed] = await getDbClient().drizzle.update(botDelegations).set({ status,permissionSnapshotJson: JSON.stringify(snapshot),pendingInteractionJson: pending ? JSON.stringify(pendingInteractionView({ ...pending, raisedAt: resumedAt })) : null,@@ -3396,6 +3561,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {.returning({ id: botDelegations.id });if (!resumed) throw new Error('Task changed before resume committed');} catch (error) {+ if (error instanceof GroupToolAuthorizationError) throw 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.@@ -3411,7 +3577,33 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}status = current.status as DelegationStatus;}- return finishTaskResume({ ...row, status, updatedAt: resumedAt, permissionSnapshotJson: JSON.stringify(snapshot) });+ const previousRaisedAt = pending?.raisedAt;+ try {+ return await finishTaskResume({ ...row, status, updatedAt: resumedAt, permissionSnapshotJson: JSON.stringify(snapshot) }, groupAuthority);+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) {+ // The resume write can finish after revocation. Keep accepted input+ // receipts for retry, but restore the pause if this exact transition+ // still owns the row; never overwrite a newer run or terminal result.+ const [restored] = await getDbClient().drizzle.update(botDelegations).set({+ status: row.status, permissionSnapshotJson: row.permissionSnapshotJson,+ pendingInteractionJson: row.pendingInteractionJson, updatedAt: row.updatedAt,+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence),+ eq(botDelegations.status, status), eq(botDelegations.updatedAt, resumedAt),+ eq(botDelegations.permissionSnapshotJson, JSON.stringify(snapshot))))+ .returning({ id: botDelegations.id });+ if (restored) {+ holdTaskInput(row.childSessionId!, true);+ if (pending && previousRaisedAt !== undefined) pending.raisedAt = previousRaisedAt;+ clearTimer(row.id);+ clearRetryTimer(row.id);+ clearInteractionRetryTimer(row.id);+ emitChanged({ delegationId: row.id, parentSessionId: row.parentSessionId,+ childSessionId: row.childSessionId, status: row.status as DelegationStatus });+ }+ }+ throw error;+ }};const messageSessionTask = (callerSessionId: string, taskId: string, input: SessionTaskMessage) =>@@ -3425,7 +3617,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {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 params = { callerSessionId, targetSessionId: row.childSessionId, queuedMessageId: input.queuedMessageId,+ beforeMutation: found.groupAuthority?.refresh };+ await found.groupAuthority?.refresh();const result = input.kind === 'edit'? await deps.taskQueue.update({ ...params, message: input.text }): await deps.taskQueue.cancel(params);@@ -3433,9 +3627,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {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);+ try { if (row.childSessionId) await reconcileTaskWorktree(row.childSessionId, found.groupAuthority); }+ catch (error) { if (error instanceof GroupToolAuthorizationError) throw error; return { ok: false as const, errorCode: 'WORKTREE_TRANSFER_PENDING', message: 'Task worktree ownership is awaiting reconciliation' }; }+ await found.groupAuthority?.refresh();+ if (input.kind === 'resume') return resumeTask(row, input.text, found.groupAuthority);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' };}@@ -3450,6 +3645,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {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);+ await found.groupAuthority?.refresh();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,@@ -3458,12 +3654,13 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}// The coordinator deduplicates in-flight and accepted IDs even when// persistence failed after native acceptance. Persisted rows cover restore.+ await found.groupAuthority?.refresh();const result = await deps.taskControl.steer({ callerSessionId,- targetSessionId: row.childSessionId, message: input.text, queuedMessageId });+ targetSessionId: row.childSessionId, message: input.text, queuedMessageId, beforeMutation: found.groupAuthority?.refresh });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);+ const result = await reply(callerSessionId, taskId, input, found.groupAuthority);return result.ok ? { ...result,delivery: input.kind !== 'message' ? 'interaction' : result.queued ? 'queued' : 'accepted' } : result;});@@ -3472,7 +3669,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {mode: 'cancel' | 'request-stop' | 'pause' = 'cancel') => withTaskOperation(taskId, async () => {const found = await findOwnedSessionTask(callerSessionId, taskId);if (!found.ok) return found;- if (mode === 'cancel') return cancelDelegation(callerSessionId, taskId);+ await found.groupAuthority?.refresh();+ if (mode === 'cancel') return cancelDelegation(callerSessionId, taskId, found.groupAuthority);const row = found.row;const control = deps.taskControl;if (!control || !row.childSessionId) return { ok: false as const,@@ -3485,7 +3683,11 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {control: taskControlView(row) };if (mode === 'request-stop') {let result: Awaited<ReturnType<typeof control.stop>> = { ok: true, status: 'no-active-turn' };- const applied = await controlDelegatedExecution(row, async () => { result = await control.stop({ targetSessionId: row.childSessionId! }); }, true);+ const applied = await controlDelegatedExecution(row, async () => {+ await found.groupAuthority?.refresh();+ result = await control.stop({ targetSessionId: row.childSessionId!,+ ...(found.groupAuthority ? { beforeMutation: found.groupAuthority.refresh } : {}) });+ }, true);if (!applied) return finishCancelledDelegation(row);if (result.ok) {await getDbClient().drizzle.update(botDelegations).set({@@ -3503,11 +3705,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {pausedAt: pending?.raisedAt ?? now(), previousStatus: row.status as SessionTaskPause['previousStatus'],interactionOnly: !!pending };const wasHeld = !!existingPause || heldSessionIds.has(row.childSessionId);+ await found.groupAuthority?.refresh();holdTaskInput(row.childSessionId, true);const snapshot = JSON.stringify({ ...parseRecord(row.permissionSnapshotJson), taskPause: pause });let persisted = false;+ let admitted = false;+ const db = getDbClient().drizzle;try {- const [paused] = await getDbClient().drizzle.update(botDelegations).set({ permissionSnapshotJson: snapshot,+ const [paused] = await db.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])))@@ -3522,9 +3727,21 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {// reservation fence. A new direct turn must never inherit this pause.let result: Awaited<ReturnType<typeof control.stop>> = { ok: true, status: 'no-active-turn' };const applied = await controlDelegatedExecution(row, async () => {- result = (pending && pause.interactionOnly) || !control.isActive(row.childSessionId!)- ? { ok: true, status: 'no-active-turn' }- : await control.stop({ targetSessionId: row.childSessionId! });+ await found.groupAuthority?.refresh();+ const beforeStop = async () => {+ await found.groupAuthority?.refresh();+ admitted = true;+ };+ if ((pending && pause.interactionOnly) || !control.isActive(row.childSessionId!)) {+ admitted = true;+ result = { ok: true, status: 'no-active-turn' };+ } else {+ // Keep rollback armed until Session control finishes its async target+ // lookup and admits the native stop under the current group grant.+ result = await control.stop({ targetSessionId: row.childSessionId!,+ ...(found.groupAuthority ? { beforeMutation: beforeStop } : {}) });+ admitted = true;+ }if (result.ok) {await control.preparePause(row.childSessionId!);await control.flushInput(row.childSessionId!);@@ -3548,6 +3765,20 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {return { ok: true as const, childSessionId: row.childSessionId,control: { ...taskControlView({ ...row, permissionSnapshotJson: snapshot }), stop_status: result.status } };} catch (error) {+ if (error instanceof GroupToolAuthorizationError) {+ if (!persisted) holdTaskInput(row.childSessionId, wasHeld);+ else if (!admitted) {+ // No native stop was admitted. Restore the previous pause/hold rather+ // than retaining a new pause created by an expired group execution.+ const [restored] = await db.update(botDelegations).set({ permissionSnapshotJson: row.permissionSnapshotJson,+ status: row.status, updatedAt: row.updatedAt,+ }).where(and(eq(botDelegations.id, row.id), eq(botDelegations.runSequence, row.runSequence),+ eq(botDelegations.status, row.status === 'queued' ? 'queued' : 'waiting'),+ eq(botDelegations.permissionSnapshotJson, snapshot))).returning({ id: botDelegations.id });+ if (restored) holdTaskInput(row.childSessionId, wasHeld);+ }+ throw 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.@@ -3972,27 +4203,23 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {resumeRetryTimers.clear();};+ const expose = <A extends unknown[], R>(operation: (...args: A) => Promise<R>) => async (...args: A) => {+ try { return await operation(...args); } catch (error) {+ if (error instanceof GroupToolAuthorizationError) return { ok: false as const, errorCode: error.code, message: error.message };+ throw error;+ }+ };return {- startSessionTask,- ensureCanonicalSession: async (botId: string) => {- const [profile] = await getDbClient().drizzle- .select({ id: botProfiles.id, currentVersion: botProfiles.currentVersion, status: botProfiles.status })- .from(botProfiles)- .where(eq(botProfiles.id, botId))- .limit(1);- if (!profile || profile.status !== 'active') {- return { ok: false as const, errorCode: 'TARGET_BOT_INACTIVE', message: '目标伙伴已暂停或归档' };- }- return ensureTargetCanonicalSession({ id: profile.id, currentVersion: profile.currentVersion });- },+ startSessionTask: expose(startSessionTask),+ ensureCanonicalSession,listDelegations,- getSessionTask,- inspectSessionTaskRoute,- advanceSessionTaskRoute,+ getSessionTask: expose(getSessionTask),+ inspectSessionTaskRoute: expose(inspectSessionTaskRoute),+ advanceSessionTaskRoute: expose(advanceSessionTaskRoute),restorePauseForSession,- messageSessionTask,- stopSessionTask,- cancelDelegation: (callerSessionId: string, delegationId: string) => withTaskOperation(delegationId, () => cancelDelegation(callerSessionId, delegationId)),+ messageSessionTask: expose(messageSessionTask),+ stopSessionTask: expose(stopSessionTask),+ cancelDelegation: expose((callerSessionId: string, delegationId: string) => withTaskOperation(delegationId, () => cancelDelegation(callerSessionId, delegationId))),cancelDelegationsForParentSession,cancelDelegationsForBot,settleSession,diff --git a/apps/desktop/src/main/maker-ipc/botDirectMessageService.ts b/apps/desktop/src/main/maker-ipc/botDirectMessageService.tsindex 409ebdfdac..fcf9f9d53a 100644--- a/apps/desktop/src/main/maker-ipc/botDirectMessageService.ts+++ b/apps/desktop/src/main/maker-ipc/botDirectMessageService.ts@@ -1,8 +1,11 @@import { parseBotPeerAddress, botPeerAddress, MAX_BOT_PEER_ADDRESS_CHARS } from '../../shared/botPeerAddress.js';import { createHash, randomUUID } from 'node:crypto';import { withBotProfileLocks } from './botProfileLock.js';+import { authorizeGroupTool, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';+import { t } from '../i18n.js';+import { AcceptedCallbackDispatchCancelled } from './acceptedCallbackRunner.js';-import { and, asc, desc, eq, inArray, isNull, ne } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, isNull, ne, sql } from 'drizzle-orm';import { getDbClient } from '../localDb/client/current.js';import { createMessage } from '../localDb/ipc/messages.js';@@ -101,6 +104,7 @@ export interface BotDirectMessageServiceDeps {transport?: BotMessageTransport;dispatch: (params: {targetSessionId: string;+ dispatcherSessionId?: string;message: string;persistedContent?: string;clientId?: string;@@ -110,9 +114,11 @@ export interface BotDirectMessageServiceDeps {/** Reuses the canonical-session ensure path for newly-created/recovering Bots. */ensureCanonicalSession?: (botId: string,+ beforeRecovery?: () => Promise<void>,) => Promise<{ ok: true; sessionId: string } | { ok: false; errorCode: string; message: string }>;/** True only when the durable input queue already owns this delivery. */hasQueuedDelivery?: (sessionId: string, clientId: string) => Promise<boolean>;+ discardQueuedDelivery?: (sessionId: string, clientId: string, assertOwner: () => void) => Promise<void>;captureOwnerScope?: () => DataOwnerBroadcastScope;isOwnerScopeCurrent?: (scope: DataOwnerBroadcastScope) => boolean;onChanged?: (payload: BotDirectMessageChangedPayload, ownerScope?: DataOwnerBroadcastScope) => void;@@ -120,25 +126,28 @@ export interface BotDirectMessageServiceDeps {createId?: () => string;}-async function activeRoster(): Promise<BotRosterEntry[]> {+async function activeRoster(beforeReturn?: () => Promise<void>): Promise<BotRosterEntry[]> {const db = getDbClient().drizzle;- return db+ const roster = await db.select({ id: botProfiles.id, name: botProfiles.displayName }).from(botProfiles).where(eq(botProfiles.status, 'active')).orderBy(desc(botProfiles.updatedAt));+ await beforeReturn?.();+ return roster;}async function failed(errorCode: string,message: string,includeRoster = false,+ beforeRosterReturn?: () => Promise<void>,): Promise<BotDirectMessageResult> {return {ok: false,errorCode,message,- ...(includeRoster ? { availableBots: await activeRoster() } : {}),+ ...(includeRoster ? { availableBots: await activeRoster(beforeRosterReturn) } : {}),};}@@ -295,6 +304,29 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)if (rejected?.status === 'rejected') throw rejected.reason;};+ // senderSessionId and the durable Bot link retain the source identity across+ // restarts. A missing local link cannot prove canonical authority either.+ const canRestoreDelivery = async (db: ReturnType<typeof getDbClient>['drizzle'], row: typeof botDirectMessages.$inferSelect): Promise<boolean> => {+ if (row.deliveryStatus === 'failed') return false;+ if (!row.senderSessionId) return !!parseBotPeerAddress(row.senderBotId); // Remote peer, not a deleted local source.+ const [link] = await db.select({ role: botSessionLinks.role }).from(botSessionLinks)+ .where(and(eq(botSessionLinks.sessionId, row.senderSessionId), eq(botSessionLinks.botId, row.senderBotId))).limit(1);+ return link?.role === 'canonical';+ };++ const assertRestoredQueuedDelivery = async (sessionId: string, clientId: string): Promise<void> => {+ if (!clientId.startsWith('bot-dm:')) return;+ const owner = deps.captureOwnerScope?.();+ const db = getDbClient().drizzle;+ const [row] = await db.select().from(botDirectMessages)+ .where(and(eq(botDirectMessages.recipientSessionId, sessionId),+ eq(sql`'bot-dm:' || ${botDirectMessages.threadId} || ':' || ${botDirectMessages.id}`, clientId))).limit(1);+ const restorable = row && await canRestoreDelivery(db, row);+ if (!restorable || (owner !== undefined && deps.isOwnerScopeCurrent && !deps.isOwnerScopeCurrent(owner))) {+ throw new AcceptedCallbackDispatchCancelled(new GroupToolAuthorizationError().message);+ }+ };+/** Reconcile receipts after restart without replaying uncertain model/tool work. */const restore = async (): Promise<void> => {const owner = deps.captureOwnerScope?.();@@ -319,10 +351,15 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)// it based on the absence of a receipt in this device's local database.if (parseBotPeerAddress(row.recipientBotId)) return;const clientId = `bot-dm:${row.threadId}:${row.id}`;- const [receipt] = row.recipientSessionId ? await db.select({ id: messages.id }).from(messages)+ const restorable = await canRestoreDelivery(db, row);+ if (!restorable && row.recipientSessionId) {+ assertOwner();+ await deps.discardQueuedDelivery?.(row.recipientSessionId, clientId, assertOwner);+ }+ const [receipt] = restorable && row.recipientSessionId ? await db.select({ id: messages.id }).from(messages).where(and(eq(messages.sessionId, row.recipientSessionId), eq(messages.clientId, clientId), isNull(messages.rewindAt))).limit(1) : [];- const queued = !receipt && row.recipientSessionId && deps.hasQueuedDelivery+ const queued = restorable && !receipt && row.recipientSessionId && deps.hasQueuedDelivery? await deps.hasQueuedDelivery(row.recipientSessionId, clientId) : false;assertOwner();if (receipt || queued) {@@ -337,7 +374,8 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)// row, remove partial projections, and return its budget to the pair.await db.delete(messages).where(inArray(messages.clientId,[row.senderSessionId, row.recipientSessionId].filter((id): id is string => !!id)- .map((id) => BOT_DIRECT_MESSAGE_CLIENT_ID.timelineAnchor(row.threadId, row.id, id))));+ .map((id) => BOT_DIRECT_MESSAGE_CLIENT_ID.timelineAnchor(row.threadId, row.id, id))+ .concat(restorable ? [] : [clientId])));}const [thread] = await db.select().from(botDirectMessageThreads).where(eq(botDirectMessageThreads.id, row.threadId)).limit(1);@@ -441,7 +479,9 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)if (caller.sessionStatus !== 'active' || caller.botStatus !== 'active') {return failed('BOT_SESSION_INACTIVE', '当前 Bot 主任务已暂停、归档或删除');}- if (caller.role !== 'canonical' || caller.linkArchivedAt !== null) {+ const groupAuthority = caller.role === 'group'+ ? await authorizeGroupTool(input.callerSessionId, caller.botId, 'owner-action') : null;+ if ((!groupAuthority && caller.role !== 'canonical') || caller.linkArchivedAt !== null) {return failed('NOT_CANONICAL_BOT_SESSION', 'send_to_agent 只能从伙伴主任务发送');}if (caller.botId === input.targetBotId) {@@ -449,6 +489,7 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)}const remoteTarget = parseBotPeerAddress(input.targetBotId);+ if (groupAuthority && remoteTarget) return failed('PERMISSION_DENIED', t('groupTools.localPeersOnly'));if (remoteTarget && remoteSender) return failed('INVALID_ARGS', 'Remote forwarding is not supported');let targetProfile: { name: string; status: string; hiddenAt?: number | null } | undefined;let bridgeSessionId: string | undefined;@@ -464,28 +505,30 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)} else targetProfile = await loadTargetProfile(input.targetBotId);if (!ownerIsCurrent()) return failed('OWNER_CHANGED', '账号已经切换,本次伙伴消息未发送');if (!targetProfile) {- return failed('TARGET_BOT_NOT_FOUND', '找不到目标 Bot', true);+ return failed('TARGET_BOT_NOT_FOUND', '找不到目标 Bot', true, groupAuthority?.refresh);}if (remoteSender && targetProfile.hiddenAt) return failed('NOT_FOUND', 'Remote teammate is unavailable');if (targetProfile.status !== 'active') {- return failed('TARGET_BOT_INACTIVE', '目标 Bot 已暂停或归档', true);+ return failed('TARGET_BOT_INACTIVE', '目标 Bot 已暂停或归档', true, groupAuthority?.refresh);}// Resolve on every use so a missing/deleted canonical task can be repaired// before the message is persisted or queued against a Session id.let targetSessionId: string | null = null;if (!remoteTarget && deps.ensureCanonicalSession) {- const ensured = await deps.ensureCanonicalSession(input.targetBotId);+ const ensured = groupAuthority+ ? await deps.ensureCanonicalSession(input.targetBotId, groupAuthority.refresh).finally(groupAuthority.refresh)+ : await deps.ensureCanonicalSession(input.targetBotId);if (!ownerIsCurrent()) return failed('OWNER_CHANGED', '账号已经切换,本次伙伴消息未发送');if (ensured.ok) targetSessionId = ensured.sessionId;- else return failed(ensured.errorCode, ensured.message, true);+ else return failed(ensured.errorCode, ensured.message, true, groupAuthority?.refresh);}if (!remoteTarget && !targetSessionId) {const target = await loadTargetCanonicalSession(input.targetBotId);targetSessionId = target?.sessionId ?? null;}if (!remoteTarget && !targetSessionId) {- return failed('TARGET_CANONICAL_UNAVAILABLE', '目标 Bot 没有可用的主任务', true);+ return failed('TARGET_CANONICAL_UNAVAILABLE', '目标 Bot 没有可用的主任务', true, groupAuthority?.refresh);}const [botAId, botBId] = pairOf(caller.botId, input.targetBotId);@@ -495,14 +538,16 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)// Admission above may precede a queued delete/pause. Re-read after obtaining// both lifecycle locks, before creating any shared thread or message row.const currentCaller = remoteSender ? caller : await loadCaller(input.callerSessionId);+ await groupAuthority?.refresh();if (!currentCaller || currentCaller.botId !== caller.botId || currentCaller.sessionSource !== 'bot'|| currentCaller.sessionStatus !== 'active' || currentCaller.botStatus !== 'active'- || currentCaller.role !== 'canonical' || currentCaller.linkArchivedAt !== null) {+ || currentCaller.role !== caller.role || currentCaller.linkArchivedAt !== null) {return failed('BOT_SESSION_INACTIVE', '当前 Bot 主任务已暂停、归档或删除');}const currentTarget = remoteTarget ? targetProfile : await loadTargetProfile(input.targetBotId);+ await groupAuthority?.refresh();if (!currentTarget || currentTarget.status !== 'active' || (remoteSender && currentTarget.hiddenAt)) {- return failed('TARGET_BOT_INACTIVE', '目标 Bot 已暂停或归档', true);+ return failed('TARGET_BOT_INACTIVE', '目标 Bot 已暂停或归档', true, groupAuthority?.refresh);}if (!ownerIsCurrent()) return failed('OWNER_CHANGED', '账号已经切换,本次伙伴消息未发送');const db = getDbClient().drizzle;@@ -536,6 +581,7 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)),).limit(1);+ await groupAuthority?.refresh();let thread: typeof botDirectMessageThreads.$inferSelect | undefined = activeThreads[0];if (thread && thread.expiresAt <= sentAt) {@@ -563,6 +609,7 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)).orderBy(desc(botDirectMessageThreads.updatedAt)).limit(1);+ await groupAuthority?.refresh();if (latest?.closeReason === 'message-limit' &&latest.blockedUntil !== null &&@@ -594,6 +641,7 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps).where(eq(botDirectMessageThreads.id, threadId)).limit(1);}+ await groupAuthority?.refresh();if (!thread) return failed('INTERNAL', '伙伴对话未能建立');// A previous process may have stopped between reserving a delivery and@@ -606,6 +654,7 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)}).from(botDirectMessages).where(eq(botDirectMessages.threadId, thread.id));+ await groupAuthority?.refresh();const reservedCount = reservations.filter((row) => row.deliveryStatus !== 'failed').length;if (reservedCount !== thread.messageCount) {await db@@ -614,6 +663,7 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps).where(eq(botDirectMessageThreads.id, thread.id));thread = { ...thread, messageCount: reservedCount };}+ await groupAuthority?.refresh();if (thread.messageCount >= thread.maxMessages - (bridgeSessionId ? 1 : 0)) {return failed('CONVERSATION_LIMIT_REACHED', '这轮伙伴对话已达到往来上限,请先回到各自主任务整理结果。');}@@ -629,6 +679,7 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)).orderBy(desc(botDirectMessages.sequence)).limit(2);+ await groupAuthority?.refresh();if (recent.length === 2 && recent.every((row) => row.senderBotId === caller.botId)) {return failed('WAIT_FOR_PEER', '已连续发出 2 条消息,请等待对方回应后再继续。');}@@ -637,6 +688,10 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)const senderId = trustedHeaderLabel(caller.botId, MAX_SENDER_ID_CHARS);const envelope = [`[Direct message from Cindy Bot "${senderName}" (${senderId})]`,+ ...(groupAuthority ? [+ `[Group source: ${trustedHeaderLabel(groupAuthority.sourceGroup?.name ?? '', MAX_SENDER_NAME_CHARS)} (${trustedHeaderLabel(groupAuthority.sourceGroup?.groupId ?? '', MAX_SENDER_ID_CHARS)}); lane: ${trustedHeaderLabel(input.callerSessionId, MAX_SENDER_ID_CHARS)}]`,+ 'Replies go to the sender teammate\'s private chat with its owner. They are not delivered to the group lane. Retain this group source when replying.',+ ] : []),`Handle this in your current canonical task. If a useful answer, result, or clarification should go back, call send_to_agent with target_id="${senderId}". Do not send acknowledgement-only replies.`,message,].join('\n\n');@@ -663,6 +718,7 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)createdAt: sentAt,});try {+ await groupAuthority?.refresh();await db.update(botDirectMessageThreads).set({@@ -753,6 +809,7 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)};const onAccepted = async () => {+ await groupAuthority?.refresh();if (!ownerIsCurrent()) throw new Error('owner changed before Bot message acceptance');await persistDeliveryAnchors({id: deliveryId, threadId: thread.id, sequence: nextSequence,@@ -796,17 +853,20 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)try {dispatched = await deps.dispatch({targetSessionId: targetSessionId!, message: envelope,- persistedContent: `${UI_ACTION_TRIGGER_PREFIX}${envelope}`,+ ...(groupAuthority ? { dispatcherSessionId: input.callerSessionId } : {}),+ // Group routing details belong only to the agent wire. Shared+ // history and queue projections can expose the persisted body.+ persistedContent: `${UI_ACTION_TRIGGER_PREFIX}${groupAuthority ? message : envelope}`,clientId: `bot-dm:${thread.id}:${deliveryId}`,onAccepted, onAcceptedRollback: rollbackReservation,});} catch (error) {await rollbackReservation().catch(() => undefined);- return failed('DELIVERY_NOT_ACCEPTED', error instanceof Error ? error.message : String(error), true);+ return failed('DELIVERY_NOT_ACCEPTED', error instanceof Error ? error.message : String(error), true, groupAuthority?.refresh);}if (!dispatched.ok) {await rollbackReservation().catch(() => undefined);- return failed(dispatched.errorCode, dispatched.message, true);+ return failed(dispatched.errorCode, dispatched.message, true, groupAuthority?.refresh);}}@@ -827,11 +887,16 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)return typeof outcome === 'function' ? outcome() : outcome;};- const messageAgent = (input: { callerSessionId: string; targetBotId: string; message: string }) => {+ const messageAgent = async (input: { callerSessionId: string; targetBotId: string; message: string }) => {const peer = parseBotPeerAddress(input.targetBotId);// Addresses copied back onto their own device still resolve to the local profile.- return sendMessage(peer && peer.deviceId === deps.transport?.selfDeviceId()- ? { ...input, targetBotId: peer.botId } : input);+ try {+ return await sendMessage(peer && peer.deviceId === deps.transport?.selfDeviceId()+ ? { ...input, targetBotId: peer.botId } : input);+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) return failed(error.code, error.message);+ throw error;+ }};const receiveRemote = async (input: { controllerDeviceId: string; senderBotId: string; targetBotId: string; messageId: string; message: string }) => {if (!deps.transport) return failed('HOST_NOT_READY', 'Device messaging is not ready');@@ -857,11 +922,18 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)const listAgents = async (callerSessionId: string) => {const scope = deps.captureOwnerScope?.();const caller = await loadCaller(callerSessionId);- if (!caller || caller.role !== 'canonical' || caller.linkArchivedAt !== null+ const groupAuthority = caller?.role === 'group'+ ? await authorizeGroupTool(callerSessionId, caller.botId, 'owner-action') : null;+ if (!caller || (!groupAuthority && caller.role !== 'canonical') || caller.linkArchivedAt !== null|| caller.sessionSource !== 'bot' || caller.sessionStatus !== 'active' || caller.botStatus !== 'active') {return { ok: false as const, errorCode: 'NOT_A_BOT_SESSION', message: 'An active canonical teammate is required' };}- const local = (await activeRoster()).filter(row => row.id !== caller.botId);+ const local = (await activeRoster(groupAuthority?.refresh)).filter(row => row.id !== caller.botId);+ if (groupAuthority) {+ if (scope !== undefined && deps.isOwnerScopeCurrent && !deps.isOwnerScopeCurrent(scope))+ return { ok: false as const, errorCode: 'OWNER_CHANGED', message: t('groupTools.ownerChanged') };+ return { ok: true as const, agents: local.map(row => ({ ...row, local: true })), unavailableDevices: [] };+ }let remote: Awaited<ReturnType<BotMessageTransport['list']>> = { agents: [], unavailableDevices: [] };let discoveryError: string | undefined;try {@@ -1050,7 +1122,75 @@ export function createBotDirectMessageService(deps: BotDirectMessageServiceDeps)return transportFailure(error);}};- return { messageAgent, receiveRemote, verifyRemoteMessage, readRemoteReceipt, listAgents, checkMessage, getThread, restore };+ const sendToUser = async (input: { callerSessionId: string; message: string; idempotencyKey: string }) => {+ try {+ const scope = deps.captureOwnerScope?.();+ const caller = await loadCaller(input.callerSessionId);+ if (!caller || caller.role !== 'group' || caller.linkArchivedAt !== null+ || caller.sessionSource !== 'bot' || caller.sessionStatus !== 'active' || caller.botStatus !== 'active')+ return { ok: false as const, errorCode: 'GROUP_AUTHORIZATION_REQUIRED', message: t('groupTools.authorizationRequired') };+ const authority = await authorizeGroupTool(input.callerSessionId, caller.botId, 'owner-action');+ if (!authority.sourceGroup) throw new GroupToolAuthorizationError();+ const message = input.message.trim();+ if (!message || message.length > MAX_MESSAGE_CHARS || !/^[\w-]{8,100}$/.test(input.idempotencyKey))+ return { ok: false as const, errorCode: 'INVALID_ARGS', message: t('groupTools.invalidMessage') };+ if (scope !== undefined && deps.isOwnerScopeCurrent && !deps.isOwnerScopeCurrent(scope))+ return { ok: false as const, errorCode: 'OWNER_CHANGED', message: t('groupTools.ownerChanged') };+ // Use the same recovery as peer messages before taking the delivery lock.+ // Recovery may await profile/Session preparation, so it cannot authorize delivery.+ if (deps.ensureCanonicalSession) {+ await authority.refresh();+ const ensured = await deps.ensureCanonicalSession(caller.botId, authority.refresh).finally(() => authority.refresh());+ if (scope !== undefined && deps.isOwnerScopeCurrent && !deps.isOwnerScopeCurrent(scope))+ return { ok: false as const, errorCode: 'OWNER_CHANGED', message: t('groupTools.ownerChanged') };+ if (!ensured.ok) return { ...ensured, message: t('groupTools.privateUnavailable') };+ }+ return await withBotProfileLocks([caller.botId], async () => {+ const current = await loadCaller(input.callerSessionId);+ const target = await loadTargetCanonicalSession(caller.botId);+ const clientId = `bot-group-private:${input.callerSessionId}:${input.idempotencyKey}`;+ // Recovery replaces the canonical Session but preserves its historical+ // link. A lane's retry key still identifies the original delivery.+ const [existing] = target ? await getDbClient().drizzle.select({ id: messages.id, content: messages.content, sessionId: messages.sessionId })+ .from(messages)+ .innerJoin(botSessionLinks, eq(botSessionLinks.sessionId, messages.sessionId))+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(and(eq(botSessionLinks.botId, caller.botId), inArray(botSessionLinks.role, ['canonical', 'history']),+ eq(sessions.source, 'bot'), eq(messages.clientId, clientId))).limit(1) : [];+ await authority.refresh();+ if (scope !== undefined && deps.isOwnerScopeCurrent && !deps.isOwnerScopeCurrent(scope))+ return { ok: false as const, errorCode: 'OWNER_CHANGED', message: t('groupTools.ownerChanged') };+ if (!target || !current || current.botId !== caller.botId || current.role !== 'group'+ || current.linkArchivedAt !== null || current.botStatus !== 'active' || current.sessionStatus !== 'active')+ return { ok: false as const, errorCode: 'TARGET_CANONICAL_UNAVAILABLE', message: t('groupTools.privateUnavailable') };+ if (existing) return existing.content === message+ ? { ok: true as const, messageId: existing.id, targetSessionId: existing.sessionId, delivered: true }+ : { ok: false as const, errorCode: 'IDEMPOTENCY_CONFLICT', message: t('groupTools.idempotencyConflict') };+ // An assistant message for the owner, never synthetic user input to the Bot.+ // Host-derived target prevents another account or a namesake from receiving it.+ const saved = await createMessage(target.sessionId, {+ clientId, role: 'assistant', content: message, agentKind: null,+ agentMeta: { sourceGroup: authority.sourceGroup, origin: { kind: 'session', senderSessionId: input.callerSessionId,+ senderBotId: caller.botId, senderBotName: caller.botName } },+ }, { broadcastOwnerScope: scope, beforePublish: async () => {+ await authority.refresh();+ if (scope !== undefined && deps.isOwnerScopeCurrent && !deps.isOwnerScopeCurrent(scope))+ throw new GroupToolAuthorizationError();+ } });+ return { ok: true as const, messageId: saved.id, targetSessionId: target.sessionId, delivered: true };+ });+ } catch (error) {+ return { ok: false as const, errorCode: error instanceof GroupToolAuthorizationError ? error.code : 'PRIVATE_MESSAGE_UNAVAILABLE',+ message: error instanceof GroupToolAuthorizationError ? error.message : t('groupTools.privateUnconfirmed') };+ }+ };+ return { messageAgent, sendToUser, receiveRemote, verifyRemoteMessage, readRemoteReceipt,+ listAgents: async (sessionId: string) => {+ try { return await listAgents(sessionId); } catch (error) {+ if (error instanceof GroupToolAuthorizationError) return { ok: false as const, errorCode: error.code, message: error.message };+ throw error;+ }+ }, checkMessage, getThread, restore, assertRestoredQueuedDelivery };}export type BotDirectMessageService = ReturnType<typeof createBotDirectMessageService>;diff --git a/apps/desktop/src/main/maker-ipc/botGroupToolAuthorization.ts b/apps/desktop/src/main/maker-ipc/botGroupToolAuthorization.tsnew file mode 100644index 0000000000..ee384bb88f--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/botGroupToolAuthorization.ts@@ -0,0 +1,50 @@+import type { MessageSourceGroup } from '@cindy/maker-shared/message-source';+import { t } from '../i18n.js';++/** A group link identifies a lane, not an authorization. Only its live Chat Server+ * execution may supply authority; persisted route keys cannot recreate a grant. */+export type GroupToolOperation = 'read-self' | 'owner-action';+export interface GroupToolAuthority {+ botId: string;+ sourceGroup?: MessageSourceGroup;+ mode: 'owner' | 'chat' | 'tools';+ validate(): Promise<void>;+ isCurrent(): boolean;+}+const authorities = new Map<string, GroupToolAuthority>();++export class GroupToolAuthorizationError extends Error {+ readonly code: string;+ constructor(readonly temporary = false) {+ super(t(temporary ? 'groupTools.verificationUnavailable' : 'groupTools.authorizationRequired'));+ this.code = temporary ? 'GROUP_AUTHORIZATION_UNAVAILABLE' : 'GROUP_AUTHORIZATION_REQUIRED';+ }+}++export function registerGroupToolAuthority(sessionId: string, authority: GroupToolAuthority): () => void {+ authorities.set(sessionId, authority);+ return () => { if (authorities.get(sessionId) === authority) authorities.delete(sessionId); };+}++export async function authorizeGroupTool(sessionId: string, botId: string, operation: GroupToolOperation) {+ const authority = authorities.get(sessionId);+ const assertCurrent = () => {+ if (!authority || authorities.get(sessionId) !== authority || authority.botId !== botId+ || !authority.isCurrent() || authority.mode === 'chat'+ || (operation === 'owner-action' && authority.mode !== 'owner')) throw new GroupToolAuthorizationError();+ };+ assertCurrent();+ try { await authority!.validate(); } catch (error) {+ const revoked = error instanceof GroupToolAuthorizationError && !error.temporary;+ if (revoked && authorities.get(sessionId) === authority) authorities.delete(sessionId);+ // A transport failure denies this attempt, without permanently revoking a live lease.+ assertCurrent();+ throw new GroupToolAuthorizationError(!revoked);+ }+ assertCurrent();+ return { assertCurrent, mode: authority!.mode, sourceGroup: authority!.sourceGroup, refresh: async (): Promise<void> => {+ assertCurrent();+ await authorizeGroupTool(sessionId, botId, operation);+ assertCurrent();+ } };+}diff --git a/apps/desktop/src/main/maker-ipc/botSessionTaskRouteBridge.ts b/apps/desktop/src/main/maker-ipc/botSessionTaskRouteBridge.tsindex a27fc06ac9..4a15a0d82f 100644--- a/apps/desktop/src/main/maker-ipc/botSessionTaskRouteBridge.ts+++ b/apps/desktop/src/main/maker-ipc/botSessionTaskRouteBridge.ts@@ -7,6 +7,7 @@ interface TaskRouteBridgeDeps {setSessionRuntime(params: {targetSessionId: string;expectedGeneration: number;+ beforeMutation?: () => Promise<void>;patch: {harness?: SessionRuntimeProfile['agentKind'];model: string;@@ -40,8 +41,9 @@ export function createBotSessionTaskRouteBridge(next: next.candidate,};},- advance: async (childSessionId, expectedGeneration, route) => {+ advance: async (childSessionId, expectedGeneration, route, beforeApply) => {const current = await deps.getSessionRuntime({ targetSessionId: childSessionId });+ await beforeApply?.();if (!current.ok) return current;if (current.runtime.runtimeGeneration !== expectedGeneration) {return { ok: false, errorCode: 'CONFLICT', message: 'Task runtime changed before model selection' };@@ -49,6 +51,7 @@ export function createBotSessionTaskRouteBridge(const result = await deps.setSessionRuntime({targetSessionId: childSessionId,expectedGeneration,+ beforeMutation: beforeApply,patch: {...(current.runtime.effectiveProfile.agentKind === route.agentKind ? {} : { harness: route.agentKind }),model: route.model,diff --git a/apps/desktop/src/main/maker-ipc/botSkillService.ts b/apps/desktop/src/main/maker-ipc/botSkillService.tsindex c0658c72de..a8a657aa6c 100644--- a/apps/desktop/src/main/maker-ipc/botSkillService.ts+++ b/apps/desktop/src/main/maker-ipc/botSkillService.ts@@ -8,6 +8,7 @@*/import { app } from 'electron';+import { authorizeGroupTool, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';import { collectTeammateGuideMount } from './teammateGuideStore.js';import { botSkillRuntimeSummary, projectBotSkillMounts } from './botSkillRuntimeProjection.js';import { queryBotSkillIndex } from './botSkillQueryIndex.js';@@ -65,7 +66,7 @@ export interface BotSkillServiceDeps {ownerBoundaryPending?: () => boolean;requestRefresh?: typeof requestBotRuntimeEpochRefresh;resolveBotId?: (callerSessionId: string) => Promise<- | { ok: true; botId: string; canonicalSessionId?: string | null }+ | { ok: true; botId: string; canonicalSessionId?: string | null; refresh?: () => Promise<void> }| { ok: false; errorCode: string; message: string }>;}@@ -123,8 +124,8 @@ async function skillHomeOf(return dir;}-async function defaultResolveBotId(callerSessionId: string): Promise<- { ok: true; botId: string; canonicalSessionId: string | null } | { ok: false; errorCode: string; message: string }+async function defaultResolveBotId(callerSessionId: string, readOnly = false): Promise<+ { ok: true; botId: string; canonicalSessionId: string | null; refresh?: () => Promise<void> } | { ok: false; errorCode: string; message: string }> {const db = getDbClient().drizzle;const [row] = await db@@ -148,7 +149,9 @@ async function defaultResolveBotId(callerSessionId: string): Promise<if (row.sessionStatus !== 'active' || row.profileStatus !== 'active' || row.linkArchivedAt !== null) {return { ok: false, errorCode: 'BOT_SESSION_INACTIVE', message: '已归档的 Bot 任务不能沉淀技能' };}- if (row.role !== 'canonical' && row.role !== 'delegation') {+ const authority = row.role === 'group' && readOnly+ ? await authorizeGroupTool(callerSessionId, row.botId, 'read-self') : null;+ if (row.role !== 'canonical' && row.role !== 'delegation' && !authority) {return { ok: false, errorCode: 'BOT_SESSION_READ_ONLY', message: '当前 Bot 历史任务为只读状态' };}// Runtime hydration cannot mount the local personal shelf on an SSH host.@@ -157,10 +160,11 @@ async function defaultResolveBotId(callerSessionId: string): Promise<if (row.remoteHostId) {return { ok: false, errorCode: 'REMOTE_SKILLS_UNAVAILABLE', message: '当前远端任务尚未挂载伙伴自有 Skill 存储,不能读取或保存本机 Skill,也不能承诺远端生效' };}- return { ok: true, botId: row.botId, canonicalSessionId: row.canonicalSessionId };+ return { ok: true, botId: row.botId, canonicalSessionId: row.canonicalSessionId, ...authority };}function storeError(cause: unknown): { ok: false; errorCode: string; message: string } {+ if (cause instanceof GroupToolAuthorizationError) return { ok: false, errorCode: cause.code, message: cause.message };if (cause instanceof BotSkillStoreError) {return { ok: false, errorCode: cause.errorCode, message: cause.message };}@@ -227,13 +231,15 @@ export async function listBotSkillsForSession(): Promise<BotSkillResult<{ skills: ReturnType<typeof botSkillRuntimeSummary>[]; total: number; nextOffset?: number }>> {try {const boundary = captureOwnerBoundary(deps);- const owner = await (deps.resolveBotId ?? defaultResolveBotId)(params.callerSessionId);+ const owner = await (deps.resolveBotId ?? (id => defaultResolveBotId(id, true)))(params.callerSessionId);if (!owner.ok) return owner;assertOwnerBoundary(deps, boundary);const home = await skillHomeOf(deps, owner.botId, boundary);assertOwnerBoundary(deps, boundary);const result = await queryBotSkillIndex(botSkillRootDir(home, owner.botId), home, owner.botId, params);assertOwnerBoundary(deps, boundary);+ await owner.refresh?.();+ assertOwnerBoundary(deps, boundary);return { ok: true, ...result };} catch (cause) {return storeError(cause);diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 05b197893e..dcf9015a3c 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -13,6 +13,7 @@ import { createChatMedia } from './chatServerMedia.js';import { chatServerWorkspaces } from './chatServerWorkspaces.js';import { buildPlanStepBrief } from './botGroupDivision.js';import { chatMigrationReceipts } from './chatMigrationReceipts.js';+import { registerGroupToolAuthority, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';import path from 'node:path';import { randomUUID, createHash } from 'node:crypto';import WebSocket from 'ws';@@ -45,6 +46,7 @@ interface Room {interface Snapshot { room: Room; members: Member[]; messages: Message[]; cursor: string }interface Execution {id: string; conversation_id: string; source_message_id: string; bot_id: string;+ requester_id?: string;plan_id?: string | null; plan_step?: number | null;context_seq: string; epoch: number; status: string; access_mode: 'owner' | 'chat' | 'tools'; access_revision: number;}@@ -62,6 +64,7 @@ interface Running {workspace?: { workDir: string; branch: string | null; ownerSessionId: string | null };beforeFiles?: Map<string, string>;pauseStarted?: number;+ releaseToolAuthority?: () => void;}class ChatResponseError extends Error {constructor(code: string, readonly status: number) { super(code); }@@ -567,6 +570,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}} finally { run.delivery = undefined; }if (running.get(run.execution.bot_id) === run) {+ run.releaseToolAuthority?.();running.delete(run.execution.bot_id);changed(run.execution.conversation_id);}@@ -616,6 +620,29 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD...(run.plan ? { plan: { planId: run.plan.id, workDir: run.workspace?.workDir ?? '', sessionId: run.workspace?.ownerSessionId ?? undefined } } : {}) });if (!lane.ok) throw new Error(lane.errorCode);run.sessionId = lane.sessionId;+ run.releaseToolAuthority = registerGroupToolAuthority(lane.sessionId, {+ botId: bot.id, mode: execution.access_mode,+ sourceGroup: { groupId: s.room.id, name: s.room.name },+ isCurrent: () => current() && running.get(execution.bot_id) === run && !run.settlement,+ validate: async () => {+ // Recheck metadata and the execution lease at the actual tool boundary.+ // Group administrators cannot grant access to someone else's companion.+ try {+ const members = await api<Member[]>(`/conversations/${s.room.id}/members`);+ const companion = members.find(m => m.id === execution.bot_id && m.kind === 'bot' && m.state === 'joined');+ const requester = members.find(m => m.id === execution.requester_id && m.state === 'joined');+ if (!companion || companion.ownerActorId !== selfId || !requester+ || companion.accessRevision !== execution.access_revision+ || (execution.access_mode === 'owner' ? requester.ownerActorId !== selfId : companion.guestAccess !== 'tools'))+ throw new GroupToolAuthorizationError();+ await updateExecution(run, 'heartbeat');+ } catch (error) {+ if (error instanceof ChatResponseError && [401, 403, 404, 409, 410].includes(error.status))+ throw new GroupToolAuthorizationError();+ throw error;+ }+ },+ });if (run.plan && run.workspace?.ownerSessionId) {const settings = workspaces().read(s.room.id)!;const key = `${run.plan.id}:${execution.access_mode}:${execution.access_revision}`;@@ -666,6 +693,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (!dispatched.ok) throw new Error(dispatched.errorCode);changed(s.room.id);} catch {+ run.releaseToolAuthority?.();if (run.sessionId) await deps.abortLane(run.sessionId).catch(() => undefined);running.delete(execution.bot_id);await updateExecution(run, 'fail', { detail: 'Local runtime could not start' }).catch(() => undefined);@@ -709,6 +737,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// An in-flight heartbeat must not discard a result that became ready while// it was awaiting its response; retry the terminal operation for its receipt.if (!run.settlement && running.get(run.execution.bot_id) === run) {+ run.releaseToolAuthority?.();running.delete(run.execution.bot_id);if (run.sessionId) await deps.abortLane(run.sessionId).catch(() => undefined);changed(run.execution.conversation_id);@@ -916,7 +945,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDeditPlanStep: input => safe(() => actPlan(input, 'reassign')),dispose: () => {disposed = true; clearInterval(timer); clearInterval(heartbeat); clearTimeout(reconnect); socket?.close();- for (const run of running.values()) if (run.sessionId) void deps.abortLane(run.sessionId).catch(() => undefined);+ for (const run of running.values()) {+ run.releaseToolAuthority?.();+ if (run.sessionId) void deps.abortLane(run.sessionId).catch(() => undefined);+ }for (const pending of planning.values()) pending.controller.abort();running.clear();},diff --git a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.tsindex 75f3a8ef1f..98231a8e6e 100644--- a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts+++ b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts@@ -178,7 +178,7 @@ export function attachMainOwnedInputBoundary(};}-const MAIN_ONLY_PERSIST_FIELDS = ['sharedTaskAuthor', 'origin', 'sourceDevice', 'sourcePlugin'] as const;+const MAIN_ONLY_PERSIST_FIELDS = ['sharedTaskAuthor', 'origin', 'sourceDevice', 'sourcePlugin', 'sourceGroup'] as const;const MAIN_ONLY_SEND_FIELDS = ['fromMobileClient','fromDeviceLinkClient',@@ -193,6 +193,7 @@ const MAIN_ONLY_SEND_FIELDS = ['origin','sourceDevice','sourcePlugin',+ 'sourceGroup','sourceOrigin','sharedTaskAuthor',] as const;diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 4481bb8205..d28b525c27 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -148,6 +148,7 @@ import {normalizeAgentInputClearBoundaryMs,serializeSessionReferencePayload,USAGE_LIMIT_RESET_AUTO_RESUME_REASON,+ HOST_ONLY_AGENT_PREFIX,type AgentInputClearBoundaryOpts,type AgentInputCreateOpts,type AgentInputQueuedMessage,@@ -723,6 +724,7 @@ import {AcceptedCallbackDispatchCancelled,runAcceptedCallback,} from './acceptedCallbackRunner.js';+import { GroupToolAuthorizationError } from './botGroupToolAuthorization.js';import { createElectronIpcHandlerRegistry } from './electronIpcRegistry.js';import { refreshCodexMcpEnvironment } from './codexMcpRefresh.js';@@ -9154,7 +9156,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},withCloseSuppressed: withRehydrateCloseSuppressed,pendingSwitches: agentSwitchPending,- selectSameAgentModel: async (sessionId, intent, applyNow, assertSelectionCurrent) => {+ selectSameAgentModel: async (sessionId, intent, applyNow, assertSelectionCurrent, beforeMutation) => {const result = await applySessionRuntimeSelection(sessionId, intent.model, intent.providerId, {effort: (intent.effort ?? null) as SessionRuntimeProfile['effort'],fastMode: intent.fastMode ?? false,@@ -9162,7 +9164,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)...(intent.confirmedContextWindow ? { confirmedContextWindow: intent.confirmedContextWindow } : {}),}, { source: 'user', sessionLockHeld: true, applyingUserSelectionOnSend: applyNow,runtimeSource: intent.runtimeSource, configStaged: intent.configStaged === true,- assertSelectionCurrent });+ assertSelectionCurrent, beforeMutation });return result;},onPendingSwitchChanged: (sessionId, intent) => {@@ -10431,12 +10433,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)botDirectMessageServiceHolder = createBotDirectMessageService({transport: createBotMessageTransport({ selfDeviceId: getSelfDeviceId,listDevices: () => handleListDevices(deviceDirectoryDeps()), invoke: invokeBotPeer }),+ discardQueuedDelivery: async (sessionId, clientId, assertOwner) => {+ await inputCoordinator.ensureQueueRestored(sessionId);+ assertOwner();+ inputCoordinator.remove(sessionId, clientId);+ },hasQueuedDelivery: async (sessionId, clientId) => {await inputCoordinator.ensureQueueRestored(sessionId);return inputCoordinator.hasKnownClientId(sessionId, clientId);},dispatch: ({targetSessionId,+ dispatcherSessionId,message,persistedContent,clientId,@@ -10445,6 +10453,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}) =>dispatchBotSessionMessage({targetSessionId,+ dispatcherSessionId,message,persistedContent,clientId,@@ -10461,11 +10470,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): undefined,onAcceptedRollback,}),- ensureCanonicalSession: async (botId) => {+ ensureCanonicalSession: async (botId, beforeRecovery) => {if (!botDelegationServiceHolder) {return { ok: false as const, errorCode: 'DELEGATION_UNAVAILABLE', message: '伙伴消息服务尚未就绪' };}- return botDelegationServiceHolder.ensureCanonicalSession(botId);+ return botDelegationServiceHolder.ensureCanonicalSession(botId, beforeRecovery);},captureOwnerScope: captureDataOwnerBroadcastScope,isOwnerScopeCurrent: (scope) =>@@ -10694,7 +10703,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)message,persistedContent,clientId,- onAccepted,+ onAccepted: onAccepted ? async (replayed) => {+ try {+ await onAccepted(replayed);+ } catch (error) {+ if (error instanceof GroupToolAuthorizationError) {+ throw new AcceptedCallbackDispatchCancelled(error.message);+ }+ throw error;+ }+ } : undefined,dispatcherSessionId,}),discardDelegationQueuedInputs: (sessionId, delegationId) =>@@ -11915,10 +11933,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 排队行的遮蔽按 text 判定,所以 text 保留前缀,只在最终 wire 组装时去掉// (agentOmitsTriggerPrefix → buildMakerUserMessage)。const hiddenTriggerForAgent = !params.message.startsWith(UI_ACTION_TRIGGER_PREFIX)- && params.persistedContent === `${UI_ACTION_TRIGGER_PREFIX}${params.message}`;+ && params.persistedContent.startsWith(UI_ACTION_TRIGGER_PREFIX);+ // Group peer envelopes belong only to the current model dispatch. Keep the+ // safe authored body in queue text/history; the symbol never crosses JSON.+ const modelOnlyEnvelope = params.clientId.startsWith('bot-dm:') && hiddenTriggerForAgent+ && params.persistedContent !== `${UI_ACTION_TRIGGER_PREFIX}${params.message}`;return {clientId: params.clientId,- text: hiddenTriggerForAgent ? params.persistedContent : params.message,+ 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) } : {}),...(hiddenTriggerForAgent ? { agentOmitsTriggerPrefix: true as const } : {}),...(params.autoReviewUserText !== undefined ? { autoReviewUserText: params.autoReviewUserText } : {}),...(params.toolsDisabled === true ? { toolsDisabled: true } : {}),@@ -11938,7 +11962,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)...(fileAttachments?.length ? { files: fileAttachments } : {}),},createOpts,- ...(params.origin ? { origin: params.origin } : {}),+ ...(params.origin ? { origin: modelOnlyEnvelope && (params.origin.kind === 'session' || params.origin.kind === 'orca')+ ? { ...params.origin, displayText: params.persistedContent } : params.origin } : {}),...(params.sourcePlugin ? { sourcePlugin: params.sourcePlugin } : {}),};}@@ -13036,6 +13061,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)/** 系统配置对齐(IM 渠道默认跟随 / 伙伴模型对齐)登记: 落地时不打「脱离跟随」标记。 */configStaged?: boolean;assertSelectionCurrent?: () => void;+ beforeMutation?: () => Promise<void>;/** Internal calls from the send / switch transaction already own the route lock. */sessionLockHeld?: boolean;applyingUserSelectionOnSend?: boolean;@@ -13809,7 +13835,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): readSessionRuntimeFallbackSettings().enabled,};},- setSessionRuntime: async ({ targetSessionId, expectedGeneration, patch }) => {+ setSessionRuntime: async ({ targetSessionId, expectedGeneration, patch, beforeMutation }) => {if (patch.harness !== undefined) {return setSessionRuntimeHarness({withSessionLock: withSendToSessionLock,@@ -13838,16 +13864,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (!axes.ok) throwIpcError('INVALID_PARAMS', `target model runtime axes unavailable: ${axes.reason}`);return { ...profile, providerId: providerId ?? null, effort: axes.effort, fastMode: axes.fastMode };},- stage: async (id, profile, assertSelectionCurrent) => {+ stage: async (id, profile, assertSelectionCurrent, beforeMutation) => {return performSessionAgentSwitch(agentSwitchDeps, {sessionId: id, targetAgentKind: profile.agentKind, model: profile.model,providerId: profile.providerId, effort: profile.effort, fastMode: profile.fastMode,- runtimeSource: 'agent', assertSelectionCurrent,+ runtimeSource: 'agent', assertSelectionCurrent, beforeMutation,});},- }, { targetSessionId, expectedGeneration, patch: { ...patch, harness: patch.harness } });+ }, { targetSessionId, expectedGeneration, beforeMutation, patch: { ...patch, harness: patch.harness } });}const profiles = await readSessionRuntimeProfiles(targetSessionId);+ if (beforeMutation) await beforeMutation();if (!profiles) {return {ok: false,@@ -13869,6 +13896,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions){ effort: next.effort, fastMode: next.fastMode },{source: 'agent',+ beforeMutation,expectedGeneration,deferWhileRunning: true,effectiveProfile: profiles.effective,@@ -13937,11 +13965,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},steerQueuedMessage: async (sessionId, item, expectedTurn) => {await inputCoordinator.ensureQueueRestored(sessionId);+ await expectedTurn.beforeMutation?.();return inputCoordinator.steer(sessionId, item, {touchUserSend: true,fallbackToTurn: false,expectedTurnSession: expectedTurn.session,expectedTurnGeneration: expectedTurn.turnGeneration,+ beforeMutation: expectedTurn.beforeMutation,});},getQueueSnapshot: async (sessionId) => {@@ -16099,6 +16129,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)orcaInterAgentDispatcher.discardQueuedOrcaInterAgentAcceptedCallback(item.clientId);},onAcceptedQueuedMessage: async (sessionId, item, restoredFromSnapshot): Promise<void> => {+ if (restoredFromSnapshot && item.clientId.startsWith('bot-dm:')) {+ if (!botDirectMessageServiceHolder) throw new AcceptedCallbackDispatchCancelled('Bot message recovery unavailable');+ await botDirectMessageServiceHolder.assertRestoredQueuedDelivery(sessionId, item.clientId);+ }// 已派发 → 该项不会再走 discard,释放 scheduler 的 discard 监听防泄漏。schedulerQueuedPromptDiscardWatchers.delete(item.clientId);schedulerQueuedPromptPreparations.delete(item.clientId);@@ -18339,6 +18373,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 那台的 Agent 认为需要换进程(跨来源等)时关掉本次连接,下一次发送按新路由重新启动// 并接上原来的对话;否则直接在那台的会话里切换。const rebuild = await live.requiresModelSwitchRebuild?.(model, { providerId: targetProviderId }) ?? false;+ if (internalOptions.beforeMutation) await internalOptions.beforeMutation();+ assertRuntimeOwnerCurrent();if (rebuild) {await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId, 'runtime-refresh'));} else {@@ -18700,6 +18736,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// authoritative until a real send holds this same lock and consumes the final choice.if (internalOptions.source === 'user' && !internalOptions.applyingUserSelectionOnSend &&!runtimeStatus.remoteHostId && !runtimeStatus.orcaRole) {+ if (internalOptions.beforeMutation) await internalOptions.beforeMutation();assertRuntimeOwnerCurrent();assertSharedTaskCurrent.admit();clearPendingCredentialSwitchForSession(sessionId, { wake: false });@@ -18734,6 +18771,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): await resolvePendingRuntimeAxisPatch(sessionId, axisPatch);const deferLockedSelection = async () => {const meta = await maker.getSessionMeta(sessionId);+ if (internalOptions.beforeMutation) await internalOptions.beforeMutation();if (!meta) return { deferred: false, superseded: true };if (supersededByOwnerBoundary()) {return { deferred: false, superseded: true };@@ -18875,6 +18913,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)providerId: targetRouteProviderId,}): undefined;+ if (internalOptions.beforeMutation) await internalOptions.beforeMutation();if (runtimeAgentKind === 'pi' && (runtimeRouteChanged || piConfigurationRefresh) && liveSessionBeforeRouteChange) {if (!piPreview || piPreview.action === 'unavailable') {throwIpcError(@@ -19393,6 +19432,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const result: Awaited<ReturnType<typeof applyRuntimeSetModelChange>> = routeExplicit? await applyRuntimeSetModelChange({maker,+ beforeMutation: internalOptions.beforeMutation,admit: () => { assertRuntimeOwnerCurrent(); assertSharedTaskCurrent.admit(); },sessionId,model,diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.tsindex 77119bc69a..eede7dac8c 100644--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts@@ -78,6 +78,8 @@ export interface ApplyRuntimeSetModelChangeInput {assertSessionCloseSupported?: () => void;/** Called after async preflight, immediately before the first setting side effect. */admit?: () => void;+ /** Host authorization refreshed after async route preparation, before admission. */+ beforeMutation?: () => Promise<void>;isSessionInTurn?: (sessionId: string) => boolean;/*** 会话自己正在跑 turn 时的延迟生效登记(PendingCredentialSwitchService.register)。@@ -258,6 +260,7 @@ export async function applyRuntimeSetModelChange(}if (!sess && requiresCodexThreadRelink) {+ if (input.beforeMutation) await input.beforeMutation();input.admit?.();await input.relinkCodexThread?.();if (providerId !== undefined) setSessionProvider(sessionId, nextProviderId);@@ -278,6 +281,7 @@ export async function applyRuntimeSetModelChange(// 把 route/model 的生效边界固定在 turn 结束;pending 收口只关闭本 Session,// 当前账号保持到回合边界,不能让工具续轮命中新账号。if (input.registerPendingCredentialSwitch) {+ if (input.beforeMutation) await input.beforeMutation();input.admit?.();await input.registerPendingCredentialSwitch(sessionId, {model,@@ -300,6 +304,7 @@ export async function applyRuntimeSetModelChange(if (sess && (shouldCloseSession || requiresCodexThreadRelink)) {input.assertSessionCloseSupported?.();+ if (input.beforeMutation) await input.beforeMutation();input.admit?.();if (isSelfBusy() && input.registerPendingCredentialSwitch) {// A required credential rebuild must also survive close failure: keeping@@ -409,6 +414,7 @@ export async function applyRuntimeSetModelChange(: { status: 'applied', retiredRuntime: true };}+ if (input.beforeMutation) await input.beforeMutation();input.admit?.();if (providerId !== undefined) {setSessionProvider(sessionId, nextProviderId);diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.tsindex 2bfb330485..7c329d2cf1 100644--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts@@ -133,6 +133,7 @@ export interface MakerSessionAgentSwitchHandlerDeps {intent: PendingAgentSwitchIntent,applyNow: boolean,assertSelectionCurrent?: () => void,+ beforeMutation?: () => Promise<void>,): Promise<{ deferred: boolean; superseded?: boolean }>;/** 与 send / SET_MODEL 共用的 session 锁;生产注入,最小测试 harness 可省略。 */withSessionLock?<T>(sessionId: string, task: () => Promise<T>): Promise<T>;@@ -437,6 +438,7 @@ export async function performSessionAgentSwitch(configStaged?: boolean;/** Recheck caller CAS after asynchronous validation, before staging any intent. */assertSelectionCurrent?: () => void;+ beforeMutation?: () => Promise<void>;},): Promise<SessionAgentSwitchResult> {const { sessionId, targetAgentKind, model, providerId, signal } = params;@@ -503,6 +505,7 @@ export async function performSessionAgentSwitch(throwIpcError('UNSUPPORTED_CAPABILITY', 'agent switch is not supported for Orca sessions');}+ if (params.beforeMutation) await params.beforeMutation();params.assertSelectionCurrent?.();const fromDbKind: DbAgentKind = normalizeDbAgentKind(row.agentKind);@@ -520,6 +523,7 @@ export async function performSessionAgentSwitch(model,typeof normalizedProviderId === 'string' ? normalizedProviderId : null,);+ if (params.beforeMutation) await params.beforeMutation();throwIfAgentSwitchAborted(signal);params.assertSelectionCurrent?.();}@@ -536,7 +540,7 @@ export async function performSessionAgentSwitch(sameAgentSelection: true,...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),...(params.configStaged === true ? { configStaged: true } : {}),- }, false, params.assertSelectionCurrent);+ }, false, params.assertSelectionCurrent, params.beforeMutation);return {switched: false,agentKind: targetAgentKind,diff --git a/apps/desktop/src/main/maker-ipc/sessionControlService.ts b/apps/desktop/src/main/maker-ipc/sessionControlService.tsindex 5e1cbf0489..38a631d22e 100644--- a/apps/desktop/src/main/maker-ipc/sessionControlService.ts+++ b/apps/desktop/src/main/maker-ipc/sessionControlService.ts@@ -81,6 +81,7 @@ export interface SessionControlLiveSession {export interface SessionSteerTurnIdentity {session: SessionControlLiveSession;turnGeneration: number;+ beforeMutation?: () => Promise<void>;}export interface SessionControlServiceDeps {@@ -91,6 +92,7 @@ export interface SessionControlServiceDeps {setSessionRuntime(params: {targetSessionId: string;expectedGeneration?: number;+ beforeMutation?: () => Promise<void>;patch: {harness?: AgentKind;model?: string;@@ -145,6 +147,8 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {callerSessionId: string;targetSessionId: string;queuedMessageId: string;+ /** Host-only authorization check after async reads, immediately before mutation. */+ beforeMutation?: () => Promise<void>;message: string;}): Promise<SessionQueuedMessageControlResult> {const missing = await ensureTarget(params.targetSessionId);@@ -154,6 +158,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {queuedMessageId: params.queuedMessageId,message: params.message,authorize: (item) => authorizeSessionQueueItem(item, params.callerSessionId),+ beforeMutation: params.beforeMutation,rebuild: rebuildSessionQueueItem,});},@@ -162,6 +167,8 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {callerSessionId: string;targetSessionId: string;queuedMessageId: string;+ /** Host-only authorization check after async reads, immediately before mutation. */+ beforeMutation?: () => Promise<void>;}): Promise<SessionQueuedMessageControlResult> {const missing = await ensureTarget(params.targetSessionId);if (missing) return missing;@@ -169,6 +176,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {sessionId: params.targetSessionId,queuedMessageId: params.queuedMessageId,authorize: (item) => authorizeSessionQueueItem(item, params.callerSessionId),+ beforeMutation: params.beforeMutation,});},@@ -210,12 +218,15 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {message: string;/** Host-owned stable ID; the input coordinator owns acceptance deduplication. */queuedMessageId?: string;+ beforeMutation?: () => Promise<void>;}): Promise<SessionSteerResult> {const missing = await ensureTarget(params.targetSessionId);+ await params.beforeMutation?.();if (missing) return missing;try {await deps.assertExternalInputAllowed(params.targetSessionId);} catch (error) {+ await params.beforeMutation?.();if ((error as { code?: unknown }).code === 'UNSUPPORTED_CAPABILITY') {return {ok: false,@@ -225,6 +236,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {}throw error;}+ await params.beforeMutation?.();const live = deps.getLiveSession(params.targetSessionId);if (!live?.isTurnRunning()) {return {@@ -246,6 +258,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {...params,queuedMessageId,});+ await params.beforeMutation?.();const current = deps.getLiveSession(params.targetSessionId);if (current !== live ||@@ -258,7 +271,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {message: `session ${params.targetSessionId} changed turns before steer was accepted`,};}- const expectedTurn = { session: live, turnGeneration };+ const expectedTurn = { session: live, turnGeneration, ...(params.beforeMutation ? { beforeMutation: params.beforeMutation } : {}) };const accepted = await deps.steerQueuedMessage(params.targetSessionId, item, expectedTurn);if (!accepted) {const latest = deps.getLiveSession(params.targetSessionId);@@ -279,8 +292,9 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {return { ok: true, queuedMessageId };},- async stopSessionTurn(params: { targetSessionId: string }): Promise<SessionStopResult> {+ async stopSessionTurn(params: { targetSessionId: string; beforeMutation?: () => Promise<void> }): Promise<SessionStopResult> {const missing = await ensureTarget(params.targetSessionId);+ if (params.beforeMutation) await params.beforeMutation();if (missing) return missing;const live = deps.getLiveSession(params.targetSessionId);if (!live) return { ok: true, status: 'no-active-turn' };@@ -322,6 +336,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {async setSessionRuntime(params: {targetSessionId: string;expectedGeneration?: number;+ beforeMutation?: () => Promise<void>;patch: {harness?: AgentKind;model?: string;@@ -331,6 +346,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {};}): Promise<SessionRuntimeSetResult> {const missing = await ensureTarget(params.targetSessionId);+ if (params.beforeMutation) await params.beforeMutation();if (missing) return missing;return deps.setSessionRuntime(params);},diff --git a/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.ts b/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.tsindex 85a7c5f2e1..ae9d079d9a 100644--- a/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.ts+++ b/apps/desktop/src/main/maker-ipc/sessionRuntimeHarnessSelection.ts@@ -38,6 +38,7 @@ export interface HarnessRuntimeSelectionDeps {sessionId: string,profile: SessionRuntimeProfile,assertCurrent: () => void,+ beforeMutation?: () => Promise<void>,): Promise<{ deferred?: boolean; sameEngineSuperseded?: boolean }>;pending(sessionId: string): PendingAgentSwitchIntent | undefined;}@@ -48,6 +49,7 @@ export async function setSessionRuntimeHarness(params: {targetSessionId: string;expectedGeneration?: number;+ beforeMutation?: () => Promise<void>;patch: {harness: AgentKind;model?: string;@@ -84,6 +86,7 @@ export async function setSessionRuntimeHarness(};assertCurrent();const effective = await deps.read(id);+ if (params.beforeMutation) await params.beforeMutation();if (!effective)return { ok: false, errorCode: 'NOT_FOUND', message: `session ${id} not found` };const profile = await deps.resolve(@@ -98,7 +101,7 @@ export async function setSessionRuntimeHarness({ effort: patch.effort !== undefined, fast: patch.fastMode !== undefined },);assertCurrent();- const result = await deps.stage(id, profile, assertCurrent);+ const result = await deps.stage(id, profile, assertCurrent, params.beforeMutation);if (result.sameEngineSuperseded) {return {ok: false,diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 2dfb677db0..b25ba8526b 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -1,3 +1,4 @@+import { t } from '../i18n.js';import { executeTaskTags } from '../localDb/ipc/taskTags.js';import { getPluginMarketService } from '../plugin-market/service.js';import { resolveHelperSurface } from './helperSurface.js';@@ -778,6 +779,11 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc},},botMessaging: {+ sendToUser: async (params) => {+ const svc = tryGetBotDirectMessageService();+ if (!svc) return { ok: false, errorCode: 'HOST_NOT_READY', message: t('groupTools.privateUnavailable') };+ return svc.sendToUser(params);+ },checkMessage: async (params) => {const svc = tryGetBotDirectMessageService();if (!svc) return { ok: false, errorCode: 'HOST_NOT_READY', message: 'Teammate messaging is unavailable' };diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.tsindex 92ea6478fd..dfa5767aef 100644--- a/apps/desktop/src/main/worktree/WorktreeManager.ts+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts@@ -619,7 +619,7 @@ export function getForSession(sessionId: string): WorktreeMeta | null {}/** Caller holds the session/resource locks. Unknown DB outcomes retain the intent. */-async function reconcileSessionTransferLocked(meta: WorktreeMeta): Promise<void> {+async function reconcileSessionTransferLocked(meta: WorktreeMeta, beforeMutation?: () => Promise<void>): Promise<void> {const transfer = meta.pendingSessionTransfer;if (!transfer) return;if (!transfer.sessionId || transfer.sessionId === meta.sessionId@@ -651,11 +651,11 @@ async function reconcileSessionTransferLocked(meta: WorktreeMeta): Promise<void>}const next = { ...meta, sessionId: row.childSessionId };delete next.pendingSessionTransfer;- await store.replace(meta.sessionId, next.sessionId, next, meta);+ await store.replace(meta.sessionId, next.sessionId, next, meta, beforeMutation);}/** Startup/dispatch/retry reconciliation, scoped to the affected execution only. */-export async function reconcileSessionTransfer(sessionId: string): Promise<void> {+export async function reconcileSessionTransfer(sessionId: string, beforeMutation?: () => Promise<void>): Promise<void> {const pending = store.getAll().find(meta => meta.pendingSessionTransfer&& (meta.sessionId === sessionId || meta.pendingSessionTransfer.sessionId === sessionId));if (!pending?.pendingSessionTransfer) return;@@ -664,7 +664,7 @@ export async function reconcileSessionTransfer(sessionId: string): Promise<void>withWorktreeRestoreMutation(pending.pendingSessionTransfer!.sessionId, () =>withWorktreeResourceLock(pending.path, async () => {const current = store.get(pending.sessionId);- if (current?.pendingSessionTransfer) await reconcileSessionTransferLocked(current);+ if (current?.pendingSessionTransfer) await reconcileSessionTransferLocked(current, beforeMutation);})));}diff --git a/apps/desktop/src/main/worktree/worktreeStore.ts b/apps/desktop/src/main/worktree/worktreeStore.tsindex 7e310074c4..6fba76bfe6 100644--- a/apps/desktop/src/main/worktree/worktreeStore.ts+++ b/apps/desktop/src/main/worktree/worktreeStore.ts@@ -214,6 +214,7 @@ export async function replace(sessionId: string,meta: WorktreeMeta,expected?: WorktreeMeta,+ beforeMutation?: () => Promise<void>,): Promise<void> {if (!sessionId) throw new Error('worktreeStore.replace: sessionId is required');await mutateRegistry((map) => {@@ -223,7 +224,7 @@ export async function replace(}if (previousSessionId && previousSessionId !== sessionId) delete map[previousSessionId];map[sessionId] = meta;- });+ }, beforeMutation);try {await setWorktreePathInDb(sessionId, meta.path);} catch (err) {@@ -234,11 +235,12 @@ export async function replace(}}-async function mutateRegistry(mutate: (map: Record<string, WorktreeMeta>) => void): Promise<void> {+async function mutateRegistry(mutate: (map: Record<string, WorktreeMeta>) => void, beforeMutation?: () => Promise<void>): Promise<void> {const uid = typeof process.getuid === 'function' ? process.getuid() : 0;await withCrossProcessLock(path.join(os.tmpdir(), `cindy-worktree-registry-${uid}.lock`),{ label: 'worktree-registry' }, async (status) => {if (!status.held) throw new Error('worktree registry is busy');+ if (beforeMutation) await beforeMutation();const map = readMap();mutate(map);writeMap(map);diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAroundClientId.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAroundClientId.test.tsindex 6d43a9c571..06c746b37e 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAroundClientId.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAroundClientId.test.ts@@ -37,6 +37,9 @@ vi.mock('@/lib/composerDraftStore', () => ({}),}));+import { redactMessageRowForSharedGuest } from '../../main/device-link/sharedTaskMessageOrigin';+import { groupWorkRuns } from '@/components/chat/messageWorkGroups';+import { simplifyBotRenderItems } from '@/features/bots/botConversationPresentation';import { makerChatStore } from '@/lib/makerChatStore';import { aroundMessagesByClientIdFor } from '@/lib/makerTransport';import type { Message } from '@/lib/ccAgent.types';@@ -104,6 +107,29 @@ describe('makerChatStore loadAroundMessageClientId', () => {]);});+ it.each([true, false])('keeps a redacted group delivery visible without sealing private progress (running=%s)', async (running) => {+ const rows = [+ serverMessage({ clientId: 'progress-before', role: 'assistant', content: 'Working before' }),+ serverMessage({ clientId: 'group-delivery', role: 'assistant', content: 'Explicit reply',+ agentMeta: { sourceGroup: { groupId: 'private-group', name: 'Secret group' } } }),+ serverMessage({ clientId: 'progress-after', role: 'assistant', content: 'Working after' }),+ serverMessage({ clientId: 'tool', role: 'tool_use', content: { toolName: 'Read', toolUseId: 't', input: {} } }),+ ...(!running ? [serverMessage({ clientId: 'final', role: 'assistant', content: 'Final reply', agentMeta: { turnCompleted: true } })] : []),+ ].map(redactMessageRowForSharedGuest);+ expect(rows[1].agentMeta).toEqual({ explicitDelivery: true });+ expect(JSON.stringify(rows)).not.toMatch(/private-group|Secret group/);+ vi.mocked(aroundMessagesByClientIdFor).mockResolvedValueOnce(rows);+ await makerChatStore.loadAroundMessageClientId(SID, 'group-delivery', { radius: 10 });+ const messages = makerChatStore.getSnapshot(SID).messages;+ expect(messages.find(m => m.clientId === 'group-delivery')).toMatchObject({ explicitDelivery: true });+ const items = messages.map(message => ({ type: 'message' as const, key: message.clientId, message }));+ const visible = simplifyBotRenderItems(groupWorkRuns(items, running), running)+ .flatMap(item => item.type === 'message' && item.message.role === 'assistant' ? [item.message.content] : []);+ expect(visible).toContain('Explicit reply');+ expect(visible).not.toContain('Working before');+ expect(visible).not.toContain('Working after');+ });+it('hydrates shorter authoritative tool_result content during around-message hydration', async () => {vi.mocked(aroundMessagesByClientIdFor).mockResolvedValueOnce([diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.tsindex 85348b09a4..59572ccd1c 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts@@ -212,3 +212,21 @@ describe('teammate result attachment history', () => {expect(messages.find(message => message.clientId === 'final')?.botTaskResults).toEqual([result]);});});++// Both initial history and live message insertion use the same stored-row projection.+describe('private group reply source', () => {+ it('keeps group provenance on assistant rows without relabeling normal private replies', async () => {+ const id = sid('group-private-source');+ transportMocks.listMessages.mockResolvedValueOnce([+ { id: 'group-reply', clientId: 'group-reply', sessionId: id, role: 'assistant', content: 'Reply',+ agentMeta: { sourceGroup: { groupId: 'g-1', name: 'Design' } }, createdAt: Date.now() },+ { id: 'private-reply', clientId: 'private-reply', sessionId: id, role: 'assistant', content: 'Private',+ agentMeta: null, createdAt: Date.now() },+ ] as never);+ makerChatStore.ensureInitialMessages(id);+ await vi.waitFor(() => expect(makerChatStore.getSnapshot(id).historyLoaded).toBe(true));+ const messages = makerChatStore.getSnapshot(id).messages;+ expect(messages.find(m => m.clientId === 'group-reply')).toMatchObject({ role: 'assistant', sourceGroup: { groupId: 'g-1', name: 'Design' } });+ expect(messages.find(m => m.clientId === 'private-reply')?.sourceGroup).toBeUndefined();+ });+});diff --git a/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx b/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsxindex dff585eeac..108de4fce0 100644--- a/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx@@ -1,5 +1,5 @@/**- * 用户消息气泡上方的来源标签行。+ * 消息气泡上方的来源标签行;群内显式私聊的 assistant 消息复用同一行。** 两个独立维度(与 @cindy/maker-shared/message-source 同口径):* - 谁发的(至多一个):自动化 / 其他任务 / 伙伴 / Orca 发送方 / Hook 渠道 / 插件;@@ -9,7 +9,7 @@* 整行属于来源标注,分享图不带(SHARE_SOURCE_ATTR)。*/-import { Monitor, Puzzle, Smartphone } from 'lucide-react';+import { Monitor, Puzzle, Smartphone, Users } from 'lucide-react';import { useNavigate } from 'react-router-dom';import { useTranslation } from 'react-i18next';@@ -27,7 +27,7 @@ import {import { SHARE_SOURCE_ATTR } from '@/lib/shareConversationImage';import { toast } from '@/lib/toast';import { cn } from '@/lib/utils';-import type { MessageSourceDevice, MessageSourcePlugin } from '@cindy/maker-shared/message-source';+import type { MessageSourceDevice, MessageSourcePlugin, MessageSourceGroup } from '@cindy/maker-shared/message-source';import { AutomationOriginBadge, MessageSourceLabelShell } from './AutomationOriginBadge';@@ -152,6 +152,7 @@ export function MessageSourceLabels({hookIm,sourceDevice,sourcePlugin,+ sourceGroup,hostSessionId,align = 'end',}: {@@ -159,10 +160,11 @@ export function MessageSourceLabels({hookIm?: string;sourceDevice?: MessageSourceDevice;sourcePlugin?: MessageSourcePlugin;+ sourceGroup?: MessageSourceGroup;hostSessionId?: string;align?: 'start' | 'end';}) {- if (!automationOrigin && !sourceDevice && !sourcePlugin) return null;+ if (!automationOrigin && !sourceDevice && !sourcePlugin && !sourceGroup) return null;return (<div{...{ [SHARE_SOURCE_ATTR]: '' }}@@ -172,8 +174,10 @@ export function MessageSourceLabels({align === 'start' ? 'justify-start' : 'justify-end',)}>- {/* 插件优先(与 messageSourceSenderFromMeta 同序):插件在某任务里派发时同时带来源任务 origin。 */}- {sourcePlugin ? (+ {/* 群来源仅用于显式私聊;普通发送方仍以插件优先于其运行任务。 */}+ {sourceGroup ? (+ <MessageSourceGroupBadge group={sourceGroup} />+ ) : sourcePlugin ? (<MessageSourcePluginBadge plugin={sourcePlugin} hostSessionId={hostSessionId} />) : automationOrigin ? (<AutomationOriginBadge@@ -186,3 +190,13 @@ export function MessageSourceLabels({</div>);}++function MessageSourceGroupBadge({ group }: { group: MessageSourceGroup }) {+ const { t } = useTranslation();+ return <MessageSourceLabelShell+ kind="group"+ icon={<Users size={11} strokeWidth={1.75} aria-hidden className="shrink-0" />}+ label={group.name ? t('chat.userMessage.groupSentNamed', { name: group.name }) : t('chat.userMessage.groupSent')}+ tooltip={t('chat.userMessage.sourceIds.group', { id: group.groupId })}+ />;+}diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 99c81facdb..c8b1352f9e 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -308,6 +308,7 @@ function hasNestedScrollableAncestorThatCanScrollDown(import { UserMessage } from './UserMessage';import { AssistantMessage } from './AssistantMessage';+import { MessageSourceLabels } from './MessageSourceLabels';import { AskUserQuestionBubble } from './AskUserQuestionBubble';import { ErrorMessageCard } from './ErrorMessageCard';import { APP_EXIT_INTERRUPTED_REASON } from '../../../shared/interruptedTurn';@@ -6763,6 +6764,7 @@ const MessageItem = memo(function MessageItem({return withAssistantAvatar(assistantAvatar,<>+ <MessageSourceLabels sourceGroup={message.sourceGroup} align="start" /><AssistantMessageworkingDir={workingDir}localFileRefs={localFileRefs}diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsxindex c9c5fb9f48..e3d589a496 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/MessageSourceLabels.test.tsx@@ -178,3 +178,13 @@ describe('QueueSourceDeviceTag (pending queue rows)', () => {});});++describe('private group reply source', () => {+ it('shows the group name and id in the existing source row, excluded from share images', () => {+ const { container } = render(<MessageSourceLabels sourceGroup={{ groupId: 'g-1', name: 'Design' }} align="start" />);+ const label = screen.getByText('chat.userMessage.groupSentNamed:Design');+ expect(label.closest('[data-message-origin]')?.getAttribute('title')).toBe('chat.userMessage.sourceIds.group:g-1');+ expect(container.querySelector(`[${SHARE_SOURCE_ATTR}]`)).not.toBeNull();+ expect(container.querySelector('button')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.tsindex ffba85244d..935ea55e18 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts@@ -216,3 +216,10 @@ it('nests only explicitly bound results, preserving original anchor and human meexpect(allKeys(project([receipt, message('unrelated', 'assistant', 'Other', { turnCompleted: true })], false))).toContain('msg-receipt');expect(input[1]).toBe(receipt);});++it('keeps explicitly delivered group private messages while the private model is working and after another reply', () => {+ const input = [message('u', 'user'), message('group', 'assistant', 'Group reply', { sourceGroup: { groupId: 'g-1' } }),+ message('progress', 'assistant', 'Working'), tool('running')];+ expect(proseIds(project(input, true))).toEqual(['group']);+ expect(proseIds(project([...input, message('final', 'assistant', 'Result', { turnCompleted: true })], false))).toEqual(['group', 'final']);+});diff --git a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts b/apps/desktop/src/renderer/features/bots/botConversationPresentation.tsindex 00b9aa278e..f9c31f6b65 100644--- a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts+++ b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts@@ -123,7 +123,7 @@ function projectWindow(if (item.type === 'message' && item.message.isSyntheticTrigger) return;if (isProse(item)) {if (!item.message.content.trim() && !hasAttachments(item.message)) return;- if (!isCompletedAssistantMessage(item.message) && !sealedAnswers.has(item.message)+ if (!item.message.sourceGroup && !item.message.explicitDelivery && !isCompletedAssistantMessage(item.message) && !sealedAnswers.has(item.message)&& !hasAttachments(item.message) && index !== fallbackProse&& extractRenderedMarkdownImageTargets(item.message.content).length === 0) {return;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7e2af7b72a..4e2c12d8de 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10534,7 +10534,8 @@"automation": "Automation ID: {{id}}","plugin": "Plugin ID: {{id}}","device": "Device ID: {{id}}",- "member": "Member ID: {{id}}"+ "member": "Member ID: {{id}}",+ "group": "Group ID: {{id}}"},"expandLongMessage": "Show full message","collapseLongMessage": "Collapse",@@ -10560,7 +10561,9 @@"sourceNeverRan": "The original session hasn't run yet, so a new session can't be started","codexStateUnavailable": "The Codex session state is unavailable, so a new session can't be started. {{detail}}","generic": "Couldn't start a new session. Try again."- }+ },+ "groupSentNamed": "Sent from group “{{name}}”",+ "groupSent": "Sent from a group"},"threadContext": {"cindyFrom": "Cindy · from {{platform}}",@@ -14813,5 +14816,15 @@"detail": "This sets the plugin’s AI permission to Allow edits for future tasks too. A separate working directory is not a system sandbox; commands still follow Cindy permission checks. You can switch back to read-only in the plugin’s AI settings.","allow": "Allow and continue","cancel": "Not now"+ },+ "groupTools": {+ "authorizationRequired": "Group authorization has expired or does not allow this action. Ask the teammate owner to make a new request in this group.",+ "localPeersOnly": "Group messages can only target teammates on this device and account.",+ "ownerChanged": "The account changed. Please try again.",+ "invalidMessage": "The message or retry identifier is invalid.",+ "privateUnavailable": "This teammate’s private chat is unavailable. Please try again later.",+ "idempotencyConflict": "This retry identifier was already used for a different message.",+ "privateUnconfirmed": "Private message delivery is unconfirmed. Retry with the same identifier.",+ "verificationUnavailable": "Group authorization could not be verified. Try again when the connection recovers."}}diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 9c126d836e..3e4dccdbdd 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10515,7 +10515,8 @@"automation": "自動化 ID:{{id}}","plugin": "プラグイン ID:{{id}}","device": "デバイス ID:{{id}}",- "member": "メンバー ID:{{id}}"+ "member": "メンバー ID:{{id}}",+ "group": "グループ ID: {{id}}"},"expandLongMessage": "全文を表示","collapseLongMessage": "折りたたむ",@@ -10541,7 +10542,9 @@"sourceNeverRan": "元のセッションがまだ実行されていないため、新しいセッションを始められません","codexStateUnavailable": "Codex セッションの状態を利用できないため、新しいセッションを始められません。{{detail}}","generic": "新しいセッションを始められませんでした。再試行してください"- }+ },+ "groupSentNamed": "グループ「{{name}}」から送信",+ "groupSent": "グループから送信"},"threadContext": {"cindyFrom": "Cindy · {{platform}} から",@@ -14781,5 +14784,15 @@"autoTitle": "Auto 自動承認を有効化","autoMessage": "「{{name}}」で Auto 自動承認を使用しますか?","autoDetail": "主タスクと Worker の操作を Cindy が自動審査します。確認が必要な操作や拒否された操作は停止します。完全アクセスではありません。他のタスクの全体設定は変更しません。"+ },+ "groupTools": {+ "authorizationRequired": "グループの許可が失効したか、この操作は許可されていません。パートナーの所有者からこのグループで再度依頼してください。",+ "localPeersOnly": "グループからのメッセージは、この端末の同じアカウントのパートナーにのみ送信できます。",+ "ownerChanged": "アカウントが切り替わりました。もう一度お試しください。",+ "invalidMessage": "メッセージまたは再試行識別子が無効です。",+ "privateUnavailable": "このパートナーの個別チャットを利用できません。後でもう一度お試しください。",+ "idempotencyConflict": "この再試行識別子は別のメッセージに使用されています。",+ "privateUnconfirmed": "個別メッセージの配信は未確認です。同じ識別子で再試行してください。",+ "verificationUnavailable": "グループの権限を確認できませんでした。接続が回復してから再試行してください。"}}diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 06e1b845c0..177ea0e42b 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10515,7 +10515,8 @@"automation": "자동화 ID: {{id}}","plugin": "플러그인 ID: {{id}}","device": "기기 ID: {{id}}",- "member": "멤버 ID: {{id}}"+ "member": "멤버 ID: {{id}}",+ "group": "그룹 ID: {{id}}"},"expandLongMessage": "전체 메시지 보기","collapseLongMessage": "접기",@@ -10541,7 +10542,9 @@"sourceNeverRan": "원래 세션이 아직 실행되지 않아 새 세션을 시작할 수 없습니다","codexStateUnavailable": "Codex 세션 상태를 사용할 수 없어 새 세션을 시작할 수 없습니다. {{detail}}","generic": "새 세션을 시작하지 못했습니다. 다시 시도해 주세요"- }+ },+ "groupSentNamed": "그룹 「{{name}}」에서 보냄",+ "groupSent": "그룹에서 보냄"},"threadContext": {"cindyFrom": "Cindy · {{platform}}에서",@@ -14781,5 +14784,15 @@"autoTitle": "Auto 자동 승인 사용","autoMessage": "“{{name}}”에 Auto 자동 승인을 허용할까요?","autoDetail": "Cindy가 주 작업과 Worker 동작을 자동 심사합니다. 확인이 필요하거나 거부된 동작은 일시 중지됩니다. 전체 접근 권한이 아니며 다른 작업의 전역 권한은 변경하지 않습니다."+ },+ "groupTools": {+ "authorizationRequired": "그룹 권한이 만료되었거나 이 작업이 허용되지 않습니다. 파트너 소유자가 이 그룹에서 다시 요청해 주세요.",+ "localPeersOnly": "그룹에서는 이 기기의 같은 계정에 있는 파트너에게만 메시지를 보낼 수 있습니다.",+ "ownerChanged": "계정이 변경되었습니다. 다시 시도해 주세요.",+ "invalidMessage": "메시지 또는 재시도 식별자가 유효하지 않습니다.",+ "privateUnavailable": "이 파트너의 개인 채팅을 사용할 수 없습니다. 나중에 다시 시도해 주세요.",+ "idempotencyConflict": "이 재시도 식별자는 다른 메시지에 이미 사용되었습니다.",+ "privateUnconfirmed": "개인 메시지 전달이 확인되지 않았습니다. 같은 식별자로 다시 시도해 주세요.",+ "verificationUnavailable": "그룹 권한을 확인할 수 없습니다. 연결이 복구되면 다시 시도하세요."}}diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 97ca25c95d..1c6b34d726 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10515,7 +10515,8 @@"automation": "自动化 ID:{{id}}","plugin": "插件 ID:{{id}}","device": "设备 ID:{{id}}",- "member": "成员 ID:{{id}}"+ "member": "成员 ID:{{id}}",+ "group": "群聊 ID:{{id}}"},"expandLongMessage": "展开全文","collapseLongMessage": "收起",@@ -10541,7 +10542,9 @@"sourceNeverRan": "原任务尚未运行,无法开启新任务","codexStateUnavailable": "Codex Agent 会话状态不可用,无法开启新任务。{{detail}}","generic": "无法开启新任务,请重试"- }+ },+ "groupSentNamed": "从群聊「{{name}}」发送",+ "groupSent": "从群聊发送"},"threadContext": {"cindyFrom": "Cindy · 来自 {{platform}}",@@ -14781,5 +14784,15 @@"detail": "将此插件的 AI 权限设为“允许修改”,后续任务沿用此选择。独立作答目录不是系统沙箱;命令仍遵循 Cindy 的权限检查。你可以随时在插件 AI 设置中改回只读。","allow": "允许并继续","cancel": "暂不允许"+ },+ "groupTools": {+ "authorizationRequired": "群内授权已失效或不允许此操作,请由伙伴主人在当前群重新发起。",+ "localPeersOnly": "群内私聊只能发送给本机同账号伙伴。",+ "ownerChanged": "账号已经切换,请重试。",+ "invalidMessage": "消息或重试标识无效。",+ "privateUnavailable": "当前伙伴私聊不可用,请稍后重试。",+ "idempotencyConflict": "此重试标识已用于另一条消息。",+ "privateUnconfirmed": "私聊未确认送达,请使用同一重试标识重试。",+ "verificationUnavailable": "暂时无法核验群聊授权,请在连接恢复后重试。"}}diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 9162c4279e..4099674c19 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10514,7 +10514,8 @@"automation": "自動化 ID:{{id}}","plugin": "插件 ID:{{id}}","device": "裝置 ID:{{id}}",- "member": "成員 ID:{{id}}"+ "member": "成員 ID:{{id}}",+ "group": "群聊 ID:{{id}}"},"expandLongMessage": "展開全文","collapseLongMessage": "收起",@@ -10540,7 +10541,9 @@"sourceNeverRan": "原任務尚未執行,無法開啟新任務","codexStateUnavailable": "Codex Agent 會話狀態不可用,無法開啟新任務。{{detail}}","generic": "無法開啟新任務,請重試"- }+ },+ "groupSentNamed": "從群聊「{{name}}」傳送",+ "groupSent": "從群聊傳送"},"threadContext": {"cindyFrom": "Cindy · 來自 {{platform}}",@@ -14781,5 +14784,15 @@"autoTitle": "啟用 Auto 自動審批","autoMessage": "允許「{{name}}」使用 Auto 自動審批?","autoDetail": "主任務與 Worker 的操作將交由 Cindy 自動審批。需要人工確認或遭拒時仍會暫停;這不是完全存取。此選擇儲存到插件 AI 設定,不變更其他任務的全域權限。"+ },+ "groupTools": {+ "authorizationRequired": "群組授權已失效或不允許此操作,請由夥伴主人在目前群組重新發起。",+ "localPeersOnly": "群組內的私訊只能傳送給本機同帳號夥伴。",+ "ownerChanged": "帳號已切換,請重試。",+ "invalidMessage": "訊息或重試識別碼無效。",+ "privateUnavailable": "目前夥伴的私聊無法使用,請稍後重試。",+ "idempotencyConflict": "此重試識別碼已用於另一則訊息。",+ "privateUnconfirmed": "尚未確認私訊送達,請使用相同的重試識別碼重試。",+ "verificationUnavailable": "暫時無法核驗群聊授權,請在連線恢復後重試。"}}diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex 1a6eccb615..3f295ea8ee 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -8,6 +8,7 @@ import type { ReviewRunMeta } from '../../shared/reviewRun';import type { AgentTaskTerminalStatus } from '@cindy/maker-shared/agent-task';import type {MessageSourceDevice,+ MessageSourceGroup,MessageSourcePlugin,} from '@cindy/maker-shared/message-source';import type { ToolLoopErrorDetails } from '@cindy/maker-core';@@ -192,6 +193,10 @@ export interface CcMeta {sourceDevice?: MessageSourceDevice;/** 插件任务派发的消息(readMessageSourcePlugin 读取)。 */sourcePlugin?: MessageSourcePlugin;+ /** Group source of an explicitly sent private assistant message. */+ sourceGroup?: MessageSourceGroup;+ /** Guest-safe independent assistant delivery; does not seal a model turn. */+ explicitDelivery?: boolean;/** 历史 per-turn USD;新数据以 turnCost 为区域金额事实。 */turnCostUsd?: number;diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex c409b2ce13..a42226824b 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -83,8 +83,10 @@ import type { AgentMeta, MessageRole, Message, MessageAutomationOrigin } from '@import { toMessageAutomationOrigin } from '@/lib/messageAutomationOrigin';import {readMessageSourceDevice,+ readMessageSourceGroup,readMessageSourcePlugin,type MessageSourceDevice,+ type MessageSourceGroup,type MessageSourcePlugin,} from '@cindy/maker-shared/message-source';import {@@ -502,6 +504,10 @@ export interface ChatMessage {sourceDevice?: MessageSourceDevice;/** 插件任务派发的消息来源(读自 agentMeta.sourcePlugin)。 */sourcePlugin?: MessageSourcePlugin;+ /** Group source of an explicitly sent private assistant message. */+ sourceGroup?: MessageSourceGroup;+ /** Host-stamped delivery remains visible after source identity is redacted. */+ explicitDelivery?: boolean;/** user 消息投递方式:普通新 turn 或运行中 steer。 */delivery?: 'turn' | 'steer';/** Hook 来源元数据(IM 平台 + 用户干净原文 + thread 上下文),UserMessage 据此渲染 Cindy 任务卡片。 */@@ -18833,6 +18839,8 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {clientId: m.clientId,role: m.role,content: typeof m.content === 'string' ? m.content : JSON.stringify(m.content),+ ...(m.role === 'assistant' ? { sourceGroup: readMessageSourceGroup(m.agentMeta) } : {}),+ ...(m.role === 'assistant' && m.agentMeta?.explicitDelivery === true ? { explicitDelivery: true } : {}),...(m.role === 'assistant' ? { botLearning: m.agentMeta?.botLearning } : {}),...(m.agentMeta?.botPrivateReply === true ? { botPrivateReply: true } : {}),...(m.role === 'assistant' && m.agentMeta?.turnCompleted === truediff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.tsindex 471246b84f..ecb57fec45 100644--- a/apps/desktop/src/shared/agentInputQueue.ts+++ b/apps/desktop/src/shared/agentInputQueue.ts@@ -244,7 +244,11 @@ export interface RecoveryCheckpoint {}>;}+/** Same-process model source prefix; cannot be supplied by JSON or survive queue persistence. */+export const HOST_ONLY_AGENT_PREFIX = Symbol('host-only-agent-prefix');+export interface AgentInputQueuedMessage {+ [HOST_ONLY_AGENT_PREFIX]?: string;/** Host-stamped attribution, retained in durable queue snapshots and messages. */sharedTaskAuthor?: SharedTaskAuthor;/** Host-captured authored text before plugin/reference decoration; omitted from wire projections. */@@ -593,7 +597,7 @@ export function sanitizeQueuedMessageForPersistence(// Historical plain-text queue payloads have no embedded reference bodies.}- if (!changed && !item.trustedSessionReferenceContexts) return item;+ if (!changed && !item.trustedSessionReferenceContexts && item[HOST_ONLY_AGENT_PREFIX] === undefined) return item;const sanitized: AgentInputQueuedMessage = {...item,persistedContent,@@ -603,6 +607,7 @@ export function sanitizeQueuedMessageForPersistence(? { sessionReferencesRequireTrustedSnapshot: true }: {}),};+ delete sanitized[HOST_ONLY_AGENT_PREFIX];if (!item.agentReferences) delete sanitized.agentReferences;if (item.trustedSessionReferenceContexts) delete sanitized.trustedSessionReferenceContexts;return sanitized;@@ -629,8 +634,9 @@ export function updateQueuedMessageText(newText: string,sessionRefs: AgentInputSessionRef[] = reconcileSessionRefsForText(newText, entry.sessionRefs),): AgentInputQueuedMessage {- // A plugin rewrite must not turn a hidden host welcome into an editable user draft.- if (entry.toolsDisabled === true && entry.text.startsWith(UI_ACTION_TRIGGER_PREFIX)+ // A plugin rewrite must not turn a hidden host message into an editable user draft.+ if ((entry.toolsDisabled === true || entry.agentOmitsTriggerPrefix === true)+ && entry.text.startsWith(UI_ACTION_TRIGGER_PREFIX)&& !newText.startsWith(UI_ACTION_TRIGGER_PREFIX)) {newText = `${UI_ACTION_TRIGGER_PREFIX}${newText}`;}@@ -1100,9 +1106,11 @@ export function buildMakerUserMessage(const blocks: Array<{ type: string; [k: string]: unknown }> = [];const facingText = getAgentFacingText(queued);// 主机内部消息只在排队行 / 历史里需要隐藏前缀;发给模型的正文不带它。- const agentFacingText = queued.agentOmitsTriggerPrefix === true && facingText.startsWith(UI_ACTION_TRIGGER_PREFIX)+ const authoredText = queued.agentOmitsTriggerPrefix === true && facingText.startsWith(UI_ACTION_TRIGGER_PREFIX)? 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;if (agentFacingText.length > 0) {blocks.push({ type: 'text', text: agentFacingText });}diff --git a/apps/mobile/src/__tests__/companionConversationPresentation.test.ts b/apps/mobile/src/__tests__/companionConversationPresentation.test.tsindex f90182db2c..b7e367501d 100644--- a/apps/mobile/src/__tests__/companionConversationPresentation.test.ts+++ b/apps/mobile/src/__tests__/companionConversationPresentation.test.ts@@ -1,3 +1,4 @@+import { redactMessageRowForSharedGuest } from '../../../desktop/src/main/device-link/sharedTaskMessageOrigin';import { HISTORY_GAP_SPLIT_MS } from '@cindy/maker-shared/history-gap';import { expect, it } from 'vitest';import { buildMobileMessageRenderItems } from '../session/messageRenderModel';@@ -133,3 +134,26 @@ it('attaches exact frozen results to their final reply across reload and keeps uexpect(bodies([input[0], row('a6', 'assistant', 'Other reply', { turnCompleted: true })], false).some(item => item.type === 'message' && item.message.companion)).toBe(true);});++it('keeps explicit group private deliveries while the private model works and after later replies', () => {+ const messages = [row('g1', 'assistant', 'Group delivery', { sourceGroup: { groupId: 'g-1' } }), ...base];+ const text = (rows: RemoteMessage[], running: boolean) => bodies(rows, running)+ .filter(item => item.type === 'message').map(item => item.message.body);+ expect(text(messages, true)).toContain('Group delivery');+ expect(text([...messages, row('a4', 'assistant', 'Answer', { turnCompleted: true })], false)).toContain('Group delivery');+});++it.each([true, false])('keeps guest-safe explicit delivery without sealing adjacent progress (running=%s)', (running) => {+ const messages = [row('u0', 'user', 'Help'), row('a1', 'assistant', 'Before'),+ row('g2', 'assistant', 'Private delivery', { sourceGroup: { groupId: 'private-group', name: 'Secret group' } }),+ row('a3', 'assistant', 'After'),+ row('t4', 'tool_use', { toolName: 'Read', toolUseId: 't4', input: {} }),+ ...(!running ? [row('a5', 'assistant', 'Final reply', { turnCompleted: true })] : []),+ ].map(redactMessageRowForSharedGuest);+ expect(messages[2].agentMeta).toEqual({ explicitDelivery: true });+ expect(JSON.stringify(messages)).not.toMatch(/private-group|Secret group/);+ const text = bodies(messages, running).filter(item => item.type === 'message').map(item => item.message.body);+ expect(text).toContain('Private delivery');+ expect(text).not.toContain('Before');+ expect(text).not.toContain('After');+});diff --git a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsxindex 9ae653145a..08757b6650 100644--- a/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx+++ b/apps/mobile/src/__tests__/messageSourceLabelsRender.test.tsx@@ -486,3 +486,16 @@ describe("source labels reveal their ids on long press", () => {expect(html).not.toMatch(/data-testid="message.automationOrigin"[^>]*data-hint/);});});++describe('private group reply source', () => {+ it('renders the host group name and id on assistant replies after remote normalization', () => {+ const html = render([{ ...msg('group-private', 'Private reply', {+ sourceGroup: { groupId: 'g-1', name: 'Design' },+ origin: { kind: 'session', senderSessionId: 'lane', senderBotId: 'bot-1' },+ }), role: 'assistant' }]);+ expect(html).toContain('从群聊「Design」发送');+ expect(html).toContain('群聊 ID:g-1');+ expect(html).toContain('message.groupSource');+ expect(render([{ ...msg('ordinary', 'Private', null), role: 'assistant' }])).not.toContain('message.groupSource');+ });+});diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex b70a112ef8..60b991a1cd 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -164,7 +164,10 @@"retryToolInput": "Couldn't load input. Retry","toolResultCompacted": "Full tool output was trimmed (original size {{size}})","mermaidEmpty": "Empty Mermaid diagram.",- "diffEditCount": "{{n}} edits"+ "diffEditCount": "{{n}} edits",+ "groupSentNamed": "Sent from group “{{name}}”",+ "groupSent": "Sent from a group",+ "sourceGroupId": "Group ID: {{id}}"},"actions": {"attachmentsPrefix": "Attachments: {{names}}",diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.jsonindex a901f7114f..02f6e1f62e 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -164,7 +164,10 @@"retryToolInput": "入力を読み込めませんでした。再試行","toolResultCompacted": "ツールの完全な出力は解放されました(元のサイズ:{{size}})","mermaidEmpty": "空の Mermaid 図。",- "diffEditCount": "{{n}} 件の編集"+ "diffEditCount": "{{n}} 件の編集",+ "groupSentNamed": "グループ「{{name}}」から送信",+ "groupSent": "グループから送信",+ "sourceGroupId": "グループ ID: {{id}}"},"actions": {"attachmentsPrefix": "添付ファイル:{{names}}",diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex 2ccbd7f258..983af06482 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -164,7 +164,10 @@"retryToolInput": "입력을 불러오지 못했습니다. 다시 시도","toolResultCompacted": "전체 도구 출력이 해제되었습니다(원래 크기 {{size}})","mermaidEmpty": "빈 Mermaid 다이어그램.",- "diffEditCount": "{{n}}개 편집"+ "diffEditCount": "{{n}}개 편집",+ "groupSentNamed": "그룹 「{{name}}」에서 보냄",+ "groupSent": "그룹에서 보냄",+ "sourceGroupId": "그룹 ID: {{id}}"},"actions": {"attachmentsPrefix": "첨부파일: {{names}}",diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.jsonindex 8f9a5e39b8..6547f6b736 100644--- a/apps/mobile/src/i18n/locales/zh-CN/message.json+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json@@ -164,7 +164,10 @@"retryToolInput": "读取失败,重试","toolResultCompacted": "完整工具输出已释放(原始大小 {{size}})","mermaidEmpty": "空 Mermaid 图表。",- "diffEditCount": "{{n}} 处编辑"+ "diffEditCount": "{{n}} 处编辑",+ "groupSentNamed": "从群聊「{{name}}」发送",+ "groupSent": "从群聊发送",+ "sourceGroupId": "群聊 ID:{{id}}"},"actions": {"attachmentsPrefix": "附件:{{names}}",diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.jsonindex dabbcb0f62..a720abbd52 100644--- a/apps/mobile/src/i18n/locales/zh-TW/message.json+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json@@ -164,7 +164,10 @@"retryToolInput": "讀取失敗,重試","toolResultCompacted": "完整工具輸出已釋放(原始大小 {{size}})","mermaidEmpty": "空 Mermaid 圖表。",- "diffEditCount": "{{n}} 處編輯"+ "diffEditCount": "{{n}} 處編輯",+ "groupSentNamed": "從群聊「{{name}}」傳送",+ "groupSent": "從群聊傳送",+ "sourceGroupId": "群聊 ID:{{id}}"},"actions": {"attachmentsPrefix": "附件:{{names}}",diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex f3a848e0f8..22232a8ee7 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -3902,6 +3902,16 @@ function MessageBubble({testID="message.sharedAuthor"/>) : null}+ {item.message.kind === 'assistant' && item.message.sourceGroup ? (+ <SourceLabelWithId+ align="agent"+ label={item.message.sourceGroup.name+ ? t('message.renderer.groupSentNamed', { name: item.message.sourceGroup.name })+ : t('message.renderer.groupSent')}+ idText={t('message.renderer.sourceGroupId', { id: item.message.sourceGroup.groupId })}+ testID="message.groupSource"+ />+ ) : null}{automationOrigin ? (// 自动化任务注入的消息:气泡上方渲来源标签(对齐桌面;手机版暂不做// 点击跳转自动化页)。共享任务访客的脱敏来源没有名字与 ID,显示通用文案。diff --git a/apps/mobile/src/session/companionConversationPresentation.ts b/apps/mobile/src/session/companionConversationPresentation.tsindex a291ca57fc..8de2f09dcc 100644--- a/apps/mobile/src/session/companionConversationPresentation.ts+++ b/apps/mobile/src/session/companionConversationPresentation.ts@@ -70,7 +70,7 @@ export function companionConversationItems(items: readonly MobileMessageRenderIt}if (message.systemCardType) return true;if (message.kind === 'thinking' || message.kind === 'tool') return false;- return message.kind !== 'assistant' || message.turnCompleted || sealed.has(item.key) || isDelivery(item)+ return message.kind !== 'assistant' || Boolean(message.sourceGroup) || message.explicitDelivery || message.turnCompleted || sealed.has(item.key) || isDelivery(item)|| message.isTurnFinalAssistant && !deliveredAfter.has(item.key);});}diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.tsindex f8401f6c50..c1814c099e 100644--- a/apps/mobile/src/session/messageNormalize.ts+++ b/apps/mobile/src/session/messageNormalize.ts@@ -25,9 +25,11 @@ import { isSyntheticTriggerText } from '@cindy/maker-shared/synthetic-trigger';import {isHookSchedulerOrigin,readMessageSourceDevice,+ readMessageSourceGroup,readMessageSourcePlugin,sanitizeSourceName,type MessageSourceDevice,+ type MessageSourceGroup,type MessageSourcePlugin,} from '@cindy/maker-shared/message-source';import { sharedTaskAuthorMemberId, sharedTaskAuthorName } from '@cindy/maker-shared';@@ -160,6 +162,10 @@ export interface NormalizedRemoteMessage {sourceDevice?: MessageSourceDevice;/** user 专用:插件任务派发的消息(agentMeta.sourcePlugin);与本轮插件调用头(pluginInvocations)无关。 */sourcePlugin?: MessageSourcePlugin;+ /** Group source of an explicitly sent private assistant message. */+ sourceGroup?: MessageSourceGroup;+ /** Host-stamped delivery remains visible after source identity is redacted. */+ explicitDelivery?: boolean;/** user 专用:共享任务成员发送的消息作者名(agentMeta.sharedTaskAuthor);气泡上方标签。 */sharedAuthorName?: string;/** 共享任务成员 id(作者标签长按显示,与模型 `[消息来源]` 的 member_id 同源)。 */@@ -570,6 +576,8 @@ export function normalizeRemoteMessages(: {}),...turnCost,...readModelMismatch(message),+ ...(message.role === 'assistant' ? { sourceGroup: readMessageSourceGroup(message.agentMeta) } : {}),+ ...(message.role === 'assistant' && message.agentMeta?.explicitDelivery === true ? { explicitDelivery: true } : {}),...(message.role === 'user' ? readAutomationOrigin(message) : {}),...(message.role === 'user' ? readSessionOrigin(message) : {}),...(message.role === 'user' ? readMessageSourceFields(message) : {}),diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex ebc5fff8e3..8dc6f22b6a 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -101,7 +101,8 @@- 伙伴本轮最终的回复文本即它在群里的消息。回复为空或恰好是 `NO_REPLY` 表示本轮不发言,群里不显示任何内容。- 伙伴本轮可以照常使用记忆、Skill 与工具,按伙伴主任务的权限档执行;需要用户确认的操作在群里提示。- 群专线不开放 `start_session_task`、`send_to_agent`、例行任务和创建伙伴;需要几位伙伴依次干活时走第 7 节的分工。+ Chat Server 群专线的独立任务与私聊能力按第 10 节核验当前执行授权;例行任务和创建伙伴不因此开放。+ 需要几位伙伴依次干活时走第 7 节的分工。### 4.4 插话、停止与失败@@ -259,6 +260,14 @@ Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授群权限必须约束实际上下文和工具执行,不能只靠提示词。群专线按授权种类与版本隔离;未获私人授权的专线不加载主人记忆、私人 Profile/Home 和已学 Skill,并使用引擎工具禁用门禁。撤回、离群、移除和执行租约失效后停止执行,拒绝旧结果。主人离群时其伙伴也退出,重新加入不继承旧授权。+群专线的 `role=group` 是来源身份,不等于只读历史任务,也不单独构成授权。读取自己的 Profile、能力与 Skill 目录时,必须核对活跃执行、伙伴归属、成员状态、授权版本及执行租约;只聊天的专线仍不可读取私人资料。群主身份不能替代伙伴主人身份。++只有伙伴主人发起且当前授权有效的执行,才能从群里启动独立开发任务或发送私聊。独立任务保留群内调用身份与来源范围,沿用普通任务的权限档、审批、隔离目录和工作目录注册。任务卡、待确认事项和结果回到**该主人与该伙伴的私聊**;工具返回 `completion_destination=teammate-private-chat`,伙伴须告知去向。非主人获得的群工具授权不包含此独立任务能力。群内只能查询或控制由同一授权专线创建的独立任务;主人仍可从私聊管理已启动的任务。群执行结束不会取消已经正式启动的独立任务,后续群内操作必须重新验证当前执行。++非主人群工具授权仅允许读取伙伴自身资料、已选能力和自己的技能;应用级能力目录与默认模型查询仍须当前主人执行授权。++`send_to_user` 由宿主定位当前伙伴主人与该伙伴的私聊,写入有来源标记的伙伴消息(桌面与手机显示宿主盖章的群名及群 ID,分享图片与共享访客不泄露来源),不唤醒模型、不接受任意账号或收件人参数;重复提交同一标识只返回原消息凭据,不宣称已读。`send_to_agent` 从群发起时仅允许同设备同账号的其他伙伴,在投递元数据及模型信封中保留群专线来源,回信沿用发起伙伴与主人的私聊,不自动投回原群;不能用发送给自己代替给主人私聊。普通任务和伙伴原有私聊发送规则不变。新调用在撤权、换账号、旧执行结束或重启后均须重新取得当前执行授权,不能凭持久化专线记录复活旧权限。+每次启动或恢复专线时,服务端分工从本机 `sessions.working_dir` 读取创建专线时登记的目录,目录不可用就失败,不依赖旧 `bot_group_plans` 行或回退伙伴 Home。仅聊天授权先于分工目录解析,始终使用与创建期相同的账号/伙伴/授权专线隔离目录和 `dialogue` 类型;即使旧本地计划存在同名 ID,也不能取得其项目目录。创建事务到启动期的回归见 `botGroupLaneTx.test.ts`,旧本地计划目录校验见 `botWorkspaceRuntimePlan.test.ts`。群主可以是伙伴,主人可代该伙伴管理群;最后群主不能直接退出。个人账号资料、群内昵称、群角色与伙伴归属是四个不同字段,禁止互相覆盖。群内昵称只由本人/伙伴主人修改;个人头像与名字走既有账号服务,Chat Server 只保存受认证的显示投影。diff --git a/docs/product-rules/message-source.md b/docs/product-rules/message-source.mdindex eaa3e03e7d..69c24c3c48 100644--- a/docs/product-rules/message-source.md+++ b/docs/product-rules/message-source.md@@ -14,11 +14,11 @@## 数据- 沿用既有字段:`origin`(scheduler / session / orca)、`imSource`、`hookSource`、- `sharedTaskAuthor`;新增 `sourceDevice`、`sourcePlugin`。+ `sharedTaskAuthor`;新增 `sourceDevice`、`sourcePlugin`;群内显式发给主人的私聊消息使用 `sourceGroup` 保存群名与 ID,桌面和手机的 assistant 消息均显示此来源。- 新数据**不进** `origin`:多处 host 逻辑把任何 `origin.kind` 当作非人工派发。- 全部只用于归属展示,**不是**权限或信任判据;wire 传入的同名字段一律丢弃,由 host 重写。- 共享任务访客收到脱敏后的数据:任务来源去掉 id 与标题,自动化只保留「由自动化发送」,- 不下发设备与插件来源。+ 不下发设备、插件与群聊来源。群来源私聊脱敏后只保留不含身份的 `explicitDelivery` 可见性标记;它不代表主任务模型轮次结束,不封存相邻过程正文。- 共享读写与说明构造在 `packages/maker-shared/src/messageSource.ts`。## 发给模型的说明diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.tsindex 7be459c4d4..fcf064123e 100644--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts@@ -282,6 +282,7 @@ describe("cindy_helper MCP server", () => {delegationId: "session-task-1",childSessionId: "desktop-child-session",status: "running",+ completionDestination: 'teammate-private-chat',deadlineAt: 1_788_000_000_000,}));const messageSessionTask = vi.fn(async () => ({@@ -365,6 +366,7 @@ describe("cindy_helper MCP server", () => {expect(sessionTask).toMatchObject({ok: true,action: "start_session_task",+ completion_destination: 'teammate-private-chat',task_id: "session-task-1",session_id: "desktop-child-session",deadline_at: 1_788_000_000_000,@@ -698,6 +700,28 @@ describe("cindy_helper MCP server", () => {}});+ it('binds send_to_user to the current lane without accepting an arbitrary recipient', async () => {+ const sendToUser = vi.fn(async () => ({ ok: true as const, messageId: 'saved', targetSessionId: 'owner-private', delivered: true }));+ const messageAgent = vi.fn(async () => ({ ok: false as const, errorCode: 'UNEXPECTED', message: 'must not run' }));+ const server = createXdtHelperMcpServer({ resolveSurface: async () => 'bot', botMessaging: { sendToUser, messageAgent } },+ { agentKind: 'codex', workingDir: '/fixture', sessionId: 'group-lane' });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ const client = new Client({ name: 'group-private-message', version: '0.0.0' });+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);+ try {+ const catalog = parsePayload(await client.callTool({ name: 'list_tools', arguments: { category: 'bots' } }));+ expect(JSON.stringify(catalog)).toContain('send_to_user');+ const result = parsePayload(await client.callTool({ name: 'call_tool', arguments: { name: 'send_to_user',+ args: { message: 'Owner reply', idempotency_key: 'request-123', target_id: 'another-account' } } }));+ expect(result).toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });+ expect(sendToUser).not.toHaveBeenCalled();+ const valid = parsePayload(await client.callTool({ name: 'call_tool', arguments: { name: 'send_to_user', args: { message: 'Owner reply', idempotency_key: 'request-123' } } }));+ expect(valid).toMatchObject({ ok: true, delivered: true, read: null, session_id: 'owner-private' });+ expect(sendToUser).toHaveBeenCalledWith({ callerSessionId: 'group-lane', message: 'Owner reply', idempotencyKey: 'request-123' });+ expect(messageAgent).not.toHaveBeenCalled();+ } finally { await client.close(); await server.close(); }+ });+it.each(["default", "restricted", "error", "unbound"] as const)("hides and blocks all companion commands on %s surface", async (surface) => {const callback = vi.fn(async () => ({ ok: false as const, errorCode: "UNEXPECTED", message: "must not run" }));const server = createXdtHelperMcpServer({@@ -706,7 +730,7 @@ describe("cindy_helper MCP server", () => {return surface === "unbound" ? "bot" : surface;},sessionTasks: { startSessionTask: callback, getSessionTask: callback, messageSessionTask: callback, stopSessionTask: callback },- botMessaging: { messageAgent: callback, checkMessage: callback },+ botMessaging: { messageAgent: callback, checkMessage: callback, sendToUser: callback },botProfiles: { create: callback },}, { agentKind: "codex", workingDir: "/repo", sessionId: surface === "unbound" ? undefined : "normal-session" });const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();@@ -716,7 +740,7 @@ describe("cindy_helper MCP server", () => {expect((await client.listTools()).tools.map((tool) => tool.name).sort()).toEqual(["call_tool", "list_tools"]);const discovery = parsePayload(await client.callTool({ name: "list_tools", arguments: { category: "bots" } }));expect(discovery).toMatchObject({ ok: false, errorCode: "CAPABILITY_NOT_AVAILABLE" });- for (const name of ["start_session_task", "check_session_task", "message_session_task", "stop_session_task", "send_to_agent", "check_agent_message", "create_teammate"]) {+ for (const name of ["start_session_task", "check_session_task", "message_session_task", "stop_session_task", "send_to_agent", "send_to_user", "check_agent_message", "create_teammate"]) {const result = parsePayload(await client.callTool({ name: "call_tool", arguments: { name, args: {} } }));expect(result).toMatchObject({ ok: false, errorCode: "CAPABILITY_NOT_AVAILABLE" });}diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex 8858f6719e..7332f38002 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -172,6 +172,9 @@ interface SessionTaskCallbacks {}interface BotMessagingCallbacks {+ sendToUser?(params: { callerSessionId: string; message: string; idempotencyKey: string }): Promise<+ { ok: true; messageId: string; targetSessionId: string; delivered: boolean }+ | { ok: false; errorCode: string; message: string }>;checkMessage?(params: { callerSessionId: string; messageId: string }): Promise<{ ok: true } | { ok: false; errorCode: string; message: string }>;listAgents?(params: { callerSessionId: string;@@ -402,8 +405,11 @@ function registerStartSessionTaskEntry(status: result.status,deadline_at: result.deadlineAt,expects_result: true,+ ...(result.completionDestination ? { completion_destination: result.completionDestination } : {}),guidance:- "The task card tracks progress and the result will return automatically. Do not start it again. Treat model_route and task/session ids as internal bookkeeping; do not echo them or the delegated instruction in ordinary replies unless the user asks for these details.",+ (result.completionDestination === 'teammate-private-chat'+ ? 'Tell the owner that the task card, permission/questions, and final result will appear in their private chat with this teammate. '+ : '') + "The task card tracks progress and the result will return automatically. Do not start it again. Treat model_route and task/session ids as internal bookkeeping; do not echo them or the delegated instruction in ordinary replies unless the user asks for these details.",}): errorPayload(result.errorCode, result.message);},@@ -417,6 +423,18 @@ function registerSendToAgentEntry(sessionCtx: XdtHelperMcpSessionCtx,): void {if (!deps.botMessaging) return;+ if (deps.botMessaging.sendToUser) registry.register({+ name: 'send_to_user', category: 'bots',+ description: 'From a group, send a private message to your owner in this same teammate’s main chat. Use when your owner explicitly asks for a private reply. The host resolves the recipient; this does not call yourself, wake another model, or message an arbitrary group member. Other members’ group tool grants do not authorize this action. In the main private chat, reply normally. Reuse idempotency_key when retrying the same message. A saved receipt does not mean the user has read it.',+ inputShape: { message: z.string().trim().min(1).max(16000), idempotency_key: z.string().regex(/^[\w-]{8,100}$/) },+ handler: async ({ message, idempotency_key }) => {+ const callerSessionId = resolveLiziMcpSessionContext(sessionCtx).sessionId;+ if (!callerSessionId) return errorPayload('NOT_A_BOT_SESSION', '当前调用未绑定伙伴任务。');+ const result = await deps.botMessaging!.sendToUser!({ callerSessionId, message, idempotencyKey: idempotency_key });+ return result.ok ? okPayload({ action: 'send_to_user', message_id: result.messageId, session_id: result.targetSessionId,+ delivered: result.delivered, read: null }) : errorPayload(result.errorCode, result.message);+ },+ });if (deps.botMessaging.checkMessage) registry.register({name: 'check_agent_message', category: 'bots',description: 'Check your own remote message: read native acceptance receipts or ordinary replies from an older teammate conversation. Use the message_id returned by send_to_agent when its transport is remote-conversation, or after uncertain delivery. This does not send or retry. It returns native acceptance or persisted ordinary reply text, not proof of engine delivery, a remote tool call, or a completed turn. Check when following up; do not poll.',diff --git a/packages/maker-shared/src/__tests__/messageSource.test.ts b/packages/maker-shared/src/__tests__/messageSource.test.tsindex 59f2b611f8..d7d8e0abcf 100644--- a/packages/maker-shared/src/__tests__/messageSource.test.ts+++ b/packages/maker-shared/src/__tests__/messageSource.test.ts@@ -8,6 +8,7 @@ import {promptSafeSourceName,messageSourceSenderFromMeta,readMessageSourceDevice,+ readMessageSourceGroup,readMessageSourcePlugin,sanitizeSourceName,shouldShowSourceDevice,@@ -233,3 +234,13 @@ describe('buildClientDeviceNote', () => {expect(buildClientDeviceNote(device)).toBe(buildClientDeviceNote(device));});});++describe('private group reply provenance', () => {+ it('shares sanitized group facts between UI and model handoff attribution', () => {+ const meta = { sourceGroup: { groupId: 'group-1', name: 'Design\nRoom' },+ origin: { kind: 'session', senderSessionId: 'lane-1', senderBotId: 'bot-1', senderBotName: 'Helper' } };+ expect(readMessageSourceGroup(meta)).toEqual({ groupId: 'group-1', name: 'Design Room' });+ expect(describeMessageSourceSender(messageSourceSenderFromMeta(meta)!)).toContain('从群聊「Design Room」(group_id: group-1)');+ expect(readMessageSourceGroup({ sourceGroup: { name: 'No identity' } })).toBeUndefined();+ });+});diff --git a/packages/maker-shared/src/messageSource.ts b/packages/maker-shared/src/messageSource.tsindex 99256a9a8c..a922718f97 100644--- a/packages/maker-shared/src/messageSource.ts+++ b/packages/maker-shared/src/messageSource.ts@@ -32,6 +32,20 @@ export interface MessageSourcePlugin {name?: string;}+/** Host-stamped group source of an explicitly sent private assistant message. */+export interface MessageSourceGroup {+ groupId: string;+ name?: string;+}++export function readMessageSourceGroup(meta: unknown): MessageSourceGroup | undefined {+ const raw = asRecord(asRecord(meta)?.sourceGroup);+ const groupId = raw && readString(raw, 'groupId');+ if (!groupId) return undefined;+ const name = sanitizeSourceName(raw?.name);+ return { groupId, ...(name ? { name } : {}) };+}+export type MessageSourceSender =| {kind: 'session';@@ -39,6 +53,7 @@ export type MessageSourceSender =title?: string;botId?: string;botName?: string;+ group?: MessageSourceGroup;}| { kind: 'plugin'; pluginId: string; name?: string }| { kind: 'shared-member'; memberId: string; name?: string };@@ -174,8 +189,10 @@ export function messageSourceSenderFromMeta(meta: unknown): MessageSourceSenderconst title = readString(origin, 'senderSessionTitle');const botId = readString(origin, 'senderBotId');const botName = readString(origin, 'senderBotName');+ const group = readMessageSourceGroup(record);return {kind: 'session',+ ...(group ? { group } : {}),...(sessionId ? { sessionId } : {}),...(title ? { title } : {}),...(botId ? { botId, ...(botName ? { botName } : {}) } : {}),@@ -235,7 +252,8 @@ export function describeMessageSourceSender(sender: MessageSourceSender): stringconst bot = formatSourceRef(sender.botName, 'bot_id', sender.botId);const sessionId = sanitizeSourceId(sender.sessionId);const via = sessionId ? ` 通过任务 (session_id: ${sessionId})` : '';- return `由伙伴${bot}${via} 发送`;+ const group = sender.group ? ` 从群聊${formatSourceRef(sender.group.name, 'group_id', sender.group.groupId)}` : '';+ return `由伙伴${bot}${group}${via} 发送`;}const ref = formatSourceRef(sender.title, 'session_id', sender.sessionId);return ref ? `由任务${ref} 发送` : '由其他任务发送';