Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 群回复不再 5 分钟硬切断,群里开的任务住在群里
Chrisad846f76a5d9
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 2c2e4dc53d..a39cdc91f3 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -3857,6 +3857,8 @@ describe('Bot Session task end-to-end runtime', () => {onResultReceiptPersisted?: () => Promise<void>;onCompletionDispatched?: () => Promise<void>;onInteractionDispatched?: () => Promise<void>;+ /** The group message channel for tasks started from a group (bot-group-chat.md §10). */+ postGroupTaskMessage?: Parameters<typeof createBotDelegationService>[0]['postGroupTaskMessage'];} = {}) {const accountReady = options.accountReady ?? (() => true);const started: StartedTurn[] = [];@@ -4071,6 +4073,7 @@ describe('Bot Session task end-to-end runtime', () => {const closeSession = vi.fn(options.closeSession ?? (async () => undefined));const delegation = createBotDelegationService({maxActiveChildren: options.maxActiveChildren,+ postGroupTaskMessage: options.postGroupTaskMessage,readSessionExecution: options.readSessionExecution,collectArtifacts: options.collectArtifacts,discardDelegationQueuedInputs: options.discardDelegationQueuedInputs ?? (coordinator@@ -4212,24 +4215,38 @@ describe('Bot Session task end-to-end runtime', () => {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 () => {+ it('starts owner-authorized group work in the group: card, result and no private-chat wake-up', 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 });+ const postGroupTaskMessage = vi.fn(async (input: { clientId: string }) => ({ ok: true as const, messageId: `posted:${input.clientId}` }));+ const runtime = createDelegationRuntime({ readCallerPermission, postGroupTaskMessage });try {const result = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture-only development task' });- expect(result).toMatchObject({ ok: true, completionDestination: 'teammate-private-chat' });+ expect(result).toMatchObject({ ok: true, completionDestination: 'group' });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');+ // The lane that started the task stays its parent; no private chat is created or re-used.+ expect(row.parent_session_id).toBe('group-lane');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' });+ expect(h.sqlite!.prepare('SELECT session_id FROM messages WHERE client_id=?').get(`bot-delegation-request:${result.delegationId}`)).toEqual({ session_id: 'group-lane' });+ // The group got the card as the teammate's own message, with the lane as the live-status parent.+ expect(postGroupTaskMessage).toHaveBeenCalledWith(expect.objectContaining({+ groupId: 'fixture', botId: 'bot-a', clientId: `bot-delegation-task:${result.delegationId}:started`, text: '',+ card: expect.objectContaining({ namespace: 'cindy.task', data: expect.objectContaining({ state: 'started',+ meta: expect.objectContaining({ role: 'delegation-request', delegationId: result.delegationId, parentSessionId: 'group-lane' }) }) }),+ }));await runtime.runPendingTurns();- expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === 'session-1')).toBe(true);+ // The result returns to the group, not to the owner's private chat, and wakes no lane.+ expect(postGroupTaskMessage).toHaveBeenLastCalledWith(expect.objectContaining({+ groupId: 'fixture', clientId: `bot-delegation-task:${result.delegationId}:1:result`, text: `${result.childSessionId} 的结论。`,+ card: expect.objectContaining({ data: expect.objectContaining({ state: 'completed' }) }),+ }));+ expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === 'session-1' || params.targetSessionId === 'group-lane')).toBe(false);+ expect(h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id=?').pluck().get(result.delegationId)).not.toBeNull();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 () => {} });@@ -4252,7 +4269,7 @@ describe('Bot Session task end-to-end runtime', () => {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' });+ expect(task).toMatchObject({ ok: true, status: 'queued', completionDestination: 'group' });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 (?, ?, ?, ?, ?, ?)')@@ -4269,7 +4286,9 @@ describe('Bot Session task end-to-end runtime', () => {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();+ // Without a group channel the result still reaches the owner, in the private chat.expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === 'session-1')).toBe(true);+ expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === 'group-lane')).toBe(false);} finally { release(); runtime.dispose(); vi.useRealTimers(); }});@@ -4307,7 +4326,9 @@ describe('Bot Session task end-to-end runtime', () => {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();+ // Without a group channel the result still reaches the owner, in the private chat.expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === 'session-1')).toBe(true);+ expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === 'group-lane')).toBe(false);} finally { h.tx = originalTx; release(); runtime.dispose(); vi.useRealTimers(); }});@@ -4493,10 +4514,11 @@ describe('Bot Session task end-to-end runtime', () => {.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' });+ expect(task).toMatchObject({ ok: true, completionDestination: 'group' });if (!task.ok) throw new Error(task.message);+ // Group work stays with its lane even when a private chat was just recovered.expect(h.sqlite!.prepare('SELECT parent_session_id FROM bot_delegations WHERE id=?').get(task.delegationId))- .toEqual({ parent_session_id: sent.targetSessionId });+ .toEqual({ parent_session_id: 'group-lane' });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(); }@@ -4530,7 +4552,7 @@ describe('Bot Session task end-to-end runtime', () => {} 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 => {+ it.each(['healthy', 'missing'] as const)('leaves the %s owner chat alone when group work is the first entry', async state => {await seedPair(); seedGroupLane();if (state === 'missing') {h.sqlite!.pragma('foreign_keys = OFF');@@ -4539,19 +4561,21 @@ describe('Bot Session task end-to-end runtime', () => {}const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });const runtime = createDelegationRuntime();+ const sessionsBefore = h.sqlite!.prepare('SELECT id FROM sessions ORDER BY id').all() as Array<{ id: string }>;+ const linksBefore = h.sqlite!.prepare('SELECT * FROM bot_session_links ORDER BY id').all();try {- const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture task as first recovery entry' });- expect(task).toMatchObject({ ok: true });+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture task as first entry' });+ expect(task).toMatchObject({ ok: true, completionDestination: 'group' });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 }]);+ // The task lives in the group: no private chat is created or repaired for it.+ expect(h.sqlite!.prepare('SELECT parent_session_id FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).toBe('group-lane');+ expect(h.sqlite!.prepare('SELECT id FROM sessions ORDER BY id').all()).toEqual([...sessionsBefore, { id: task.childSessionId }].sort((a, b) => String(a.id).localeCompare(String(b.id))));+ expect(h.sqlite!.prepare('SELECT * FROM bot_session_links ORDER BY id').all()).toEqual(linksBefore);} 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) => {+ // Independent tasks no longer recover a private chat: they stay in the group (bot-group-chat.md §10).+ it.each([['private-message', 'revoked'], ['private-message', '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();@@ -4581,7 +4605,7 @@ describe('Bot Session task end-to-end runtime', () => {} finally { release(); runtime.dispose(); }});- it.each((['private-message', 'peer-message', 'independent-task'] as const).flatMap(operation =>+ it.each((['private-message', 'peer-message'] 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';@@ -4657,8 +4681,12 @@ describe('Bot Session task end-to-end runtime', () => {} finally { release(); }});+ // Reopening group work keeps the lane as its parent (bot-group-chat.md §10), so reopen no+ // longer reads the owner chat; its revocation boundaries are the child read and reconcile.it.each((['resume', 'reopen'] as const).flatMap(mode =>- (['requester-read', 'child-read', 'reconcile'] as const).map(boundary => ({ mode, boundary }))))+ (['requester-read', 'child-read', 'reconcile'] as const)+ .filter(boundary => !(mode === 'reopen' && boundary === 'requester-read'))+ .map(boundary => ({ mode, boundary }))))('rejects $mode preparation revoked during $boundary', async ({ mode, boundary }) => {await seedPair(); seedGroupLane();let armed = false;@@ -5390,13 +5418,12 @@ describe('Bot Session task end-to-end runtime', () => {},);- it.each(['deleted-parent', 'deleting-bot', 'ordinary-task', 'group-link', 'missing-link'] as const)(+ it.each(['deleted-parent', 'deleting-bot', 'ordinary-task', 'missing-link'] as const)('rejects task title list reads from %s', async (state) => {await seedPair();if (state === 'deleted-parent') h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = 'session-1'").run();if (state === 'deleting-bot') h.sqlite!.prepare("UPDATE bot_profiles SET status = 'deleting' WHERE id = 'bot-a'").run();if (state === 'ordinary-task') h.sqlite!.prepare("UPDATE sessions SET source = 'desktop' WHERE id = 'session-1'").run();- if (state === 'group-link') h.sqlite!.prepare("UPDATE bot_session_links SET role = 'group' WHERE session_id = 'session-1'").run();if (state === 'missing-link') h.sqlite!.prepare("DELETE FROM bot_session_links WHERE session_id = 'session-1'").run();const runtime = createDelegationRuntime();try {@@ -5406,6 +5433,23 @@ describe('Bot Session task end-to-end runtime', () => {},);+ // The card posted in a group reads its live row through the lane that started the task+ // (bot-group-chat.md §10); a lane of another group sees nothing, the owner chat sees it all.+ it('lets a group lane list only the tasks started from its own group', async () => {+ await seedPair(); seedGroupLane(); seedGroupLane('other-group', 'group:other:access:owner:2');+ 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: 'Group-only listing fixture' });+ if (!task.ok) throw new Error(task.message);+ expect(await runtime.delegation.listDelegations('group-lane'))+ .toMatchObject({ ok: true, delegations: [expect.objectContaining({ id: task.delegationId, parentSessionId: 'group-lane' })] });+ expect(await runtime.delegation.listDelegations('other-group')).toEqual({ ok: true, delegations: [] });+ expect(await runtime.delegation.listDelegations('session-1'))+ .toMatchObject({ ok: true, delegations: [expect.objectContaining({ id: task.delegationId })] });+ } finally { release(); runtime.dispose(); }+ });+it.each(['cc', 'codex'])('starts a child on the actual %s route after its Bot changes engines', async (agentKind) => {await seedPair();const runtime = createDelegationRuntime({diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex bb8cea44fc..4c2de9b2b1 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-const fixture = vi.hoisted(() => ({ upload: vi.fn(async (): Promise<unknown[]> => []), download: vi.fn(), packaged: true, urls: [] as string[], wsUrls: [] as string[], exists: vi.fn(), config: '', handle: vi.fn(), profiles: [] as unknown[], sockets: [] as import('ws').WebSocket[], token: 'isolated-test-token', refresh: vi.fn(async () => true), requests: [] as Array<{ url: string; token: string }> }));+const fixture = vi.hoisted(() => ({ upload: vi.fn(async (): Promise<unknown[]> => []), download: vi.fn(), packaged: true, urls: [] as string[], wsUrls: [] as string[], exists: vi.fn(), config: '', handle: vi.fn(), profiles: [] as unknown[], sockets: [] as import('ws').WebSocket[], token: 'isolated-test-token', refresh: vi.fn(async () => true), requests: [] as Array<{ url: string; token: string; actor?: string }> }));vi.mock('../../authManager.js', () => ({ getAccessToken: () => fixture.token, refresh: fixture.refresh }));vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.cindy.app' }));vi.mock('../chatServerMedia.js', () => ({ createChatMedia: () => ({ upload: fixture.upload, download: fixture.download }) }));@@ -16,7 +16,7 @@ vi.mock('node:http', async () => {const { EventEmitter } = await import('node:events');return { request: (url: string, options: { method: string; headers: { Authorization: string } }, callback: (response: unknown) => void) => {fixture.urls.push(String(url));- fixture.requests.push({ url: String(url), token: options.headers.Authorization });+ fixture.requests.push({ url: String(url), token: options.headers.Authorization, actor: (options.headers as Record<string, string>)['X-Chat-Actor'] });const req = Object.assign(new EventEmitter(), {end: (data?: string) => {void Promise.resolve().then(() => fixture.handle(new URL(url).pathname.slice(3) + new URL(url).search, options.method, data ? JSON.parse(data) : undefined))@@ -45,7 +45,7 @@ import { withChatServer } from '../chatServer.js';import { projectBotGroupExecutionFailures } from '@cindy/maker-shared/botGroupPresentation';import { botGroupRuntimeFailureCode, settleUndispatchedBotGroupTurn } from '../botGroupRuntimeFailure.js';import { authorizeGroupTool } from '../botGroupToolAuthorization.js';-import { botGroupQuoteFromMessage, buildBotGroupQuoteCard } from '../../../shared/botGroupChat.js';+import { botGroupQuoteFromMessage, buildBotGroupQuoteCard, buildBotGroupTaskCard } from '../../../shared/botGroupChat.js';import type { BotGroupChatService, BotGroupChatServiceDeps } from '../botGroupChatService.js';describe('Chat Server production connection', () => {@@ -463,10 +463,14 @@ describe('Chat Server result delivery and refresh', () => {expect(deps.abortLane).not.toHaveBeenCalled();});- it('still times out an ordinary group turn after its active runtime budget is exhausted', async () => {+ it('lets an ordinary group turn run tools past five minutes and times it out only after two hours', async () => {deps.hasPendingInteraction = vi.fn(() => false);await start();- await vi.advanceTimersByTimeAsync(6 * 60_000);+ // bot-group-chat.md §4.4: a reply that is testing or reading files is not cut at five minutes.+ await vi.advanceTimersByTimeAsync(90 * 60_000);+ expect(deps.abortLane).not.toHaveBeenCalled();+ expect(fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'fail')).toEqual([]);+ await vi.advanceTimersByTimeAsync(31 * 60_000);expect(deps.abortLane).toHaveBeenCalledExactlyOnceWith('lane');const failures = fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'fail');expect(failures).toHaveLength(1);@@ -474,6 +478,77 @@ describe('Chat Server result delivery and refresh', () => {expect(deliveries()).toEqual([]);});+ describe('independent tasks started from the group (bot-group-chat.md §10)', () => {+ const taskMeta = { v: 1, role: 'delegation-request', delegationId: 'task-1', fromBotId: 'local-bot', fromBotName: 'Bot', toBotId: null,+ toBotName: 'Cindy', parentSessionId: 'lane', childSessionId: 'child-1', objective: 'Write the launch post' } as const;+ const taskCard = buildBotGroupTaskCard({ meta: taskMeta, state: 'started', title: 'Launch post' });+ const joined = (id: string, kind: 'bot' | 'human') => ({ id, kind, name: kind === 'bot' ? 'Bot' : 'Me', state: 'joined', role: 'member',+ ownerActorId: selfId, ownerName: '', nickname: null, displayName: kind === 'bot' ? 'Bot' : 'Me', guestAccess: 'none', accessRevision: 1 });++ it('posts the task card as the teammate itself, outside any execution, with its files', async () => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ fixture.upload.mockResolvedValueOnce([{ type: 'media', mediaId: '60000000-0000-4000-8000-000000000001', caption: 'post.md' }]);+ fixture.handle.mockImplementation((route, method) => {+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members: [joined(botId, 'bot'), joined(selfId, 'human')], messages: [], cursor: '1' } };+ if (route.endsWith('/messages') && method === 'POST') return { body: { id: '70000000-0000-4000-8000-000000000001' } };+ return response(route);+ });+ const posted = await service.postCompanionTaskMessage({ groupId: roomId, botId: 'local-bot', clientId: 'bot-delegation-task:task-1:1:result',+ text: 'Done: the post is drafted.', card: { ...taskCard, data: { ...taskCard.data, state: 'completed' } }, files: [{ absolutePath: '/no/such/file.md' }] });+ expect(posted).toEqual({ ok: true, messageId: '70000000-0000-4000-8000-000000000001' });+ const post = fixture.handle.mock.calls.find(([route, method]) => route === `/conversations/${roomId}/messages` && method === 'POST')!;+ expect(post[2]).toEqual({ operationId: 'bot-delegation-task:task-1:1:result', mentions: [],+ content: [{ type: 'text', text: 'Done: the post is drafted.' }, expect.objectContaining({ namespace: 'cindy.task', data: expect.objectContaining({ state: 'completed' }) }),+ { type: 'media', mediaId: '60000000-0000-4000-8000-000000000001', caption: 'post.md' }] });+ // Never as the owner: the teammate's actor signs the message.+ expect(fixture.requests.findLast(request => request.url.endsWith(`/conversations/${roomId}/messages`))?.actor).toBe(botId);+ // A delivery file that no longer exists is simply not uploaded.+ expect(fixture.upload).toHaveBeenCalledWith(roomId, 'bot-delegation-task:task-1:1:result', [], botId);+ expect(deps.onChanged).toHaveBeenCalledWith(expect.objectContaining({ groupId: roomId, change: 'messages' }), undefined);+ });++ it.each([+ ['bot left the group', 403, false],+ ['server unavailable', 503, true],+ ])('reports a refused post as not retryable and a transport failure as retryable (%s)', async (_label, status, retryable) => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ fixture.handle.mockImplementation((route, method) => {+ if (route.endsWith('/snapshot')) return { body: { room: room(roomId), members: [joined(botId, 'bot')], messages: [], cursor: '1' } };+ if (route.endsWith('/messages') && method === 'POST') return { status, body: { error: { code: 'REFUSED' } } };+ return response(route);+ });+ const posted = await service.postCompanionTaskMessage({ groupId: roomId, botId: 'local-bot', clientId: 'bot-delegation-task:task-1:started', text: '', card: taskCard });+ expect(posted).toMatchObject({ ok: false, retryable });+ });++ it('refuses for good when the teammate is no longer a member', async () => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ fixture.handle.mockImplementation(route => route.endsWith('/snapshot')+ ? { body: { room: room(roomId), members: [joined(selfId, 'human')], messages: [], cursor: '1' } } : response(route));+ expect(await service.postCompanionTaskMessage({ groupId: roomId, botId: 'local-bot', clientId: 'bot-delegation-task:task-1:started', text: '', card: taskCard }))+ .toEqual({ ok: false, errorCode: 'MEMBER_UNAVAILABLE', retryable: false });+ expect(fixture.handle.mock.calls.some(([route, method]) => route.endsWith('/messages') && method === 'POST')).toBe(false);+ });++ it('projects the card as the message\'s task, not as body text, and only on the teammate\'s own message', async () => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ const at = '2026-10-03T00:00:00Z';+ const fromBot = { id: '90000000-0000-4000-8000-000000000001', seq: '3', authorId: botId, author: { kind: 'bot', name: 'Bot' }, origin: 'bot',+ deleted: false, threadRootId: null, createdAt: at, content: [{ type: 'text', text: 'Started the post.' }, taskCard] };+ const fromHuman = { id: '90000000-0000-4000-8000-000000000002', seq: '4', authorId: selfId, author: { kind: 'human', name: 'Me' }, origin: 'user',+ deleted: false, threadRootId: null, createdAt: at, content: [taskCard, { type: 'text', text: 'Pasted a card' }] };+ fixture.handle.mockImplementation(route => route.includes('/messages?')+ ? { body: [fromBot, fromHuman] }+ : route.endsWith('/snapshot') ? { body: { room: room(roomId), members: [joined(botId, 'bot'), joined(selfId, 'human')], messages: [], cursor: '1' } } : response(route));+ const result = await service.getGroup(roomId);+ if (!result.ok) throw new Error('Expected group');+ const [bot, human] = result.group.messages;+ expect(bot).toMatchObject({ authorKind: 'bot', content: 'Started the post.', task: { state: 'started', title: 'Launch post', meta: { delegationId: 'task-1', parentSessionId: 'lane' } } });+ expect(human.task).toBeUndefined();+ expect(human.content).toBe(`${taskCard.fallback}\nPasted a card`);+ });+ });+it('rejects an old undispatched input instead of failing its replacement', async () => {await start();expect(await settleUndispatchedBotGroupTurn(service, 'lane', 'old-input', 'failed', 'MODEL_NOT_FOUND')).toBe(false);diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex ec1a866bcd..ca68af8b56 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -47,6 +47,8 @@ import type {BotDelegationInterjectResult,} from '../../shared/botCollaboration.js';import { BOT_DELEGATION_CLIENT_ID } from '../../shared/botCollaboration.js';+import { buildBotGroupTaskCard, type BotGroupTaskCardState } from '../../shared/botGroupChat.js';+import type { BotGroupTaskPostInput, BotGroupTaskPostResult } from './botGroupChatService.js';import { ensureBotWorkspaceDir } from './botProfileFolder.js';import type { SessionQueuedMessageControlResult, SessionSteerResult, SessionStopResult } from './sessionControlService.js';import { ownerScopedUserDataPath } from '../appSessionState.js';@@ -191,6 +193,12 @@ export interface BotDelegationServiceDeps {| { ok: false; errorCode: string; message: string }>;};+ /**+ * A task started from a group lives in that group (bot-group-chat.md §10): its card,+ * confirmations and result are posted there as the teammate's own messages. A definite+ * refusal (not retryable) falls back to the owner's private chat so no result is lost.+ */+ postGroupTaskMessage?: (input: BotGroupTaskPostInput) => Promise<BotGroupTaskPostResult>;now?: () => number;createId?: () => string;maxActiveChildren?: number;@@ -782,6 +790,62 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {* 冻结这次协作双方的展示身份。名字后来改了不回填历史消息——消息流讲的是* 「当时谁把活交给了谁」,不是「他们现在叫什么」。*/+ /** The group a task was started from, by its persisted origin route (bot-group-chat.md §10). */+ const groupHomeOf = (permissionSnapshotJson: string | null | undefined): { groupId: string; routeKey: string } | null => {+ const route = parseRecord(permissionSnapshotJson).groupOriginRoute;+ const match = typeof route === 'string' ? /^group:([^:]+)/.exec(route) : null;+ return match ? { groupId: match[1]!, routeKey: route as string } : null;+ };++ type GroupTaskRow = Pick<DelegationRow,+ 'id' | 'requestingBotId' | 'targetBotId' | 'objective' | 'parentSessionId' | 'childSessionId'+ >;++ /** One task event as the teammate's own group message, carrying the task card. */+ const postGroupTaskEvent = async (+ home: { groupId: string },+ row: GroupTaskRow,+ event: { clientId: string; text: string; state: BotGroupTaskCardState; summary?: string; files?: Array<{ absolutePath: string }> },+ ): Promise<BotGroupTaskPostResult> => {+ if (!deps.postGroupTaskMessage) return { ok: false, errorCode: 'GROUP_CHANNEL_UNAVAILABLE', retryable: false };+ const meta = await collaborationMeta(row, 'delegation-request');+ const child = row.childSessionId ? await getDbClient().drizzle+ .select({ title: sessions.title }).from(sessions)+ .where(eq(sessions.id, row.childSessionId)).get() : undefined;+ const card = buildBotGroupTaskCard({+ meta,+ state: event.state,+ title: child?.title?.trim() || row.objective.split('\n')[0]!.slice(0, 120),+ ...(event.summary ? { summary: event.summary } : {}),+ });+ return deps.postGroupTaskMessage({+ groupId: home.groupId, botId: row.requestingBotId, clientId: event.clientId, text: event.text, card,+ ...(event.files?.length ? { files: event.files } : {}),+ });+ };++ const groupPostTimers = new Set<ReturnType<typeof setTimeout>>();+ /** The start card is best effort with backoff; the result message carries the card again. */+ const postGroupTaskStart = async (home: { groupId: string }, row: GroupTaskRow, attempt = 0): Promise<void> => {+ try {+ const posted = await postGroupTaskEvent(home, row, { clientId: `bot-delegation-task:${row.id}:started`, text: '', state: 'started' });+ if (posted.ok) return;+ if (!posted.retryable) {+ log.warn('group refused the task card', { delegationId: row.id, groupId: home.groupId, errorCode: posted.errorCode });+ return;+ }+ } catch (error) {+ log.warn('Bot task group card deferred', { delegationId: row.id, error: error instanceof Error ? error.message : String(error) });+ }+ if (attempt >= 6) return;+ const timer = setTimeout(() => {+ groupPostTimers.delete(timer);+ void postGroupTaskStart(home, row, attempt + 1);+ }, Math.min(MAX_RETRY_DELAY_MS, 1_000 * 2 ** attempt));+ timer.unref?.();+ groupPostTimers.add(timer);+ };+const collaborationMeta = async (row: Pick<DelegationRow,'id' | 'requestingBotId' | 'targetBotId' | 'objective' | 'parentSessionId' | 'childSessionId'@@ -989,8 +1053,59 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {scheduleCompletionRetry(params, attempt);return false;}- const targetSessionId = await requesterLiveSessionId(params.requestingBotId, params.parentSessionId);+ // A group task reports back in its group as the teammate's own message; the lane that+ // started it is never woken. Only a definite refusal falls back to the owner's main chat.+ const home = groupHomeOf((await getDbClient().drizzle+ .select({ snapshot: botDelegations.permissionSnapshotJson }).from(botDelegations)+ .where(eq(botDelegations.id, params.id)).get())?.snapshot);+ if (home) {+ const posted = await postGroupTaskEvent(home, params, {+ clientId: `bot-delegation-task:${params.id}:${params.runSequence}:result`,+ text: params.resultSummary ?? '',+ state: params.status,+ files: artifacts.filter((file) => file.status !== 'deleted').map((file) => ({ absolutePath: file.absolutePath })),+ });+ if (!(await completionStillPending())) return false;+ if (posted.ok) {+ if (!(await ensureResultReceipt())) {+ scheduleCompletionRetry(params, attempt);+ return false;+ }+ const [marked] = await getDbClient().drizzle+ .update(botDelegations)+ .set({ completionDeliveredAt: now(), updatedAt: now() })+ .where(and(+ eq(botDelegations.id, params.id),+ eq(botDelegations.runSequence, params.runSequence),+ eq(botDelegations.status, params.status),+ params.childSessionId === null+ ? isNull(botDelegations.childSessionId)+ : eq(botDelegations.childSessionId, params.childSessionId),+ isNull(botDelegations.completionDeliveredAt),+ ))+ .returning({ id: botDelegations.id });+ if (!marked && await completionStillPending()) {+ scheduleCompletionRetry(params, attempt);+ return false;+ }+ clearCompletionRetryTimer(params.id);+ return !!marked;+ }+ if (posted.retryable) {+ scheduleCompletionRetry(params, attempt);+ return false;+ }+ log.warn('group refused the task result; delivering to the owner private chat instead', {+ delegationId: params.id, groupId: home.groupId, errorCode: posted.errorCode,+ });+ }+ const targetSessionId = await requesterLiveSessionId(params.requestingBotId, home ? null : params.parentSessionId);if (!targetSessionId && await holdCompletionForStoppedRequester(params)) return false;+ if (home && targetSessionId && targetSessionId !== receiptSessionId) {+ // The owner reads the result where the wake-up lands, not in the hidden lane.+ receiptSessionId = targetSessionId;+ await persistResultReceipt(targetSessionId);+ }if (!targetSessionId) {log.warn('defer Bot delegation wake-up: requester has no live task', {delegationId: params.id,@@ -1021,7 +1136,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {// The target may have been deleted while dispatch was accepting the// hidden message. A rehomed receipt alone does not wake its replacement.// Leave this run pending so the stable completion ID is dispatched there.- const currentTargetSessionId = await requesterLiveSessionId(params.requestingBotId, params.parentSessionId);+ const currentTargetSessionId = await requesterLiveSessionId(params.requestingBotId, home ? null : params.parentSessionId);if (currentTargetSessionId !== targetSessionId) {scheduleCompletionRetry(params, attempt);return false;@@ -1169,7 +1284,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {parent?.status === 'active'&& parent.profileStatus === 'active'&& parent.botId === requestingBotId- && (parent.role === 'canonical' || parent.role === 'delegation')+ // A group lane is a live requester only for the task it started (bot-group-chat.md §10);+ // the lane is never woken by this service, its group gets the messages instead.+ && (parent.role === 'canonical' || parent.role === 'delegation' || parent.role === 'group'));};if (parentSessionId && (await liveRequesterTask(parentSessionId))) return parentSessionId;@@ -1444,8 +1561,40 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {pending.request.kind === 'permission' ? `请求工具: ${pending.request.toolName}` : '','你是用户的代理。能按用户已表达的意图安全决定,就用 `message_session_task` 直接回答;拿不准才用一句人话问用户。不要让用户去子任务窗口处理,也不要复述内部编号。',].filter(Boolean).join('\n\n');- try {- const requesterSessionId = await requesterLiveSessionId(row.requestingBotId, row.parentSessionId);+ // A group task asks in its group: the owner opens the task from the card to answer.+ // Tool names and arguments stay on this computer; only a question's words are shared.+ const home = groupHomeOf(row.permissionSnapshotJson);+ let privateFallback = !home;+ if (home) {+ try {+ const posted = await postGroupTaskEvent(home, row, {+ clientId: `bot-delegation-task:${row.id}:interaction:${pending.requestId}`,+ text: '',+ state: 'waiting',+ ...(pending.request.kind === 'permission' ? {} : { summary: pending.summary }),+ });+ if (!stillPending() || (row.childSessionId && heldSessionIds.has(row.childSessionId))) return;+ if (posted.ok) {+ clearInteractionRetryTimer(row.id);+ return;+ }+ if (!posted.retryable) {+ log.warn('group refused the task notice; asking in the owner private chat instead', {+ delegationId: row.id, groupId: home.groupId, errorCode: posted.errorCode,+ });+ privateFallback = true;+ }+ } catch (error) {+ log.warn('Bot task group notice deferred', {+ delegationId: row.id,+ requestId: pending.requestId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ if (privateFallback) try {+ // A lane is never woken; a refused group notice goes to the owner's main chat.+ const requesterSessionId = await requesterLiveSessionId(row.requestingBotId, home ? null : row.parentSessionId);if (!stillPending() || (row.childSessionId && heldSessionIds.has(row.childSessionId))) return;const dispatched = requesterSessionId? await deps.dispatch({@@ -1459,7 +1608,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {// Acceptance in a parent that was deleted or archived during dispatch// does not wake its replacement. The client ID is stable per target,// so retrying is safe even if the first send was merely queued.- const currentTarget = await requesterLiveSessionId(row.requestingBotId, row.parentSessionId);+ const currentTarget = await requesterLiveSessionId(row.requestingBotId, home ? null : row.parentSessionId);if (currentTarget === requesterSessionId || !stillPending()) {clearInteractionRetryTimer(row.id);return;@@ -2160,20 +2309,10 @@ 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 };+ // The execution caller remains the parent, including a group lane: work started from a+ // group stays in that group (bot-group-chat.md §10). Its card, confirmations and result+ // are posted there as the teammate's messages; the lane itself is never woken for them.+ const parentSessionId = input.callerSessionId;const delegationId = createId();let childSessionId = resolveBusinessSessionId(undefined);if (input.useWorktree) {@@ -2340,6 +2479,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}scheduleTimeout(delegationId, plan.limits.deadlineAt);+ // The group sees the card as soon as the task exists; the lane's own reply follows later.+ const groupHome = input.caller.role === 'group' ? groupHomeOf(permissionSnapshotJson) : null;+ if (groupHome) void postGroupTaskStart(groupHome, mirrorRow);// 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.@@ -2362,7 +2504,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {input: SessionTaskInput,): Promise<BotDelegationResult<{modelRoute: BotModelRoute;- completionDestination?: 'teammate-private-chat';+ /** `group`: the card, confirmations and result stay in the group this was started from. */+ completionDestination?: 'group';delegationId: string;childSessionId: string;/**@@ -2498,7 +2641,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {childSessionId: started.childSessionId,status: started.status,deadlineAt: started.deadlineAt,- ...(caller.role === 'group' ? { completionDestination: 'teammate-private-chat' as const } : {}),+ ...(caller.role === 'group' ? { completionDestination: 'group' as const } : {}),modelRoute: {harness: taskRuntime.agentKind === 'codex' ? 'codex' : taskRuntime.agentKind === 'pi' ? 'pi' : 'claude',model: taskRuntime.model,@@ -2514,21 +2657,20 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {): Promise<BotDelegationResult<{ delegations: BotDelegationView[] }>> => {// History cards need saved titles even when their chat or teammate is inactive.// Only this read path accepts history links; task operations still use resolveCaller.+ // A group lane reads only the tasks started from its group, for the cards posted there.const caller = await resolveLinkedSession(callerSessionId);if (!caller|| caller.sessionSource !== 'bot'|| (caller.sessionStatus !== 'active' && caller.sessionStatus !== 'archived')|| caller.profileStatus === 'deleting'- || !['canonical', 'history', 'delegation'].includes(caller.role)) {+ || !['canonical', 'history', 'delegation', 'group'].includes(caller.role)) {return { ok: false, errorCode: 'NOT_A_BOT_SESSION', message: '当前任务不属于任何伙伴' };}const db = getDbClient().drizzle;const rows = await db.select().from(botDelegations)- .where(- eq(botDelegations.requestingBotId, caller.botId),- )+ .where(callerTaskScope(caller)).orderBy(desc(botDelegations.createdAt));const profiles = await db.select({ id: botProfiles.id, displayName: botProfiles.displayName })@@ -3221,10 +3363,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};}if (!isActiveDelegation(row.status as DelegationStatus)) {- const returnSessionId = caller.role === 'group' ? await requesterLiveSessionId(caller.botId, null) : callerSessionId;+ // Reopened group work keeps its group home; the lane that reopens it becomes the parent.await caller.groupAuthority?.refresh();- if (!returnSessionId) throw new GroupToolAuthorizationError();- return reopenTerminalDelegation(returnSessionId, caller.botId, row, input.text, caller.groupAuthority);+ return reopenTerminalDelegation(callerSessionId, caller.botId, row, input.text, caller.groupAuthority);}const result = await interjectDelegation(callerSessionId,@@ -4226,6 +4367,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {timers.clear();for (const timer of retryTimers.values()) clearTimeout(timer);retryTimers.clear();+ for (const timer of groupPostTimers) clearTimeout(timer);+ groupPostTimers.clear();for (const timer of completionRetryTimers.values()) clearTimeout(timer);completionRetryTimers.clear();for (const timer of interactionRetryTimers.values()) clearTimeout(timer);diff --git a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts b/apps/desktop/src/main/maker-ipc/botGroupChatService.tsindex 8676d02746..82e13f7796 100644--- a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts+++ b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts@@ -64,12 +64,12 @@ import {type BotGroupSpeaker,type BotGroupSpeakingMode,type BotGroupSummary,+ type BotGroupTaskCard,} from '../../shared/botGroupChat.js';/** docs/product-rules/bot-group-chat.md §4.2 — enforced here, never by prompt. */const MAX_CIRCLES_PER_ROUND = 3;const MAX_BOT_MESSAGES_PER_ROUND = 10;-const MEMBER_TURN_TIMEOUT_MS = 5 * 60_000;const MAX_DELTA_MESSAGES = 30;/** Attachments sent with one member turn; the newest win when unseen messages carry more. */const MAX_TURN_ATTACHMENTS = 40;@@ -79,6 +79,11 @@ const PREVIEW_CHARS = 80;const MAX_ID_CHARS = 128;/** docs/product-rules/bot-group-chat.md §7.4: a step may run long; time waiting on the user is not counted. */const STEP_TURN_TIMEOUT_MS = 2 * 60 * 60_000;+/**+ * docs/product-rules/bot-group-chat.md §4.4: an ordinary reply may run tools and tests for as long+ * as a step; a hung lane is caught by the session's own idle watchdog, not by this wall clock.+ */+const MEMBER_TURN_TIMEOUT_MS = STEP_TURN_TIMEOUT_MS;const MAX_PLAN_RECENT_MESSAGES = 12;const MAX_PROJECT_DIR_CHARS = 4_096;@@ -2165,10 +2170,28 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {retryPlan: (input: unknown) => planAction('retry', input),editPlanStep,settleLaneTurn,+ /** Only a server room has a message channel a teammate can post into outside a turn. */+ postCompanionTaskMessage: async (_input: BotGroupTaskPostInput): Promise<BotGroupTaskPostResult> =>+ ({ ok: false, errorCode: 'GROUP_CHANNEL_UNAVAILABLE', retryable: false }),dispose,};}+/** One message a teammate posts into its group about an independent task (bot-group-chat.md §10). */+export interface BotGroupTaskPostInput {+ groupId: string;+ botId: string;+ /** Idempotent per event: retries return the message the server already stored. */+ clientId: string;+ text: string;+ card: BotGroupTaskCard;+ /** Delivered files, uploaded as this teammate's attachments; unreadable ones are skipped. */+ files?: Array<{ absolutePath: string }>;+}+export type BotGroupTaskPostResult =+ | { ok: true; messageId: string }+ | { ok: false; errorCode: string; retryable: boolean };+export type BotGroupChatService = ReturnType<typeof createBotGroupChatService> & {chatServer?: import('../../shared/botGroupChat.js').ChatServerApi;};diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 8c3d7e28e5..37402df0a8 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -32,8 +32,9 @@ import {readBotGroupExecutionFailure, type BotGroupExecutionFailureView,type BotGroupDetail, type BotGroupPlanView, type BotGroupFailure, type BotGroupMessageView, type BotGroupAttachment, type ChatServerApi,botGroupQuoteAttachmentName, botGroupQuoteExcerpt, botGroupQuoteFromMessage, buildBotGroupQuoteCard, readBotGroupQuote, readBotGroupQuoteCard, type BotGroupQuoteView,+ readBotGroupTaskCard,} from '../../shared/botGroupChat.js';-import type { BotGroupChatService, BotGroupChatServiceDeps, BotGroupLaneTerminal } from './botGroupChatService.js';+import type { BotGroupChatService, BotGroupChatServiceDeps, BotGroupLaneTerminal, BotGroupTaskPostInput, BotGroupTaskPostResult } from './botGroupChatService.js';import { readPersistedReplyText } from './botGroupChatService.js';import { botGroupRuntimeFailureCode, botGroupRuntimeFailureDetail } from './botGroupRuntimeFailure.js';import { botGroupExecutionFailureBatches } from '@cindy/maker-shared/botGroupPresentation';@@ -99,7 +100,15 @@ type ExecutionContext = { kind: 'message' } | { kind: 'member.joined'; trigger:const ordinaryExecution = (execution: Execution) => execution.trigger === undefined && execution.trigger_type == null;const groupInput = z.object({ name: z.string().trim().min(1).max(40), botIds: z.array(z.string().min(1)).max(6) });// A recognized quote card is shown as the quote, not as body text; unknown revisions keep their fallback.-const bodyBlocks = (m: Message) => m.content.filter(b => (b.namespace !== 'cindy.local-history' || b.data?.activity === true) && !readBotGroupQuoteCard(b));+// A task card is the message's task only on a teammate's own message; a human may not post one for it.+const taskCardOf = (m: Message) => m.author.kind === 'bot' ? m.content.map(readBotGroupTaskCard).find(Boolean) ?? null : null;+const bodyBlocks = (m: Message) => m.content.filter(b => (b.namespace !== 'cindy.local-history' || b.data?.activity === true) && !readBotGroupQuoteCard(b)+ && !(m.author.kind === 'bot' && readBotGroupTaskCard(b)));+/**+ * docs/product-rules/bot-group-chat.md §4.4 / §7.4: a reply or step may run tools for as long as+ * two hours; time waiting on the user is not counted. A hung lane is ended by its own idle watchdog.+ */+const TURN_TIMEOUT_MS = 2 * 60 * 60 * 1000;const bodyText = (m: Message) => m.deleted ? '(消息已删除)' : readImportedBotGroupRuntimeFailureCode(m) ? '' : bodyBlocks(m).map(b => b.text ?? b.fallback ?? (b.type === 'media' ? `[附件: ${b.caption ?? '文件'}]` : '')).join('\n');/** Words of a message for a quote excerpt; attachments are summarized separately. */const quotedText = (m: Message) => bodyBlocks(m).filter(b => b.type !== 'media').map(b => b.text ?? b.fallback ?? '').join('\n');@@ -159,6 +168,7 @@ export function withChatServer(local: BotGroupChatService, deps: BotGroupChatSerretryPlan: (...args) => service().retryPlan(...args),editPlanStep: (...args) => service().editPlanStep(...args),settleLaneTurn: (...args) => service().settleLaneTurn(...args),+ postCompanionTaskMessage: (...args) => service().postCompanionTaskMessage(...args),dispose: () => { active.dispose(); local.dispose(); },};}@@ -634,8 +644,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDnoticeCode: runtimeFailureCode === 'RUNTIME_TIMEOUT' ? 'member-timeout' : 'member-failed', runtimeFailureCode,planId: null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };const quote = m.deleted || planCard ? null : readBotGroupQuote(m.content);+ const task = m.deleted || planCard ? null : taskCardOf(m);return { id: m.id, sequence: Number(m.seq), deleted: m.deleted, kind: planCard ? 'plan' : 'message', authorKind: legacy?.authorKind === 'system' ? 'system' : m.author.kind === 'human' ? 'user' : 'bot',- isSelf: m.authorId === selfId, threadRootId: m.threadRootId, replyCount: m.replyCount ?? 0, reactions: m.reactions ?? [], ...(quote ? { quote } : {}),+ isSelf: m.authorId === selfId, threadRootId: m.threadRootId, replyCount: m.replyCount ?? 0, reactions: m.reactions ?? [], ...(quote ? { quote } : {}), ...(task ? { task } : {}),authorBotId: localBot(m.authorId)?.id ?? m.authorId, authorName: legacy?.authorKind === 'system' && typeof legacy.authorName === 'string' ? legacy.authorName : member ? memberName(member) : m.author.name, content: bodyText(m),mentions: { all: false, botIds: [] }, noticeCode: null, planId: typeof planCard?.data?.planId === 'string' ? planCard.data.planId : null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };}@@ -1239,7 +1250,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst paused = !!deps.hasPendingInteraction?.(run.sessionId);if (paused) run.pauseStarted ??= Date.now();else if (run.pauseStarted !== undefined) { run.started += Date.now() - run.pauseStarted; run.pauseStarted = undefined; }- const timedOut = !paused && Date.now() - run.started > (run.plan ? 2 * 60 * 60 * 1000 : 300000);+ const timedOut = !paused && Date.now() - run.started > TURN_TIMEOUT_MS;if (timedOut) {await settleExecution(run, { sessionId: run.sessionId, activeInputClientId: run.clientId,outcome: 'error', resultText: '', failureCode: 'RUNTIME_TIMEOUT' }, true);@@ -1526,6 +1537,45 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDawait settleExecution(run, terminal, terminal.undispatched);return true;},+ // A teammate's own message about an independent task it started from this group+ // (bot-group-chat.md §10): posted outside any execution, as that teammate, never as the owner.+ postCompanionTaskMessage: async (input: BotGroupTaskPostInput): Promise<BotGroupTaskPostResult> => {+ const refused = (errorCode: string): BotGroupTaskPostResult => ({ ok: false, errorCode, retryable: false });+ try {+ if (!current()) return refused('OWNER_CHANGED');+ const roomId = id.safeParse(input.groupId).success ? input.groupId : null;+ if (!roomId) return local.postCompanionTaskMessage(input);+ await register();+ const actor = actors.find(a => a.kind === 'bot' && a.externalId === input.botId);+ if (!actor) return refused('BOT_UNAVAILABLE');+ const s = await snapshot(roomId);+ if (s.room.archived || !s.members.some(m => m.id === actor.id && m.state === 'joined')) return refused('MEMBER_UNAVAILABLE');+ const produced: BotGroupAttachment[] = [];+ const fs = await import('node:fs/promises');+ for (const file of input.files ?? []) {+ try {+ const stat = await fs.lstat(file.absolutePath);+ if (stat.isFile()) produced.push({ id: file.absolutePath, name: path.basename(file.absolutePath), category: 'file',+ mimeType: 'application/octet-stream', size: stat.size, path: file.absolutePath, url: null });+ } catch { /* a file deleted since the task finished is simply not delivered */ }+ }+ // A delivery file that cannot be uploaded must not hold back the result text and card.+ const uploaded = await media.upload(roomId, input.clientId, produced, actor.id).catch(error => {+ deps.log?.warn('Chat task delivery files skipped', { groupId: roomId, ...chatErrorDiagnostic(error) });+ return [];+ });+ const text = input.text.trim().slice(0, 8000);+ const posted = await api<{ id: string }>(`/conversations/${roomId}/messages`, 'POST', {+ operationId: input.clientId, content: [...(text ? [{ type: 'text', text }] : []), input.card, ...uploaded], mentions: [],+ }, actor.id);+ changed(roomId);+ return { ok: true, messageId: posted.id };+ } catch (error) {+ deps.log?.warn('Chat task message post failed', { groupId: input.groupId, ...chatErrorDiagnostic(error) });+ return { ok: false, errorCode: error instanceof Error ? error.message : 'REQUEST_FAILED',+ retryable: !(error instanceof ChatResponseError) || retryableResponse(error) };+ }+ },setMembers: input => safe(async () => {const i = z.object({ groupId: id, botIds: z.array(z.string()).max(6), addOnly: z.boolean().optional() }).parse(input);const room = await resolveGroup(i.groupId); const s = await snapshot(room);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 23924222fb..6ad8c2e357 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -12026,6 +12026,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}return [...byPath.values()];},+ // A task started from a group posts its card, confirmations and result there as its teammate.+ postGroupTaskMessage: async (input) => botGroupChatServiceHolder+ ? botGroupChatServiceHolder.postCompanionTaskMessage(input)+ : { ok: false as const, errorCode: 'GROUP_CHANNEL_UNAVAILABLE', retryable: true },});registerBotLifecycleHandlers({maker,diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex eaa4713efb..c43ffd589c 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@ -77,6 +77,7 @@ import { ChatInviteButton, ChatMessageActions } from './ChatServerControls';import { animateThreadPanelWidth, ChatThreadPanel } from './ChatThreadPanel';import { BotGroupPendingInteraction } from './BotGroupPendingInteraction';import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';+import { BotGroupTaskCard } from './BotGroupTaskCard';import { isBotGroupRuntimeFailureCode } from '../../../shared/botGroupChat';import {BotGroupHandoffFiles,@@ -1116,6 +1117,8 @@ function BotGroupTimelineItem({) : (<>{quoteDisplay ? <BotGroupQuoteBlock display={quoteDisplay} onLocate={onLocateQuote} /> : null}+ {/* A task this teammate started from the group; mine is live, another owner's is a snapshot. */}+ {message.task ? <BotGroupTaskCard task={message.task} owned={member?.isOwned !== false} /> : null}{hasText ? (<div className={`min-w-0 text-[var(--msg-assistant-text)] ${CHAT_BODY_CLASS}`}><MarkdownRenderer workingDir="" content={message.content} allowPrivilegedLinks={false} />diff --git a/apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx b/apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsxnew file mode 100644index 0000000000..5e2831149e--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx@@ -0,0 +1,35 @@+/**+ * An independent task a teammate started from this group (bot-group-chat.md §10).+ *+ * My own teammate's task: the live task link (status icon, click to open), read from the+ * delegation row on this computer. Someone else's teammate: the card as it was posted —+ * title and state — because that task runs on their computer.+ */+import { ListTodo } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import type { BotGroupTaskCardView } from '../../../shared/botGroupChat';+import { BotSessionTaskLink } from './BotSessionTaskLink';++export function BotGroupTaskCard({ task, owned }: { task: BotGroupTaskCardView; owned: boolean }) {+ const { t } = useTranslation();+ const state = t(`bots.groupChat.task.state.${task.state}`);+ return (+ <div+ data-testid="bot-group-task"+ data-state={task.state}+ className="my-1 flex min-w-0 max-w-[520px] items-start gap-2.5 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2"+ >+ <ListTodo size={14} aria-hidden className="mt-[5px] shrink-0 text-[var(--text-tertiary)]" />+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ {owned ? (+ <BotSessionTaskLink card={task.meta} sessionId={task.meta.parentSessionId ?? undefined} />+ ) : (+ <span className="truncate text-14 leading-6 text-[var(--text-primary)]">{task.title}</span>+ )}+ <span className="min-w-0 break-words text-12 leading-5 text-[var(--text-tertiary)]">+ {task.state === 'waiting' && task.summary ? `${state} · ${task.summary}` : state}+ </span>+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTaskCard.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTaskCard.test.tsxnew file mode 100644index 0000000000..26f6aa05f6--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupTaskCard.test.tsx@@ -0,0 +1,42 @@+// @vitest-environment jsdom+import { cleanup, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { BotGroupTaskCardView } from '../../../../shared/botGroupChat';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key.replace('bots.groupChat.task.state.', 'state:') }),+}));+// Another owner's task never reaches the live link; the component must not need its stores.+vi.mock('../BotSessionTaskLink', () => ({ BotSessionTaskLink: () => <span data-testid="live-link">live</span> }));++import { BotGroupTaskCard } from '../BotGroupTaskCard';++const task = (state: BotGroupTaskCardView['state'], summary?: string): BotGroupTaskCardView => ({+ meta: { v: 1, role: 'delegation-request', delegationId: 'task-1', fromBotId: 'bot-a', fromBotName: 'LiZi', toBotId: null,+ toBotName: 'Cindy', parentSessionId: 'group-lane', childSessionId: 'child-1', objective: 'Write the launch post' },+ state, title: 'Launch post', ...(summary ? { summary } : {}),+});++afterEach(cleanup);++describe('BotGroupTaskCard', () => {+ it('shows another owner\'s task as the posted snapshot: title and state', () => {+ render(<BotGroupTaskCard task={task('completed')} owned={false} />);+ const card = screen.getByTestId('bot-group-task');+ expect(card.dataset.state).toBe('completed');+ expect(card.textContent).toContain('Launch post');+ expect(card.textContent).toContain('state:completed');+ expect(screen.queryByTestId('live-link')).toBeNull();+ });++ it('shows what a waiting task asks for', () => {+ render(<BotGroupTaskCard task={task('waiting', 'Which audience?')} owned={false} />);+ expect(screen.getByTestId('bot-group-task').textContent).toContain('state:waiting · Which audience?');+ });++ it('shows my own teammate\'s task as the live link', () => {+ render(<BotGroupTaskCard task={task('started')} owned />);+ expect(screen.getByTestId('live-link')).toBeTruthy();+ expect(screen.getByTestId('bot-group-task').textContent).toContain('state:started');+ });+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 57482d1873..af964cc003 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9167,6 +9167,16 @@"speaking": {"planning": "Splitting the work…"},+ "task": {+ "state": {+ "started": "In progress",+ "waiting": "Waiting for your confirmation",+ "completed": "Done",+ "failed": "Failed",+ "cancelled": "Cancelled",+ "timed-out": "Timed out"+ }+ },"files": {"openFailed": "Couldn’t open the file. It may have been moved or deleted."},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 6b5b09aa06..26559cfc99 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9130,6 +9130,16 @@"speaking": {"planning": "役割分担を考えています…"},+ "task": {+ "state": {+ "started": "進行中",+ "waiting": "確認待ち",+ "completed": "完了",+ "failed": "失敗",+ "cancelled": "キャンセル済み",+ "timed-out": "タイムアウト"+ }+ },"files": {"openFailed": "ファイルを開けませんでした。移動または削除された可能性があります"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 4b1e0e50d1..71682a71d4 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9130,6 +9130,16 @@"speaking": {"planning": "역할을 나누는 중…"},+ "task": {+ "state": {+ "started": "진행 중",+ "waiting": "확인 대기 중",+ "completed": "완료",+ "failed": "실패",+ "cancelled": "취소됨",+ "timed-out": "시간 초과"+ }+ },"files": {"openFailed": "파일을 열지 못했습니다. 이동되었거나 삭제되었을 수 있습니다"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex e78c9f69b1..63a987f377 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9130,6 +9130,16 @@"speaking": {"planning": "正在安排…"},+ "task": {+ "state": {+ "started": "进行中",+ "waiting": "等你确认",+ "completed": "已完成",+ "failed": "失败了",+ "cancelled": "已取消",+ "timed-out": "已超时"+ }+ },"files": {"openFailed": "文件没能打开,可能已被移动或删除"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 1b15646701..5ec27a25eb 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9130,6 +9130,16 @@"speaking": {"planning": "正在安排…"},+ "task": {+ "state": {+ "started": "進行中",+ "waiting": "等你確認",+ "completed": "已完成",+ "failed": "失敗了",+ "cancelled": "已取消",+ "timed-out": "已逾時"+ }+ },"files": {"openFailed": "檔案沒能開啟,可能已被移動或刪除"},diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsxindex 1e80fc5dba..3ad5563dc0 100644--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx@@ -75,7 +75,7 @@ vi.mock('react-i18next', async (importOriginal) => ({vi.mock('expo-crypto', () => ({ randomUUID: () => `uuid-${++h.uuid}` }));vi.mock('lucide-react-native', () => Object.fromEntries(['ChevronLeft', 'Settings2', 'Plus', 'Square', 'Users', 'X', 'Check', 'CircleAlert', 'CircleCheck', 'CircleDashed', 'FileText', 'Sparkles', 'Folder', 'Camera', 'Image',- 'Layers', 'ListChecks', 'Ellipsis', 'ChevronRight', 'ChevronDown']+ 'Layers', 'ListChecks', 'ListTodo', 'Ellipsis', 'ChevronRight', 'ChevronDown'].map((name) => [name, () => null]),));vi.mock('@/theme', async () => ({@@ -201,6 +201,8 @@ vi.mock('@/session/useBotGroupSettingsManagement', () => ({ useBotGroupSettingsMvi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));vi.mock('@/session/CompanionPresenceRing', () => ({ CompanionPresenceRing: () => null }));vi.mock('@/session/ThinkingDots', () => ({ ThinkingDots: () => null }));+// The live card of my own teammate's task reads the computer over device-link; not under test here.+vi.mock('@/session/CompanionMessageCard', () => ({ CompanionTaskCard: () => null }));import { BotGroupChatScreen } from '@/session/BotGroupChatScreen';import { parseBotGroupChatData } from '@/session/botGroupRemote';@@ -304,6 +306,23 @@ describe('group timeline', () => {expect(node.textContent).not.toContain('私密的原文');});+ it('shows a task another owner\'s teammate started from the group as its posted title and state', async () => {+ const meta = { v: 1 as const, role: 'delegation-request' as const, delegationId: 'task-1', fromBotId: 'abu', fromBotName: '阿布', toBotId: null,+ toBotName: 'Cindy', parentSessionId: 'group-lane', childSessionId: 'child-1', objective: '写官网首页' };+ const data = group({ serverBacked: true, members: [+ { botId: 'mimi', name: '咪咪', avatar: '🐱', avatarColor: 'red', status: 'active', isOwned: true },+ { botId: 'abu', name: '阿布', avatar: '🦉', avatarColor: 'blue', status: 'active', isOwned: false },+ ] });+ data.messages.push(message('t1', 20, { authorBotId: 'abu', authorName: '阿布', content: '我开了个任务',+ task: { meta, state: 'waiting', title: '官网首页', summary: '首页要放几个案例?' } }));+ await render(parseBotGroupChatData(data)!);+ const card = byId('botGroup.task')!;+ expect(card.textContent).toContain('官网首页');+ expect(card.textContent).toContain('groupChat.task.state.waiting');+ expect(card.textContent).toContain('首页要放几个案例?');+ expect(byId('botGroup.task.live')).toBeNull();+ });+it('uses the shared Android keyboard avoidance behavior for the group composer', async () => {h.platform.OS = 'android';await render();diff --git a/apps/mobile/src/__tests__/botGroupRemote.test.ts b/apps/mobile/src/__tests__/botGroupRemote.test.tsindex 258c39194f..4265e2c348 100644--- a/apps/mobile/src/__tests__/botGroupRemote.test.ts+++ b/apps/mobile/src/__tests__/botGroupRemote.test.ts@@ -88,6 +88,25 @@ describe('parseBotGroupChatData', () => {expect(parseBotGroupChatData(chatData())!.messages.every(message => !message.quote && !message.deleted)).toBe(true);});+ it('keeps a validated task card only on a teammate message (bot-group-chat.md §10)', () => {+ const meta = { v: 1, role: 'delegation-request', delegationId: 'task-1', fromBotId: 'mimi', fromBotName: '咪咪', toBotId: null,+ toBotName: 'Cindy', parentSessionId: 'group-lane', childSessionId: 'child-1', objective: '写官网首页' };+ const task = { meta, state: 'started', title: '官网首页' };+ const posted = (id: string, authorKind: 'bot' | 'user', value: unknown) => ({ id, sequence: 7, kind: 'message', authorKind,+ authorBotId: authorKind === 'bot' ? 'mimi' : null, authorName: '', content: '', noticeCode: null, planId: null, files: [], createdAt: 70, task: value });+ const parsed = parseBotGroupChatData(chatData({ messages: [+ posted('t1', 'bot', task),+ posted('t2', 'bot', { ...task, state: 'paused' }),+ posted('t3', 'bot', { ...task, meta: { ...meta, role: 'delegation-result' } }),+ posted('t4', 'user', task),+ ] }))!;+ const byId = new Map(parsed.messages.map(message => [message.id, message]));+ expect(byId.get('t1')?.task).toEqual(task);+ expect(byId.get('t2')?.task).toBeUndefined();+ expect(byId.get('t3')?.task).toBeUndefined();+ expect(byId.get('t4')?.task).toBeUndefined();+ });+it('preserves a server join notice through the phone projection', () => {const joined = { id: 'joined', sequence: 20, kind: 'notice', authorKind: 'system', authorBotId: null,authorName: 'Taylor', content: 'Taylor joined the group', noticeCode: 'member-joined',diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.jsonindex d73540e01b..593d10ae86 100644--- a/apps/mobile/src/i18n/locales/en/groupChat.json+++ b/apps/mobile/src/i18n/locales/en/groupChat.json@@ -140,6 +140,16 @@"planning": "Splitting the work…","step": "Working on it…"},+ "task": {+ "state": {+ "started": "In progress",+ "waiting": "Waiting for your confirmation",+ "completed": "Done",+ "failed": "Failed",+ "cancelled": "Cancelled",+ "timed-out": "Timed out"+ }+ },"files": {"onComputer": "These files are on your computer. Open them there."},diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.jsonindex 4ce63ff62f..a8965fc672 100644--- a/apps/mobile/src/i18n/locales/ja/groupChat.json+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json@@ -140,6 +140,16 @@"planning": "役割分担を考えています…","step": "作業中…"},+ "task": {+ "state": {+ "started": "進行中",+ "waiting": "確認待ち",+ "completed": "完了",+ "failed": "失敗",+ "cancelled": "キャンセル済み",+ "timed-out": "タイムアウト"+ }+ },"files": {"onComputer": "ファイルはパソコンにあります。パソコンで開いてください"},diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.jsonindex d3d5d0044e..ffcb6ba8a4 100644--- a/apps/mobile/src/i18n/locales/ko/groupChat.json+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json@@ -140,6 +140,16 @@"planning": "역할을 나누는 중…","step": "작업 중…"},+ "task": {+ "state": {+ "started": "진행 중",+ "waiting": "확인 대기 중",+ "completed": "완료",+ "failed": "실패",+ "cancelled": "취소됨",+ "timed-out": "시간 초과"+ }+ },"files": {"onComputer": "파일은 컴퓨터에 있습니다. 컴퓨터에서 열어 주세요"},diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.jsonindex 525cb2a4aa..b9fd4ae8f2 100644--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json@@ -140,6 +140,16 @@"planning": "正在安排…","step": "正在做…"},+ "task": {+ "state": {+ "started": "进行中",+ "waiting": "等你确认",+ "completed": "已完成",+ "failed": "失败了",+ "cancelled": "已取消",+ "timed-out": "已超时"+ }+ },"files": {"onComputer": "文件在电脑上,回电脑打开"},diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.jsonindex c9da227d32..9374f0214c 100644--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json@@ -140,6 +140,16 @@"planning": "正在安排…","step": "正在做…"},+ "task": {+ "state": {+ "started": "進行中",+ "waiting": "等你確認",+ "completed": "已完成",+ "failed": "失敗了",+ "cancelled": "已取消",+ "timed-out": "已逾時"+ }+ },"files": {"onComputer": "檔案在電腦上,回電腦開啟"},diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsxindex 04ecb29b37..040e962040 100644--- a/apps/mobile/src/session/BotGroupChatScreen.tsx+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx@@ -68,6 +68,7 @@ import { SessionHeaderNativeBlur } from './SessionHeaderNativeControls';import { CompanionEntering } from './CompanionEntering';import { BotGroupComposer, type BotGroupSendInput } from './BotGroupComposer';import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';+import { BotGroupTaskCard } from './BotGroupTaskCard';import { BotGroupMarkdownText, BotGroupUserText } from './BotGroupMessageText';import { BotGroupQuote } from './BotGroupQuote';import {@@ -537,6 +538,8 @@ function BotGroupTimelineItem({onStart={() => onPlanAction('start')} onDismiss={() => onPlanAction('dismiss')} onEditStep={onEditStep} />: <>{quoteDisplay ? <BotGroupQuote display={quoteDisplay} /> : null}+ {/* A task this teammate started from the group; mine is live, another owner's is a snapshot. */}+ {message.task ? <BotGroupTaskCard task={message.task} owned={member?.isOwned !== false} deviceId={deviceId} /> : null}{message.attachments?.length ? <BotGroupMessageAttachments messageId={message.id} attachments={message.attachments} align="left" onResolveRemoteMedia={resolveMedia} resolveServerMedia={resolveServerMedia} /> : null}{message.content.trim() ? <BotGroupMarkdownText content={message.content} /> : null}<BotGroupHandoffFiles files={message.files} />diff --git a/apps/mobile/src/session/BotGroupTaskCard.tsx b/apps/mobile/src/session/BotGroupTaskCard.tsxnew file mode 100644index 0000000000..bdc2f2a4f9--- /dev/null+++ b/apps/mobile/src/session/BotGroupTaskCard.tsx@@ -0,0 +1,49 @@+/**+ * An independent task a teammate started from this group (bot-group-chat.md §10).+ *+ * My own teammate's task: the live task card read from the computer that runs it (same card+ * as a teammate chat). Someone else's teammate: the card as it was posted — title and state —+ * because that task runs on their computer.+ */+import { ListTodo } from 'lucide-react-native';+import { StyleSheet, View } from 'react-native';+import { useTranslation } from 'react-i18next';+import type { BotGroupTaskCardView } from '@cindy/maker-shared/botGroupChat';+import { Text } from '@/components/AppText';+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';+import { CompanionTaskCard } from './CompanionMessageCard';++export function BotGroupTaskCard({ task, owned, deviceId }: { task: BotGroupTaskCardView; owned: boolean; deviceId: string }) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const { colors } = useTheme();+ if (owned && deviceId && task.meta.parentSessionId) {+ return <View testID="botGroup.task.live">+ <CompanionTaskCard deviceId={deviceId} parentSessionId={task.meta.parentSessionId} meta={task.meta} />+ </View>;+ }+ const state = t(`groupChat.task.state.${task.state}`);+ return <View style={styles.card} testID="botGroup.task" accessibilityLabel={`${task.title} · ${state}`}>+ <ListTodo size={iconSize.sm} color={colors.textTertiary} style={styles.icon} />+ <View style={styles.body}>+ <Text numberOfLines={2} style={styles.title}>{task.title}</Text>+ <Text style={styles.state}>{state}</Text>+ {task.state === 'waiting' && task.summary ? <Text style={styles.summary}>{task.summary}</Text> : null}+ </View>+ </View>;+}++const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ card: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.sm, alignSelf: 'stretch',+ backgroundColor: colors.surfaceElevated, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,+ borderRadius: radius.container, paddingHorizontal: spacing.md, paddingVertical: spacing.sm },+ icon: { marginTop: 3 },+ body: { flex: 1, minWidth: 0, gap: 2 },+ // 行标题 role (16 / 22, 500, textPrimary).+ title: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },+ // 状态词 role (12 / 18, 400, textTertiary).+ state: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },+ // 说明 role (13 / 18, 400, textSecondary): what the task is waiting on.+ summary: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+});diff --git a/apps/mobile/src/session/CompanionMessageCard.tsx b/apps/mobile/src/session/CompanionMessageCard.tsxindex 787b7a4681..ba7bf9dade 100644--- a/apps/mobile/src/session/CompanionMessageCard.tsx+++ b/apps/mobile/src/session/CompanionMessageCard.tsx@@ -170,7 +170,8 @@ function CompanionPrivateTrace({ deviceId, meta }: { deviceId: string; meta: Bot);}-function CompanionTaskCard({+/** Also the live card of a task a teammate started from a group (BotGroupTaskCard). */+export function CompanionTaskCard({deviceId,parentSessionId,meta,diff --git a/apps/mobile/src/session/botGroupRemote.ts b/apps/mobile/src/session/botGroupRemote.tsindex cc29f47db6..3a26930e19 100644--- a/apps/mobile/src/session/botGroupRemote.ts+++ b/apps/mobile/src/session/botGroupRemote.ts@@ -14,6 +14,7 @@ import {BOT_GROUP_REMOTE_RESOURCE_KIND,isBotGroupRuntimeFailureCode,parseBotGroupQuoteView,+ parseBotGroupTaskCardView,type BotGroupAttachment,type BotGroupAttachmentCategory,type BotGroupErrorCode,@@ -205,6 +206,8 @@ function parseMessage(value: unknown): BotGroupMessageView | null {? record.noticeCode as BotGroupMessageView['noticeCode']: null;const quote = parseBotGroupQuoteView(record.quote);+ // A task this teammate started from the group (bot-group-chat.md §10); older computers send none.+ const task = authorKind === 'bot' ? parseBotGroupTaskCardView(record.task) : null;return {id: messageId,sequence,@@ -222,6 +225,7 @@ function parseMessage(value: unknown): BotGroupMessageView | null {// 引用回复 and the tombstone it degrades to; older computers send neither....(record.deleted === true ? { deleted: true } : {}),...(quote ? { quote } : {}),+ ...(task ? { task } : {}),attachments: Array.isArray(record.attachments)? record.attachments.slice(0, BOT_GROUP_ATTACHMENTS_MAX).flatMap((raw) => {const attachment = parseAttachment(raw);diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 4e2f237baf..a231618ab6 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -110,8 +110,9 @@- **插话**:本轮进行中用户又发了消息,本轮立即作废;正在发言的伙伴(同时想时是全部)被停止,未发出的回复丢弃;按新消息开启新一轮。- **停止**:用户点停止,本轮结束,正在发言的伙伴被停止。-- **失败与超时**:单个伙伴出错、没有可用模型或 5 分钟内没有回复,视为本轮不发言,群里显示一条- 轻提示;不影响其余伙伴继续。+- **失败与超时**:单个伙伴出错、没有可用模型或 2 小时内没有回复(与分工步骤同一上限,等待用户+ 确认的时间不计),视为本轮不发言,群里显示一条轻提示;不影响其余伙伴继续。普通回复里伙伴照样可以+ 跑工具、实测、看文件,宿主不用更短的墙钟把它切断;专线真正挂住由会话自己的空闲看门狗收口。发送前拒绝同样立即收尾,不等待模型事件或超时;按输入 clientId 匹配执行,旧输入不能结束新执行,用户主动停止不作为失败。隐藏输入从队列撤下,避免下一条群消息带出已失败的旧输入。提示尽可能说明原因和解决办法:图片能力、模型可用性、认证、限流、额度、网络和超时分别本地化,@@ -339,7 +340,7 @@ Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授群专线的 `role=group` 是来源身份,不等于只读历史任务,也不单独构成授权。读取自己的 Profile、能力与 Skill 目录时,必须核对活跃执行、伙伴归属、成员状态、授权版本及执行租约;只聊天的专线仍不可读取私人资料。群主身份不能替代伙伴主人身份。-只有伙伴主人发起且当前授权有效的执行,才能从群里启动独立开发任务或发送私聊。独立任务保留群内调用身份与来源范围,沿用普通任务的权限档、审批、隔离目录和工作目录注册。任务卡、待确认事项和结果回到**该主人与该伙伴的私聊**;工具返回 `completion_destination=teammate-private-chat`,伙伴须告知去向。非主人获得的群工具授权不包含此独立任务能力。群内只能查询或控制由同一授权专线创建的独立任务;主人仍可从私聊管理已启动的任务。群执行结束不会取消已经正式启动的独立任务,后续群内操作必须重新验证当前执行。+只有伙伴主人发起且当前授权有效的执行,才能从群里启动独立开发任务或发送私聊。独立任务保留群内调用身份与来源范围,沿用普通任务的权限档、审批、隔离目录和工作目录注册。**从群里启动的任务住在这个群里**:父任务就是发起它的群专线,不再改挂或新建私聊。任务一建立,伙伴就以自己的身份在群里发一条带任务卡(`cindy.task` 卡片块,带 fallback 文字)的消息;子任务要确认时再发一条「等你确认」的卡(权限请求只说需要批准,不带工具名和参数;提问带问题原文),主人从卡片打开任务作答;任务结束后结果正文、终态卡与交付文件作为伙伴的群消息回到群里。这些消息在任何执行之外以伙伴 actor 发出,不唤醒群专线,也不唤醒私聊;工具返回 `completion_destination=group`,伙伴只需告诉群里开了什么。群的消息通道明确拒绝(伙伴已不在群、群已归档、本机旧式群)时,结果退回该主人与该伙伴的私聊,不丢失。主人的桌面与手机看到的是实时任务卡(读本机委派行),其他成员看到卡片发出时的标题与状态。非主人获得的群工具授权不包含此独立任务能力。群内只能查询或控制由同一授权专线创建的独立任务;主人仍可从私聊管理已启动的任务。群执行结束不会取消已经正式启动的独立任务,后续群内操作必须重新验证当前执行。非主人群工具授权仅允许读取伙伴自身资料、已选能力和自己的技能;应用级能力目录与默认模型查询仍须当前主人执行授权。diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.tsindex 3182ba29ce..6a5e7d96de 100644--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts@@ -328,7 +328,7 @@ describe("cindy_helper MCP server", () => {delegationId: "session-task-1",childSessionId: "desktop-child-session",status: "running",- completionDestination: 'teammate-private-chat',+ completionDestination: 'group',deadlineAt: 1_788_000_000_000,}));const messageSessionTask = vi.fn(async () => ({@@ -414,7 +414,7 @@ describe("cindy_helper MCP server", () => {expect(sessionTask).toMatchObject({ok: true,action: "start_session_task",- completion_destination: 'teammate-private-chat',+ completion_destination: 'group',task_id: "session-task-1",session_id: "desktop-child-session",deadline_at: 1_788_000_000_000,diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex 254c613901..d8db28550c 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -428,8 +428,8 @@ function registerStartSessionTaskEntry(expects_result: true,...(result.completionDestination ? { completion_destination: result.completionDestination } : {}),guidance:- (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. '+ (result.completionDestination === 'group'+ ? 'This task lives in this group: its card is already posted here, and anything it needs confirmed plus its final result will arrive here as your own messages. Tell the group briefly what you started; do not promise a private-chat update. ': '') + "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);diff --git a/packages/maker-shared/src/__tests__/botGroupTask.test.ts b/packages/maker-shared/src/__tests__/botGroupTask.test.tsnew file mode 100644index 0000000000..51b2705cf1--- /dev/null+++ b/packages/maker-shared/src/__tests__/botGroupTask.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';+import type { BotCollaborationMeta } from '../botCollaboration';+import { buildBotGroupTaskCard, parseBotGroupTaskCardView, readBotGroupTaskCard } from '../botGroupTask';++const meta: BotCollaborationMeta = {+ v: 1, role: 'delegation-request', delegationId: 'task-1', fromBotId: 'bot-a', fromBotName: 'LiZi',+ toBotId: null, toBotName: 'Cindy', parentSessionId: 'group-lane', childSessionId: 'child-1', objective: 'Write the launch post',+};++describe('group task card (bot-group-chat.md §10)', () => {+ it('builds a card older clients read as one fallback line and new clients read back as the view', () => {+ const card = buildBotGroupTaskCard({ meta, state: 'started', title: 'Launch post' });+ expect(card).toMatchObject({ type: 'card', namespace: 'cindy.task', schemaRevision: 1, fallback: '[任务] Launch post · 进行中' });+ expect(readBotGroupTaskCard(card)).toEqual({ meta, state: 'started', title: 'Launch post' });+ expect(parseBotGroupTaskCardView(card.data)).toEqual({ meta, state: 'started', title: 'Launch post' });+ });++ it('keeps what a waiting task asks for, clipped, and never a tool argument block', () => {+ const summary = `1. Which audience?(Developers / Everyone)\n${'x'.repeat(500)}`;+ const card = buildBotGroupTaskCard({ meta, state: 'waiting', title: 'Launch post', summary });+ expect(card.data.summary!.length).toBeLessThanOrEqual(400);+ expect(card.fallback.startsWith('[任务] Launch post · 等你确认:1. Which audience?')).toBe(true);+ expect(readBotGroupTaskCard(card)?.summary).toBe(card.data.summary);+ });++ it.each([+ ['wrong namespace', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }), namespace: 'cindy.plan' }],+ ['future revision', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }), schemaRevision: 2 }],+ ['unknown state', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }), data: { meta, state: 'paused', title: 't' } }],+ ['result receipt instead of the anchor', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }), data: { meta: { ...meta, role: 'delegation-result' }, state: 'started', title: 't' } }],+ ['missing meta', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }), data: { state: 'started', title: 't' } }],+ ['not a card', { type: 'text', text: '[任务] t · 进行中' }],+ ])('rejects a malformed card (%s) so the message falls back to text', (_label, block) => {+ expect(readBotGroupTaskCard(block)).toBeNull();+ });++ it('rejects a view whose task anchor is not a delegation request', () => {+ expect(parseBotGroupTaskCardView({ meta: { ...meta, role: 'interjection' }, state: 'completed', title: 't' })).toBeNull();+ expect(parseBotGroupTaskCardView(null)).toBeNull();+ });+});diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex a92c6f6b4f..ef8d11d0e1 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -3,8 +3,10 @@* Product rules: docs/product-rules/bot-group-chat.md.*/import type { BotGroupQuoteInput, BotGroupQuoteView } from './botGroupQuote';+import type { BotGroupTaskCardView } from './botGroupTask';export * from './botGroupQuote';+export * from './botGroupTask';export const BOT_GROUP_MIN_MEMBERS = 2;export const BOT_GROUP_MAX_MEMBERS = 6;@@ -144,6 +146,8 @@ export interface BotGroupMessageView {replyCount?: number;/** 引用回复: the earlier main-timeline message this one quotes; not a Thread parent. */quote?: BotGroupQuoteView;+ /** An independent task this teammate started from the group (bot-group-chat.md §10). */+ task?: BotGroupTaskCardView;reactions?: Array<{ emoji: string; count: number; me: boolean }>;id: string;sequence: number;diff --git a/packages/maker-shared/src/botGroupTask.ts b/packages/maker-shared/src/botGroupTask.tsnew file mode 100644index 0000000000..179a2b9ad2--- /dev/null+++ b/packages/maker-shared/src/botGroupTask.ts@@ -0,0 +1,92 @@+/**+ * An independent background task started from a group by its owner's teammate+ * (docs/product-rules/bot-group-chat.md §10). The task lives in the group: its+ * card, confirmations and result are posted there as the teammate's own messages,+ * each carrying one of these cards. Older clients read the `fallback` line.+ */+import { readBotCollaborationMeta, type BotCollaborationMeta } from './botCollaboration';++export const BOT_GROUP_TASK_NAMESPACE = 'cindy.task';+export const BOT_GROUP_TASK_SCHEMA_REVISION = 1;++/** What the card said when it was posted; the owner's clients read the live row instead. */+export type BotGroupTaskCardState = 'started' | 'waiting' | 'completed' | 'failed' | 'cancelled' | 'timed-out';+const STATES: readonly BotGroupTaskCardState[] = ['started', 'waiting', 'completed', 'failed', 'cancelled', 'timed-out'];++export interface BotGroupTaskCardView {+ /** The task anchor (`delegation-request`); `parentSessionId` is the group lane on the owner's computer. */+ meta: BotCollaborationMeta;+ state: BotGroupTaskCardState;+ /** Task title when this card was posted. */+ title: string;+ /** What the task is waiting on (only for `waiting`). */+ summary?: string;+}++export interface BotGroupTaskCard {+ type: 'card';+ namespace: typeof BOT_GROUP_TASK_NAMESPACE;+ schemaRevision: typeof BOT_GROUP_TASK_SCHEMA_REVISION;+ fallback: string;+ data: { meta: BotCollaborationMeta; state: BotGroupTaskCardState; title: string; summary?: string };+}++const TITLE_MAX = 120;+const SUMMARY_MAX = 400;++const STATE_FALLBACK: Record<BotGroupTaskCardState, string> = {+ started: '进行中',+ waiting: '等你确认',+ completed: '已完成',+ failed: '失败了',+ cancelled: '已取消',+ 'timed-out': '已超时',+};++function clip(value: string, max: number): string {+ const text = value.replace(/\s+/g, ' ').trim();+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;+}++export function buildBotGroupTaskCard(view: BotGroupTaskCardView): BotGroupTaskCard {+ const title = clip(view.title, TITLE_MAX) || '后台任务';+ const summary = view.summary ? clip(view.summary, SUMMARY_MAX) : undefined;+ return {+ type: 'card',+ namespace: BOT_GROUP_TASK_NAMESPACE,+ schemaRevision: BOT_GROUP_TASK_SCHEMA_REVISION,+ fallback: `[任务] ${title} · ${STATE_FALLBACK[view.state]}${summary ? `:${summary}` : ''}`,+ data: { meta: view.meta, state: view.state, title, ...(summary ? { summary } : {}) },+ };+}++function viewFromFields(data: Record<string, unknown>): BotGroupTaskCardView | null {+ const meta = readBotCollaborationMeta(data.meta);+ if (!meta || meta.role !== 'delegation-request') return null;+ if (typeof data.state !== 'string' || !STATES.includes(data.state as BotGroupTaskCardState)) return null;+ if (typeof data.title !== 'string') return null;+ if (data.summary !== undefined && typeof data.summary !== 'string') return null;+ return {+ meta,+ state: data.state as BotGroupTaskCardState,+ title: clip(data.title, TITLE_MAX),+ ...(data.summary ? { summary: clip(data.summary, SUMMARY_MAX) } : {}),+ };+}++/** Strict: a malformed card is no card, and the message renders as plain text. */+export function readBotGroupTaskCard(block: unknown): BotGroupTaskCardView | null {+ if (!block || typeof block !== 'object') return null;+ const value = block as { type?: unknown; namespace?: unknown; schemaRevision?: unknown; data?: unknown };+ if (value.type !== 'card' || value.namespace !== BOT_GROUP_TASK_NAMESPACE+ || value.schemaRevision !== BOT_GROUP_TASK_SCHEMA_REVISION) return null;+ const data = value.data && typeof value.data === 'object' && !Array.isArray(value.data)+ ? value.data as Record<string, unknown> : null;+ return data ? viewFromFields(data) : null;+}++/** The card as a controller receives it in a message view (same fields, already projected). */+export function parseBotGroupTaskCardView(value: unknown): BotGroupTaskCardView | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ return viewFromFields(value as Record<string, unknown>);+}