Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 群任务结果投递按单文件跳过本地拒绝、分批 20 个附件、超时卡归一化、fallback 本地化
Chris76278af72bab
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 671c428d81..fe158cf720 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -4260,6 +4260,29 @@ describe('Bot Session task end-to-end runtime', () => {} finally { release(); runtime.dispose(); }});+ it('posts a timed-out group task to the group as timed out, in the sender\'s language, not as failed', async () => {+ await seedPair(); seedGroupLane();+ vi.useFakeTimers();+ setMainLocale('en');+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ const postGroupTaskMessage = vi.fn(async (input: { clientId: string }) => ({ ok: true as const, messageId: `posted:${input.clientId}` }));+ const runtime = createDelegationRuntime({ postGroupTaskMessage });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Deadline work.', timeoutMs: 1000 });+ if (!task.ok) throw new Error(task.message);+ runtime.advance(1000);+ await vi.advanceTimersByTimeAsync(1000);+ // Stored as failed + TIMEOUT; every reader of the card sees the same normalised state as the owner's live view.+ expect(h.sqlite!.prepare('SELECT status FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).toBe('failed');+ expect(await runtime.delegation.getSessionTask('group-lane', task.delegationId)).toMatchObject({ task: { status: 'timed-out' } });+ expect(postGroupTaskMessage).toHaveBeenLastCalledWith(expect.objectContaining({+ clientId: `bot-delegation-task:${task.delegationId}:1:result`,+ card: expect.objectContaining({ fallback: '[Task] Deadline work. · Timed out', data: expect.objectContaining({ state: 'timed-out' }) }),+ }));+ expect(h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).not.toBeNull();+ } finally { release(); runtime.dispose(); vi.useRealTimers(); }+ });+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();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex b74c28aea1..b9686ab9ec 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -481,9 +481,33 @@ describe('Chat Server result delivery and refresh', () => {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 taskLabels = { task: 'Task', untitled: 'Background task', states: { started: 'In progress', waiting: 'Waiting', completed: 'Done', failed: 'Failed', cancelled: 'Cancelled', 'timed-out': 'Timed out' } };+ const taskCard = buildBotGroupTaskCard({ meta: taskMeta, state: 'started', title: 'Launch post' }, taskLabels);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 });+ // Delivery files are read from disk before upload: a real directory, cleaned up after each test.+ let deliveryDir = '';+ const deliveryFiles = async (count: number): Promise<Array<{ absolutePath: string }>> => {+ const fs = await import('node:fs/promises');+ const os = await import('node:os');+ const nodePath = await import('node:path');+ deliveryDir = await fs.mkdtemp(nodePath.join(os.tmpdir(), 'cindy-task-files-'));+ return Promise.all(Array.from({ length: count }, async (_, index) => {+ const absolutePath = nodePath.join(deliveryDir, `file-${String(index + 1).padStart(2, '0')}.md`);+ await fs.writeFile(absolutePath, `file ${index + 1}`);+ return { absolutePath };+ }));+ };+ afterEach(async () => {+ if (deliveryDir) await (await import('node:fs/promises')).rm(deliveryDir, { recursive: true, force: true });+ deliveryDir = '';+ // Per-file upload stand-ins must not outlive their test: later tests expect the default empty upload.+ fixture.upload.mockReset();+ fixture.upload.mockImplementation(async () => []);+ });+ const mediaBlock = (name: string) => ({ type: 'media', mediaId: `60000000-0000-4000-8000-${name.replace(/\D/g, '').padStart(12, '0')}`, caption: name });+ const uploadEach = (refuse?: { name: string; error: Error }) => fixture.upload.mockImplementation(async (...args: unknown[]) =>+ (args[2] as Array<{ name: string }>).map(attachment => { if (attachment.name === refuse?.name) throw refuse.error; return mediaBlock(attachment.name); }));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' }];@@ -493,8 +517,9 @@ describe('Chat Server result delivery and refresh', () => {if (route.endsWith('/messages') && method === 'POST') return { body: { id: '70000000-0000-4000-8000-000000000001' } };return response(route);});+ const [file] = await deliveryFiles(1);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' }] });+ text: 'Done: the post is drafted.', card: { ...taskCard, data: { ...taskCard.data, state: 'completed' } }, files: [file!, { 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: [],@@ -502,11 +527,53 @@ describe('Chat Server result delivery and refresh', () => {{ 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);+ // A delivery file that no longer exists is simply not uploaded; the existing one goes up under the message identity.+ expect(fixture.upload).toHaveBeenCalledExactlyOnceWith(roomId, 'bot-delegation-task:task-1:1:result',+ [expect.objectContaining({ path: file!.absolutePath, name: 'file-01.md', size: 6 })], botId);expect(deps.onChanged).toHaveBeenCalledWith(expect.objectContaining({ groupId: roomId, change: 'messages' }), undefined);});+ it('leaves out one file this computer cannot send and still posts the result with the others', async () => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ const files = await deliveryFiles(3);+ uploadEach({ name: 'file-02.md', error: new Error('ATTACHMENT_UNAVAILABLE') });+ const warn = vi.fn();+ deps.log = { warn };+ 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 { 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.', card: taskCard, files });+ expect(posted).toEqual({ ok: true, messageId: '70000000-0000-4000-8000-000000000001' });+ const sent = fixture.handle.mock.calls.filter(([route, method]) => route === `/conversations/${roomId}/messages` && method === 'POST');+ expect(sent).toHaveLength(1);+ expect(sent[0][2].content).toEqual([{ type: 'text', text: 'Done.' }, taskCard, mediaBlock('file-01.md'), mediaBlock('file-03.md')]);+ expect(warn).toHaveBeenCalledWith('Chat task delivery file refused', expect.objectContaining({ groupId: roomId }));+ });++ it('continues more than 20 delivery files in follow-up messages under stable operation ids', async () => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ const files = await deliveryFiles(23);+ uploadEach();+ let posts = 0;+ 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 { body: { id: `7000000${++posts}-0000-4000-8000-000000000001` } };+ return response(route);+ });+ const text = `${'a'.repeat(7990)}\n${'b'.repeat(20)}`;+ const posted = await service.postCompanionTaskMessage({ groupId: roomId, botId: 'local-bot', clientId: 'bot-delegation-task:task-1:1:result', text, card: taskCard, files });+ expect(posted).toEqual({ ok: true, messageId: '70000001-0000-4000-8000-000000000001' });+ const bodies = fixture.handle.mock.calls.filter(([route, method]) => route === `/conversations/${roomId}/messages` && method === 'POST').map(([, , body]) => body);+ expect(bodies.map(body => body.operationId)).toEqual(['bot-delegation-task:task-1:1:result', 'bot-delegation-task:task-1:1:result:2', 'bot-delegation-task:task-1:1:result:files:2']);+ expect(bodies[0].content).toEqual([{ type: 'text', text: 'a'.repeat(7990) }, taskCard, ...files.slice(0, 20).map((_, index) => mediaBlock(`file-${String(index + 1).padStart(2, '0')}.md`))]);+ expect(bodies[1].content).toEqual([{ type: 'text', text: 'b'.repeat(20) }]);+ expect(bodies[2].content).toEqual([mediaBlock('file-21.md'), mediaBlock('file-22.md'), mediaBlock('file-23.md')]);+ expect(bodies.every(body => body.content.filter((block: { type: string }) => block.type === 'media').length <= 20)).toBe(true);+ });+it.each([['bot left the group', 403, false],['server unavailable', 503, true],@@ -544,6 +611,7 @@ describe('Chat Server result delivery and refresh', () => {it.each([['a transient upload failure is retried with the message', new Error('ECONNRESET'), { ok: false, retryable: true }, 0],['a file the server refuses is left out, the result still posts', new ChatResponseError('PAYLOAD_TOO_LARGE', 413), { ok: true }, 1],+ ['a file too large to ever send is left out, the result still posts', new Error('ATTACHMENT_TOO_LARGE'), { ok: true }, 1],])('%s', async (_label, failure, expected, posts) => {fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];fixture.upload.mockRejectedValueOnce(failure);@@ -553,7 +621,7 @@ describe('Chat Server result delivery and refresh', () => {return response(route);});const posted = await service.postCompanionTaskMessage({ groupId: roomId, botId: 'local-bot', clientId: 'bot-delegation-task:task-1:1:result',- text: 'Done.', card: taskCard, files: [{ absolutePath: '/no/such/file.md' }] });+ text: 'Done.', card: taskCard, files: await deliveryFiles(1) });expect(posted).toMatchObject(expected);const sent = fixture.handle.mock.calls.filter(([route, method]) => route === `/conversations/${roomId}/messages` && method === 'POST');expect(sent).toHaveLength(posts);diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex 3ec97c1817..d26d4311c1 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -47,7 +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 { buildBotGroupTaskCard, type BotGroupTaskCardLabels, type BotGroupTaskCardState } from '../../shared/botGroupChat.js';+import { t } from '../i18n.js';import type { BotGroupTaskPostInput, BotGroupTaskPostResult } from './botGroupChatService.js';import { ensureBotWorkspaceDir } from './botProfileFolder.js';import type { SessionQueuedMessageControlResult, SessionSteerResult, SessionStopResult } from './sessionControlService.js';@@ -807,6 +808,26 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {'id' | 'requestingBotId' | 'targetBotId' | 'objective' | 'parentSessionId' | 'childSessionId'>;+ /** The card's fallback line, in this computer's UI language, for clients that do not know the card. */+ const groupTaskCardLabels = (): BotGroupTaskCardLabels => ({+ task: t('bots.groupChat.task.label'),+ untitled: t('bots.collab.backgroundTask'),+ states: {+ started: t('bots.groupChat.task.state.started'),+ waiting: t('bots.groupChat.task.state.waiting'),+ completed: t('bots.groupChat.task.state.completed'),+ failed: t('bots.groupChat.task.state.failed'),+ cancelled: t('bots.groupChat.task.state.cancelled'),+ 'timed-out': t('bots.groupChat.task.state.timed-out'),+ },+ });++ /** The state a terminal task shows on its card: a timeout is stored as `failed` + `TIMEOUT` error. */+ const terminalCardState = (+ row: { status: Extract<DelegationStatus, 'completed' | 'failed' | 'cancelled' | 'timed-out'>; lastError?: string | null },+ ): BotGroupTaskCardState =>+ sessionTaskViewStatus({ status: row.status, lastError: row.lastError ?? null }) === 'timed-out' ? 'timed-out' : row.status;+/** One task event as the teammate's own group message, carrying the task card. */const postGroupTaskEvent = async (home: { groupId: string },@@ -823,7 +844,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {state: event.state,title: child?.title?.trim() || row.objective.split('\n')[0]!.slice(0, 120),...(event.summary ? { summary: event.summary } : {}),- });+ }, groupTaskCardLabels());return deps.postGroupTaskMessage({groupId: home.groupId, botId: row.requestingBotId, clientId: event.clientId, text: event.text, card,...(event.files?.length ? { files: event.files } : {}),@@ -1074,7 +1095,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const posted = await postGroupTaskEvent(home, params, {clientId: `bot-delegation-task:${params.id}:${params.runSequence}:result`,text: params.resultSummary ?? '',- state: params.status,+ state: terminalCardState(params),files: artifacts.filter((file) => file.status !== 'deleted').map((file) => ({ absolutePath: file.absolutePath })),});if (!(await completionStillPending())) return false;diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 3cda975100..adfb9361e1 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -26,7 +26,7 @@ import { botGroups, botProfiles, botGroupMembers, botGroupMessages, botGroupPlanimport { UI_ACTION_TRIGGER_PREFIX } from '../../shared/interruptedTurn.js';import { untrustedJsonBlock } from '../../shared/untrustedPrompt.js';import {- BOT_GROUP_CLIENT_ID, isBotGroupNoReplyText,+ BOT_GROUP_ATTACHMENTS_MAX, BOT_GROUP_CLIENT_ID, isBotGroupNoReplyText,isBotGroupRuntimeFailureCode, type BotGroupRuntimeFailureCode,readImportedBotGroupRuntimeFailureCode,readBotGroupExecutionFailure, type BotGroupExecutionFailureView,@@ -93,6 +93,8 @@ const recoverableAuth = (error: ChatResponseError) => error.status === 401&& (CHAT_REFRESHABLE_ERROR_CODES.has(error.message) || error.message === 'INVALID_CHAT_RESPONSE');const retryableResponse = (error: ChatResponseError) => recoverableAuth(error)|| error.status >= 500 || [408, 429].includes(error.status);+/** A file this computer will never be able to send (chatServerMedia): retrying cannot help. */+const LOCAL_FILE_REFUSALS = new Set(['ATTACHMENT_TOO_LARGE', 'ATTACHMENT_UNAVAILABLE']);const id = z.string().uuid();const memberJoinedTrigger = z.object({ type: z.literal('member.joined'), messageId: id, actorId: id,displayName: z.string().min(1).refine(value => value.trim().length > 0) }).strict();@@ -1574,27 +1576,39 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDmimeType: 'application/octet-stream', size: stat.size, path: file.absolutePath, url: null });} catch { /* a file deleted since the task finished is simply not delivered */ }}- // A transient upload failure is reported as retryable so the files are sent later with the- // same message; only a file the server definitely refuses (too large, unsupported) is left out.- let uploaded: ChatContentBlock[];- try {- uploaded = await media.upload(roomId, input.clientId, produced, actor.id);- } catch (error) {- if (!(error instanceof ChatResponseError) || retryableResponse(error)) throw error;- deps.log?.warn('Chat task delivery files refused', { groupId: roomId, ...chatErrorDiagnostic(error) });- uploaded = [];+ // Files go up one at a time so a refused file never holds back the others: a file this+ // computer cannot send (empty, over the size limit) or the server definitely refuses is+ // left out with a warning, while a transient failure keeps the whole message for a retry.+ const uploaded: ChatContentBlock[] = [];+ for (const file of produced) {+ try {+ uploaded.push(...await media.upload(roomId, input.clientId, [file], actor.id));+ } catch (error) {+ const refusedHere = error instanceof Error && !(error instanceof ChatResponseError) && LOCAL_FILE_REFUSALS.has(error.message);+ if (!refusedHere && (!(error instanceof ChatResponseError) || retryableResponse(error))) throw error;+ deps.log?.warn('Chat task delivery file refused', { groupId: roomId, ...chatErrorDiagnostic(error) });+ }}- // The server takes 8000 characters per message: a longer result continues in follow-up- // messages (same idempotent operation id family), never silently cut.+ // The server takes 8000 characters and BOT_GROUP_ATTACHMENTS_MAX files per message: a longer+ // result and further files continue in follow-up messages (same idempotent operation id+ // family), never silently cut.const [first = '', ...rest] = splitChatMessageText(input.text.trim());+ const fileBatches: ChatContentBlock[][] = [];+ for (let at = 0; at < uploaded.length; at += BOT_GROUP_ATTACHMENTS_MAX) fileBatches.push(uploaded.slice(at, at + BOT_GROUP_ATTACHMENTS_MAX));+ const [firstFiles = [], ...moreFiles] = fileBatches;const posted = await api<{ id: string }>(`/conversations/${roomId}/messages`, 'POST', {- operationId: input.clientId, content: [...(first ? [{ type: 'text', text: first }] : []), input.card, ...uploaded], mentions: [],+ operationId: input.clientId, content: [...(first ? [{ type: 'text', text: first }] : []), input.card, ...firstFiles], mentions: [],}, actor.id);for (const [index, text] of rest.entries()) {await api(`/conversations/${roomId}/messages`, 'POST', {operationId: `${input.clientId}:${index + 2}`, content: [{ type: 'text', text }], mentions: [],}, actor.id);}+ for (const [index, files] of moreFiles.entries()) {+ await api(`/conversations/${roomId}/messages`, 'POST', {+ operationId: `${input.clientId}:files:${index + 2}`, content: files, mentions: [],+ }, actor.id);+ }changed(roomId);return { ok: true, messageId: posted.id };} catch (error) {diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex af964cc003..151468f1d5 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9168,6 +9168,7 @@"planning": "Splitting the work…"},"task": {+ "label": "Task","state": {"started": "In progress","waiting": "Waiting for your confirmation",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 26559cfc99..55fea727db 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9131,6 +9131,7 @@"planning": "役割分担を考えています…"},"task": {+ "label": "タスク","state": {"started": "進行中","waiting": "確認待ち",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 71682a71d4..d848794c10 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9131,6 +9131,7 @@"planning": "역할을 나누는 중…"},"task": {+ "label": "작업","state": {"started": "진행 중","waiting": "확인 대기 중",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 63a987f377..e6c1f1e36c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9131,6 +9131,7 @@"planning": "正在安排…"},"task": {+ "label": "任务","state": {"started": "进行中","waiting": "等你确认",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 5ec27a25eb..6506d654f9 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9131,6 +9131,7 @@"planning": "正在安排…"},"task": {+ "label": "任務","state": {"started": "進行中","waiting": "等你確認",diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.tsindex 5598a57748..d16949ed7b 100644--- a/apps/mobile/src/__tests__/chatServerClient.test.ts+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts@@ -31,7 +31,8 @@ describe('direct Chat Server client', () => {it('reads a task card on a teammate message as its task, and only there (bot-group-chat.md §10)', () => {const card = buildBotGroupTaskCard({ meta: { v: 1, role: 'delegation-request', delegationId: 'task-1', fromBotId: 'bot', fromBotName: 'Bot',- toBotId: null, toBotName: 'Cindy', parentSessionId: 'lane', childSessionId: 'child', objective: 'Launch post' }, state: 'started', title: 'Launch post' });+ toBotId: null, toBotName: 'Cindy', parentSessionId: 'lane', childSessionId: 'child', objective: 'Launch post' }, state: 'started', title: 'Launch post' },+ { task: 'Task', untitled: 'Background task', states: { started: 'In progress', waiting: 'Waiting', completed: 'Done', failed: 'Failed', cancelled: 'Cancelled', 'timed-out': 'Timed out' } });const fromBot = { ...message(20), authorId: id(12), author: { kind: 'bot', name: 'Bot' }, content: [{ type: 'text', text: 'Started it.' }, card] };const fromHuman = { ...message(21), content: [card, { type: 'text', text: 'Pasted a card' }] };const view = chatGroupView({ snapshot: snapshot(), messages: [fromBot, fromHuman], before: null }, id(11));diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex a231618ab6..e57c3461b8 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -340,7 +340,7 @@ Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授群专线的 `role=group` 是来源身份,不等于只读历史任务,也不单独构成授权。读取自己的 Profile、能力与 Skill 目录时,必须核对活跃执行、伙伴归属、成员状态、授权版本及执行租约;只聊天的专线仍不可读取私人资料。群主身份不能替代伙伴主人身份。-只有伙伴主人发起且当前授权有效的执行,才能从群里启动独立开发任务或发送私聊。独立任务保留群内调用身份与来源范围,沿用普通任务的权限档、审批、隔离目录和工作目录注册。**从群里启动的任务住在这个群里**:父任务就是发起它的群专线,不再改挂或新建私聊。任务一建立,伙伴就以自己的身份在群里发一条带任务卡(`cindy.task` 卡片块,带 fallback 文字)的消息;子任务要确认时再发一条「等你确认」的卡(权限请求只说需要批准,不带工具名和参数;提问带问题原文),主人从卡片打开任务作答;任务结束后结果正文、终态卡与交付文件作为伙伴的群消息回到群里。这些消息在任何执行之外以伙伴 actor 发出,不唤醒群专线,也不唤醒私聊;工具返回 `completion_destination=group`,伙伴只需告诉群里开了什么。群的消息通道明确拒绝(伙伴已不在群、群已归档、本机旧式群)时,结果退回该主人与该伙伴的私聊,不丢失。主人的桌面与手机看到的是实时任务卡(读本机委派行),其他成员看到卡片发出时的标题与状态。非主人获得的群工具授权不包含此独立任务能力。群内只能查询或控制由同一授权专线创建的独立任务;主人仍可从私聊管理已启动的任务。群执行结束不会取消已经正式启动的独立任务,后续群内操作必须重新验证当前执行。+只有伙伴主人发起且当前授权有效的执行,才能从群里启动独立开发任务或发送私聊。独立任务保留群内调用身份与来源范围,沿用普通任务的权限档、审批、隔离目录和工作目录注册。**从群里启动的任务住在这个群里**:父任务就是发起它的群专线,不再改挂或新建私聊。任务一建立,伙伴就以自己的身份在群里发一条带任务卡(`cindy.task` 卡片块,带 fallback 文字;fallback 由发送端按本机界面语言生成,卡片数据本身不含语言)的消息;子任务要确认时再发一条「等你确认」的卡(权限请求只说需要批准,不带工具名和参数;提问带问题原文),主人从卡片打开任务作答;任务结束后结果正文、终态卡与交付文件作为伙伴的群消息回到群里。终态卡与主人实时任务卡同一口径:超时任务显示「已超时」,不是「失败了」。交付文件逐个上传,本机发不出去的文件(空文件、超过 100 MB)和服务端明确拒绝的文件跳过并记日志,其余照常送达;只有临时故障才整条稍后重试。超过一条消息 20 个附件上限的文件,与超长正文一样,在同一幂等 ID 家族的后续消息里继续发,不截断。这些消息在任何执行之外以伙伴 actor 发出,不唤醒群专线,也不唤醒私聊;工具返回 `completion_destination=group`,伙伴只需告诉群里开了什么。群的消息通道明确拒绝(伙伴已不在群、群已归档、本机旧式群)时,结果退回该主人与该伙伴的私聊,不丢失。主人的桌面与手机看到的是实时任务卡(读本机委派行),其他成员看到卡片发出时的标题与状态。非主人获得的群工具授权不包含此独立任务能力。群内只能查询或控制由同一授权专线创建的独立任务;主人仍可从私聊管理已启动的任务。群执行结束不会取消已经正式启动的独立任务,后续群内操作必须重新验证当前执行。非主人群工具授权仅允许读取伙伴自身资料、已选能力和自己的技能;应用级能力目录与默认模型查询仍须当前主人执行授权。diff --git a/packages/maker-shared/src/__tests__/botGroupTask.test.ts b/packages/maker-shared/src/__tests__/botGroupTask.test.tsindex 51b2705cf1..bf4398cfae 100644--- a/packages/maker-shared/src/__tests__/botGroupTask.test.ts+++ b/packages/maker-shared/src/__tests__/botGroupTask.test.ts@@ -1,35 +1,45 @@import { describe, expect, it } from 'vitest';import type { BotCollaborationMeta } from '../botCollaboration';-import { buildBotGroupTaskCard, parseBotGroupTaskCardView, readBotGroupTaskCard } from '../botGroupTask';+import { buildBotGroupTaskCard, parseBotGroupTaskCardView, readBotGroupTaskCard, type BotGroupTaskCardLabels } 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',};+const en: BotGroupTaskCardLabels = { task: 'Task', untitled: 'Background task',+ states: { started: 'In progress', waiting: 'Waiting for your confirmation', completed: 'Done', failed: 'Failed', cancelled: 'Cancelled', 'timed-out': 'Timed out' } };+const zh: BotGroupTaskCardLabels = { task: '任务', untitled: '后台任务',+ states: { started: '进行中', waiting: '等你确认', completed: '已完成', failed: '失败了', cancelled: '已取消', 'timed-out': '已超时' } };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 · 进行中' });+ const card = buildBotGroupTaskCard({ meta, state: 'started', title: 'Launch post' }, en);+ expect(card).toMatchObject({ type: 'card', namespace: 'cindy.task', schemaRevision: 1, fallback: '[Task] Launch post · In progress' });expect(readBotGroupTaskCard(card)).toEqual({ meta, state: 'started', title: 'Launch post' });expect(parseBotGroupTaskCardView(card.data)).toEqual({ meta, state: 'started', title: 'Launch post' });});+ it('writes the fallback line in the sender\'s language and keeps the card data language-free', () => {+ expect(buildBotGroupTaskCard({ meta, state: 'timed-out', title: '' }, zh)).toMatchObject({+ fallback: '[任务] 后台任务 · 已超时', data: { meta, state: 'timed-out', title: '后台任务' } });+ expect(buildBotGroupTaskCard({ meta, state: 'timed-out', title: '' }, en).fallback).toBe('[Task] Background task · Timed out');+ });+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 });+ const card = buildBotGroupTaskCard({ meta, state: 'waiting', title: 'Launch post', summary }, en);expect(card.data.summary!.length).toBeLessThanOrEqual(400);- expect(card.fallback.startsWith('[任务] Launch post · 等你确认:1. Which audience?')).toBe(true);+ expect(card.fallback.startsWith('[Task] Launch post · Waiting for your confirmation: 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 · 进行中' }],+ ['wrong namespace', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }, en), namespace: 'cindy.plan' }],+ ['future revision', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }, en), schemaRevision: 2 }],+ ['unknown state', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }, en), data: { meta, state: 'paused', title: 't' } }],+ ['result receipt instead of the anchor', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }, en), data: { meta: { ...meta, role: 'delegation-result' }, state: 'started', title: 't' } }],+ ['missing meta', { ...buildBotGroupTaskCard({ meta, state: 'started', title: 't' }, en), data: { state: 'started', title: 't' } }],+ ['not a card', { type: 'text', text: '[Task] t · In progress' }],])('rejects a malformed card (%s) so the message falls back to text', (_label, block) => {expect(readBotGroupTaskCard(block)).toBeNull();});diff --git a/packages/maker-shared/src/botGroupTask.ts b/packages/maker-shared/src/botGroupTask.tsindex 179a2b9ad2..6e1183888e 100644--- a/packages/maker-shared/src/botGroupTask.ts+++ b/packages/maker-shared/src/botGroupTask.ts@@ -34,28 +34,31 @@ export interface BotGroupTaskCard {const TITLE_MAX = 120;const SUMMARY_MAX = 400;-const STATE_FALLBACK: Record<BotGroupTaskCardState, string> = {- started: '进行中',- waiting: '等你确认',- completed: '已完成',- failed: '失败了',- cancelled: '已取消',- 'timed-out': '已超时',-};+/**+ * Words for the `fallback` line, supplied by the sender in its own UI language: this+ * module has no locale, and a card is read by clients in any language.+ */+export interface BotGroupTaskCardLabels {+ /** Short noun before the title, e.g. "Task". */+ task: string;+ /** Title for a task that has none yet. */+ untitled: string;+ states: Record<BotGroupTaskCardState, string>;+}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) || '后台任务';+export function buildBotGroupTaskCard(view: BotGroupTaskCardView, labels: BotGroupTaskCardLabels): BotGroupTaskCard {+ const title = clip(view.title, TITLE_MAX) || clip(labels.untitled, 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}` : ''}`,+ fallback: `[${labels.task}] ${title} · ${labels.states[view.state]}${summary ? `: ${summary}` : ''}`,data: { meta: view.meta, state: view.state, title, ...(summary ? { summary } : {}) },};}