Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bots): 群任务终态卡等起始卡落地后再发;超长结果不拆代理对

Chrisa736bff6ca31
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index fe158cf720..40cbb014f6 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,34 @@ describe('Bot Session task end-to-end runtime', () => {
} finally { release(); runtime.dispose(); }
});
+ it('never lets the result card overtake a start card still on its way to the group', async () => {
+ await seedPair(); seedGroupLane();
+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });
+ let releaseStart: () => void = () => {};
+ const startLanded = new Promise<void>((resolve) => { releaseStart = resolve; });
+ const landed: string[] = [];
+ const postGroupTaskMessage = vi.fn(async (input: { clientId: string }) => {
+ // The start card's request is slow; the task completes while it is still in flight.
+ if (input.clientId.endsWith(':started')) await startLanded;
+ landed.push(input.clientId);
+ return { ok: true as const, messageId: `posted:${input.clientId}` };
+ });
+ const runtime = createDelegationRuntime({ postGroupTaskMessage });
+ try {
+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Quick work' });
+ if (!task.ok) throw new Error(task.message);
+ const settled = runtime.runPendingTurns();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ // The result waits: nothing has landed yet, and the result request has not even been made.
+ expect(landed).toEqual([]);
+ expect(postGroupTaskMessage.mock.calls.map(([input]) => input.clientId)).toEqual([`bot-delegation-task:${task.delegationId}:started`]);
+ releaseStart();
+ await settled;
+ expect(landed).toEqual([`bot-delegation-task:${task.delegationId}:started`, `bot-delegation-task:${task.delegationId}:1:result`]);
+ expect(h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).not.toBeNull();
+ } 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();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index b9686ab9ec..0c2b467c7e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -41,13 +41,26 @@ vi.mock('ws', async () => {
close() { this.emit('close'); }
} };
});
-import { ChatResponseError, withChatServer } from '../chatServer.js';
+import { ChatResponseError, splitChatMessageText, 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, buildBotGroupTaskCard } from '../../../shared/botGroupChat.js';
import type { BotGroupChatService, BotGroupChatServiceDeps } from '../botGroupChatService.js';
+describe('splitChatMessageText', () => {
+ it('breaks at the last line before the limit, else at the limit, never inside a surrogate pair', () => {
+ expect(splitChatMessageText('short')).toEqual(['short']);
+ expect(splitChatMessageText(`${'a'.repeat(10)}\n${'b'.repeat(5)}`, 12)).toEqual(['a'.repeat(10), 'b'.repeat(5)]);
+ // 7999 ASCII characters then an emoji (two UTF-16 units): the emoji moves whole to the next piece.
+ const pieces = splitChatMessageText(`${'a'.repeat(7999)}😀${'b'.repeat(10)}`);
+ expect(pieces).toEqual(['a'.repeat(7999), `😀${'b'.repeat(10)}`]);
+ const loneSurrogate = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
+ expect(pieces.some(piece => loneSurrogate.test(piece))).toBe(false);
+ expect(pieces.join('')).toBe(`${'a'.repeat(7999)}😀${'b'.repeat(10)}`);
+ });
+});
+
describe('Chat Server production connection', () => {
afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks(); });
const local = { dispose: vi.fn() } as unknown as BotGroupChatService;
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index d26d4311c1..a7c854e7d7 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -852,32 +852,46 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
};
const groupPostTimers = new Set<ReturnType<typeof setTimeout>>();
+ /** Start-card posts still on their way, by task: a later card waits for them (see `afterGroupTaskStart`). */
+ const groupStartPosts = new Map<string, Promise<void>>();
/** 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) {
- log.warn('group refused the task card', { delegationId: row.id, groupId: home.groupId, errorCode: posted.errorCode });
- return;
+ const postGroupTaskStart = (home: { groupId: string }, row: GroupTaskRow, attempt = 0): Promise<void> => {
+ const run = (async () => {
+ 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) {
+ 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) });
}
- } 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);
+ 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);
+ })().finally(() => {
+ if (groupStartPosts.get(row.id) === run) groupStartPosts.delete(row.id);
+ });
+ groupStartPosts.set(row.id, run);
+ return run;
};
+ /**
+ * A task that ends or asks at once must not have its 「等你确认」 or terminal card land in the
+ * group before the 「进行中」 card still in flight: later cards wait for that post to settle.
+ * A retry scheduled for later re-checks the task state itself and stays away once it ended.
+ */
+ const afterGroupTaskStart = (delegationId: string): Promise<void> => groupStartPosts.get(delegationId) ?? Promise.resolve();
const collaborationMeta = async (
row: Pick<DelegationRow,
@@ -1092,6 +1106,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
.select({ snapshot: botDelegations.permissionSnapshotJson }).from(botDelegations)
.where(eq(botDelegations.id, params.id)).get())?.snapshot);
if (home) {
+ await afterGroupTaskStart(params.id);
const posted = await postGroupTaskEvent(home, params, {
clientId: `bot-delegation-task:${params.id}:${params.runSequence}:result`,
text: params.resultSummary ?? '',
@@ -1603,6 +1618,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
let privateFallback = !home;
if (home) {
try {
+ await afterGroupTaskStart(row.id);
const posted = await postGroupTaskEvent(home, row, {
clientId: `bot-delegation-task:${row.id}:interaction:${pending.requestId}`,
text: '',
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index adfb9361e1..3a1c7ca227 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -120,7 +120,10 @@ export function splitChatMessageText(text: string, max = CHAT_MESSAGE_TEXT_MAX):
let rest = text;
while (rest.length > max) {
const cut = rest.lastIndexOf('\n', max);
- const at = cut > max / 2 ? cut : max;
+ let at = cut > max / 2 ? cut : max;
+ // Never split a surrogate pair (emoji and other astral characters are two UTF-16 units).
+ const high = rest.charCodeAt(at - 1);
+ if (high >= 0xd800 && high <= 0xdbff) at -= 1;
pieces.push(rest.slice(0, at));
rest = rest.slice(at).replace(/^\n/, '');
}