Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 群任务消息的补发、长结果与私聊退回
Chrisa2e4730adb28
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex a39cdc91f3..671c428d81 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -4552,6 +4552,54 @@ describe('Bot Session task end-to-end runtime', () => {} finally { h.tx = originalTx; release(); }});+ it('restores a missing owner chat only when the group refuses a task result for good', async () => {+ await seedPair(); seedGroupLane();+ h.sqlite!.pragma('foreign_keys = OFF');+ h.sqlite!.prepare("DELETE FROM sessions WHERE id='session-1'").run();+ h.sqlite!.pragma('foreign_keys = ON');+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ // The card posts; the result is refused for good (the teammate left the group).+ const postGroupTaskMessage = vi.fn(async (input: { clientId: string }) => input.clientId.endsWith(':started')+ ? { ok: true as const, messageId: `posted:${input.clientId}` }+ : { ok: false as const, errorCode: 'MEMBER_UNAVAILABLE', retryable: false });+ const runtime = createDelegationRuntime({ postGroupTaskMessage });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture refused result' });+ if (!task.ok) throw new Error(task.message);+ // Starting the task repaired no private chat: the stale link still points at the missing row.+ const liveCanonical = () => h.sqlite!.prepare(`SELECT s.id FROM bot_session_links l JOIN sessions s ON s.id = l.session_id+ WHERE l.bot_id='bot-a' AND l.role='canonical' AND l.archived_at IS NULL AND s.status='active'`).pluck().get() as string | undefined;+ expect(liveCanonical()).toBeUndefined();+ await runtime.runPendingTurns();+ // Delivery restored one and woke it, so the result is not lost and not retried forever.+ const restored = liveCanonical();+ expect(restored).toBeTruthy();+ expect(runtime.dispatch.mock.calls.some(([params]) => params.targetSessionId === restored)).toBe(true);+ expect(h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).not.toBeNull();+ } finally { release(); runtime.dispose(); }+ });++ it('does not post a stale 「进行中」 card after the task has already ended', async () => {+ await seedPair(); seedGroupLane();+ vi.useFakeTimers();+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });+ // The first start post fails transiently; the task finishes before the retry is due.+ let startAttempts = 0;+ const postGroupTaskMessage = vi.fn(async (input: { clientId: string }) => {+ if (input.clientId.endsWith(':started') && ++startAttempts === 1) return { ok: false as const, errorCode: 'ECONNRESET', retryable: true };+ return { ok: true as const, messageId: `posted:${input.clientId}` };+ });+ const runtime = createDelegationRuntime({ postGroupTaskMessage });+ try {+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Fixture short task' });+ if (!task.ok) throw new Error(task.message);+ await runtime.runPendingTurns();+ expect(postGroupTaskMessage).toHaveBeenLastCalledWith(expect.objectContaining({ clientId: `bot-delegation-task:${task.delegationId}:1:result` }));+ await vi.advanceTimersByTimeAsync(60_000);+ expect(postGroupTaskMessage.mock.calls.filter(([input]) => input.clientId.endsWith(':started'))).toHaveLength(1);+ } finally { release(); runtime.dispose(); vi.useRealTimers(); }+ });+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') {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex 4c2de9b2b1..b74c28aea1 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -41,7 +41,7 @@ vi.mock('ws', async () => {close() { this.emit('close'); }} };});-import { withChatServer } from '../chatServer.js';+import { ChatResponseError, withChatServer } from '../chatServer.js';import { projectBotGroupExecutionFailures } from '@cindy/maker-shared/botGroupPresentation';import { botGroupRuntimeFailureCode, settleUndispatchedBotGroupTurn } from '../botGroupRuntimeFailure.js';import { authorizeGroupTool } from '../botGroupToolAuthorization.js';@@ -521,6 +521,45 @@ describe('Chat Server result delivery and refresh', () => {expect(posted).toMatchObject({ ok: false, retryable });});+ it('continues a long result in follow-up messages instead of cutting it', async () => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ 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)}\n${'c'.repeat(8000)}${'d'.repeat(10)}`;+ const posted = await service.postCompanionTaskMessage({ groupId: roomId, botId: 'local-bot', clientId: 'bot-delegation-task:task-1:1:result', text, card: taskCard });+ 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:3']);+ // The first piece breaks at the line before the limit and carries the card; nothing is lost.+ expect(bodies[0].content).toEqual([{ type: 'text', text: 'a'.repeat(7990) }, taskCard]);+ expect(bodies[1].content).toEqual([{ type: 'text', text: `${'b'.repeat(20)}\n${'c'.repeat(7979)}` }]);+ expect(bodies[2].content).toEqual([{ type: 'text', text: `${'c'.repeat(21)}${'d'.repeat(10)}` }]);+ expect(bodies.every(body => body.content.every((block: { text?: string }) => (block.text ?? '').length <= 8000))).toBe(true);+ });++ 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],+ ])('%s', async (_label, failure, expected, posts) => {+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];+ fixture.upload.mockRejectedValueOnce(failure);+ 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: [{ absolutePath: '/no/such/file.md' }] });+ expect(posted).toMatchObject(expected);+ const sent = fixture.handle.mock.calls.filter(([route, method]) => route === `/conversations/${roomId}/messages` && method === 'POST');+ expect(sent).toHaveLength(posts);+ if (posts) expect(sent[0][2].content).toEqual([{ type: 'text', text: 'Done.' }, taskCard]);+ });+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')diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex ca68af8b56..3ec97c1817 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -785,6 +785,12 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {await beforeRecovery?.();return ensureTargetCanonicalSession({ id: profile.id, currentVersion: profile.currentVersion }, beforeRecovery);};+ /** The owner chat a group task falls back to, created or repaired when it is missing. */+ const restoredRequesterSessionId = async (botId: string): Promise<string | null> => {+ const ensured = await ensureCanonicalSession(botId);+ if (!ensured.ok) return null;+ return requesterLiveSessionId(botId, null);+ };/*** 冻结这次协作双方的展示身份。名字后来改了不回填历史消息——消息流讲的是@@ -828,6 +834,12 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {/** 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 {+ if (attempt > 0) {+ // A retry after the task already ended would put a stale 「进行中」 card under its result.+ const current = await getDbClient().drizzle.select({ status: botDelegations.status }).from(botDelegations)+ .where(eq(botDelegations.id, row.id)).get();+ if (!current || !isActiveDelegation(current.status as DelegationStatus)) return;+ }const posted = await postGroupTaskEvent(home, row, { clientId: `bot-delegation-task:${row.id}:started`, text: '', state: 'started' });if (posted.ok) return;if (!posted.retryable) {@@ -1099,7 +1111,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {delegationId: params.id, groupId: home.groupId, errorCode: posted.errorCode,});}- const targetSessionId = await requesterLiveSessionId(params.requestingBotId, home ? null : params.parentSessionId);+ // A group task falling back to the owner chat may find none (deleted, or never created):+ // restore it here, the one place that needs it, rather than when the task starts.+ const targetSessionId = await requesterLiveSessionId(params.requestingBotId, home ? null : params.parentSessionId)+ ?? (home ? await restoredRequesterSessionId(params.requestingBotId) : null);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.@@ -1593,8 +1608,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {}}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);+ // A lane is never woken; a refused group notice goes to the owner's main chat (restored if missing).+ const requesterSessionId = await requesterLiveSessionId(row.requestingBotId, home ? null : row.parentSessionId)+ ?? (home ? await restoredRequesterSessionId(row.requestingBotId) : null);if (!stillPending() || (row.childSessionId && heldSessionIds.has(row.childSessionId))) return;const dispatched = requesterSessionId? await deps.dispatch({diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 37402df0a8..3cda975100 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -9,7 +9,7 @@ import { retryAfterDeadline } from '@cindy/auth-client';import { existsSync, readFileSync } from 'node:fs';import { request as httpRequest } from 'node:http';import { request as httpsRequest } from 'node:https';-import { migrateLocalGroups } from './chatServerMigration.js';+import { migrateLocalGroups, type ChatContentBlock } from './chatServerMigration.js';import { chatErrorDiagnostic, chatGroupFailure } from './chatServerErrors.js';import { createChatMedia } from './chatServerMedia.js';import { chatServerWorkspaces } from './chatServerWorkspaces.js';@@ -81,7 +81,7 @@ interface Running {pauseStarted?: number;releaseToolAuthority?: () => void;}-class ChatResponseError extends Error {+export class ChatResponseError extends Error {constructor(code: string, readonly status: number, readonly retryAt?: number, readonly details?: unknown) { super(code); }}const CHAT_AUTH_RETRY_MS = 60_000;@@ -110,6 +110,21 @@ const bodyBlocks = (m: Message) => m.content.filter(b => (b.namespace !== 'cindy*/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');+/** One server message holds this much text. */+const CHAT_MESSAGE_TEXT_MAX = 8000;+/** Splits long text into message-sized pieces, preferring a line break near the limit; '' → []. */+export function splitChatMessageText(text: string, max = CHAT_MESSAGE_TEXT_MAX): string[] {+ const pieces: string[] = [];+ let rest = text;+ while (rest.length > max) {+ const cut = rest.lastIndexOf('\n', max);+ const at = cut > max / 2 ? cut : max;+ pieces.push(rest.slice(0, at));+ rest = rest.slice(at).replace(/^\n/, '');+ }+ if (rest) pieces.push(rest);+ return pieces;+}/** 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');const quotedAttachments = (m: Message) => m.content.flatMap(b => b.type === 'media' ? [{ name: b.caption?.trim() || '…' }] : []);@@ -1559,15 +1574,27 @@ 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 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);+ // 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 = [];+ }+ // The server takes 8000 characters per message: a longer result continues in follow-up+ // messages (same idempotent operation id family), never silently cut.+ const [first = '', ...rest] = splitChatMessageText(input.text.trim());const posted = await api<{ id: string }>(`/conversations/${roomId}/messages`, 'POST', {- operationId: input.clientId, content: [...(text ? [{ type: 'text', text }] : []), input.card, ...uploaded], mentions: [],+ operationId: input.clientId, content: [...(first ? [{ type: 'text', text: first }] : []), input.card, ...uploaded], 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);+ }changed(roomId);return { ok: true, messageId: posted.id };} catch (error) {diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.tsindex 09241783ab..5598a57748 100644--- a/apps/mobile/src/__tests__/chatServerClient.test.ts+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest';import { chatGroupView, chatRoomRow, chatReadAt, createChatServerClient, type ChatMessage, type ChatRoom, type ChatSnapshot } from '@/chat/chatServerClient';-import { buildBotGroupQuoteCard } from '@cindy/maker-shared/botGroupChat';+import { buildBotGroupQuoteCard, buildBotGroupTaskCard } from '@cindy/maker-shared/botGroupChat';const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;const room = (n = 1, state = 'joined'): ChatRoom => ({ id: id(n), name: 'Discussion', kind: 'group', state, archived: false,revision: 1, created_at: '2026-10-01', updated_at: '2026-10-09', response_mode: 'all', speaking_mode: 'auto' });@@ -29,6 +29,17 @@ describe('direct Chat Server client', () => {expect(deleted.messages[0].quote).toMatchObject({ messageId: id(20), originalDeleted: true });});+ 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' });+ 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));+ expect(view.messages[0]).toMatchObject({ authorKind: 'bot', content: 'Started it.', task: { state: 'started', title: 'Launch post' } });+ expect(view.messages[1].task).toBeUndefined();+ expect(view.messages[1].content).toBe(`${card.fallback}\nPasted a card`);+ });+it('reconciles all loaded message pages in bounded requests and clears an old-source failure on refresh', async () => {const latest = Array.from({ length: 100 }, (_, n) => message(200 - n));const older = Array.from({ length: 100 }, (_, n) => message(100 - n));diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex 743a8a7ea4..6c49fa8693 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -1,5 +1,5 @@/** The existing Chat Server HTTP contract; no device-link or executor registration. */-import { readBotGroupExecutionFailure, readBotGroupQuote, readBotGroupQuoteCard, readImportedBotGroupRuntimeFailureCode, type BotGroupAttachment, type BotGroupMemberView, type BotGroupMessageView, type BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';+import { readBotGroupExecutionFailure, readBotGroupQuote, readBotGroupQuoteCard, readBotGroupTaskCard, readImportedBotGroupRuntimeFailureCode, type BotGroupAttachment, type BotGroupMemberView, type BotGroupMessageView, type BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';import { botGroupExecutionFailureBatches, projectBotGroupExecutionFailures } from '@cindy/maker-shared/botGroupPresentation';import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';@@ -60,8 +60,10 @@ export function chatRejection(error: unknown, status: number, code: string): Recconst memberName = (member: ChatMember) => member.kind === 'bot' && member.ownerName?.trim()? `${member.name} (${member.ownerName.trim()})` : member.name;// A recognized 引用回复 card renders as the quote; an unknown revision keeps its readable fallback.+// A task card is the message's task only on a teammate's own message (bot-group-chat.md §10).+const taskCardOf = (message: ChatMessage) => message.author.kind === 'bot' ? message.content.map(readBotGroupTaskCard).find(Boolean) ?? null : null;const contentText = (message: ChatMessage) => message.deleted || readImportedBotGroupRuntimeFailureCode(message) ? '' : message.content- .filter(block => !readBotGroupQuoteCard(block))+ .filter(block => !readBotGroupQuoteCard(block) && !(message.author.kind === 'bot' && readBotGroupTaskCard(block))).map(block => block.text ?? block.fallback ?? (block.type === 'media' ? block.caption ?? '' : '')).join('\n');export const chatMessageText = (message: ChatMessage) => contentText(message);@@ -145,7 +147,9 @@ export function chatGroupView(page: ChatPage, selfId: string): BotGroupRemoteChaconst joined = message.origin === 'system' && !message.deleted && message.content.find(block =>block.type === 'card' && block.namespace === 'cindy.membership' && block.schemaRevision === 1 && block.data?.type === 'member.joined');const quote = message.origin === 'system' ? null : readBotGroupQuote(message.content);+ const task = message.origin === 'system' ? null : taskCardOf(message);return { id: message.id, sequence: index + 1, kind: message.origin === 'system' ? 'notice' : 'message',+ ...(task ? { task } : {}),authorKind: message.origin === 'system' ? 'system' : message.author.kind === 'human' ? 'user' : 'bot',authorBotId: message.authorId, authorName: joined && typeof joined.data?.displayName === 'string' ? joined.data.displayName: member ? memberName(member) : message.author.name,