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(bot-group): retry a turn's conversation lookup and keep unread queue notices

zqchris475f49e30857
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts
index 0d3d00406e..2f60c4abc1 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts
@@ -71,6 +71,8 @@ let completed: Array<{ executionId: string; body: Record<string, unknown> }> = [
let directPosts = 0;
/** The room's execution list; off by default so other cases keep reading no executions. */
let listExecutions = false;
+/** Message IDs whose next single read fails like a dropped connection. */
+let failNextRead = new Set<string>();
function post(text: string, options: { by?: 'owner' | number; threadRootId?: string; mentions?: string[]; media?: string[] } = {}) {
const bot = typeof options.by === 'number' ? bots[options.by] : undefined;
@@ -121,6 +123,7 @@ function handle(route: string, method: string, body: Record<string, unknown> | u
if (path === `/conversations/${roomId}/messages` && method === 'POST') { directPosts++; return { body: { id: uuid(++ids) } }; }
if (path === `/conversations/${roomId}/messages`) return { body: list(url.searchParams) };
const single = path.match(/\/messages\/([^/]+)$/)?.[1];
+ if (single && failNextRead.delete(single)) return { status: 503, body: { error: { code: 'SERVICE_UNAVAILABLE' } } };
if (single) {
const message = messages.find(m => m.id === single);
return message && !hidden.has(single) ? { body: message } : { status: 404, body: { error: { code: 'NOT_FOUND' } } };
@@ -148,7 +151,7 @@ describe('Chat Server Thread context reaches the Agent input', () => {
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'Date'] });
vi.setSystemTime(new Date('2026-10-13T00:00:00Z'));
vi.stubEnv('XDT_ISOLATED', '1');
- ids = 100; seq = 0; messages = []; hidden = new Set(); queue = new Map(); executions = new Map(); completed = []; directPosts = 0; listExecutions = false;
+ ids = 100; seq = 0; messages = []; hidden = new Set(); queue = new Map(); executions = new Map(); completed = []; directPosts = 0; listExecutions = false; failNextRead = new Set();
fixture.profiles = bots.map(bot => ({ id: bot.local, displayName: bot.name, avatar: null, status: 'active' }));
fixture.handle.mockImplementation(handle);
fixture.download.mockImplementation(async (_room: string, mediaId: string) => ({ id: mediaId, name: mediaId, category: 'image', path: '/test/image', url: null }));
@@ -348,6 +351,25 @@ describe('Chat Server Thread context reaches the Agent input', () => {
expect(executions.get(again.id)!.status).toBe('running');
});
+ it('keeps taking a busy companion\'s other Threads after reading its turn\'s Thread failed once', async () => {
+ listExecutions = true;
+ const laneOf = (local: string, threadRootId?: string) => `lane-${local}${threadRootId ? `:${threadRootId}` : ''}`;
+ deps.ensureLane = vi.fn(async ({ botId, threadRootId }: { botId: string; threadRootId?: string }) =>
+ ({ ok: true, sessionId: laneOf(botId, threadRootId) })) as unknown as BotGroupChatServiceDeps['ensureLane'];
+ const sessions = () => vi.mocked(deps.dispatch).mock.calls.map(call => call[0].targetSessionId);
+ const pricing = post('定价要不要调?');
+ const release = post('发布前要不要先冻结主干?');
+ const question = post('@Nova 你怎么看定价?', { threadRootId: pricing.id, mentions: [bots[0].id] });
+ trigger(question);
+ // The turn still starts from its history page; only the separate read of its Thread fails.
+ failNextRead.add(question.id);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(sessions()).toEqual([laneOf('nova', pricing.id)]);
+ trigger(post('@Nova 发布这边呢?', { threadRootId: release.id, mentions: [bots[0].id] }));
+ await vi.advanceTimersByTimeAsync(4000);
+ expect(sessions()).toEqual([laneOf('nova', pricing.id), laneOf('nova', release.id)]);
+ });
+
it.each([['everyone', undefined, ['nova', 'pico']], ['one companion', 0, ['nova']]] as const)(
'runs only the server-targeted companions for a Thread mention of %s', async (_label, target, expected) => {
const root = post('只要伙伴能管理任务,是不是就拿到了所有权限?');
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 87208def11..d427b65ce3 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -86,6 +86,7 @@ interface Running {
execution: Execution; sessionId: string; clientId: string; accepted: boolean; started: number;
/** The conversation this turn answers in (see executionLane); unknown until its source is read. */
lane?: string;
+ laneLookup?: Promise<void>;
context?: ExecutionContext;
settlement?: { terminal: BotGroupLaneTerminal; payload?: Record<string, unknown>; retryAt: number; keepLease?: boolean };
delivery?: Promise<void>;
@@ -1462,7 +1463,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const run: Running = { execution, sessionId: '', clientId: BOT_GROUP_CLIENT_ID.memberTurn(execution.conversation_id, execution.id, bot.id), accepted: false, started: Date.now(), lane };
running.set(execution.id, run);
// Until its conversation is known, this turn holds back the companion's other work.
- if (!lane) void executionLane(execution).then(value => { run.lane = value; }, () => undefined);
+ resolveLane(run);
try {
z.object({ access_mode: z.enum(['owner', 'chat', 'tools']), access_revision: z.number().int().positive() }).parse(execution);
run.context = ordinaryExecution(execution) ? { kind: 'message' }
@@ -1799,6 +1800,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const source = await readMessage(room, execution.source_message_id);
return source?.threadRootId ? `${room}:thread:${source.threadRootId}` : `${room}:main`;
}
+ /** Reads a turn's conversation once at a time; a failed read is tried again on the next claim pass. */
+ function resolveLane(run: Running) {
+ if (run.lane || run.laneLookup) return;
+ run.laneLookup = executionLane(run.execution).then(value => { run.lane = value; }, () => undefined)
+ .finally(() => { run.laneLookup = undefined; });
+ }
const runsOf = (botId: string) => [...running.values()].filter(run => run.execution.bot_id === botId);
/** Leases one execution: the oldest the server offers, or exactly `executionId`. */
async function claim(actorId: string, executionId?: string): Promise<Execution | null> {
@@ -1829,14 +1836,19 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}
for (const room of [...rooms].sort()) {
const rows = await api<Execution[]>(`/conversations/${room}/executions`);
- for (const [executionId, hinted] of hints) if (hinted === room) hints.delete(executionId);
const queued = rows.filter(row => row.bot_id === actorId && row.status === 'queued')
.sort((a, b) => (a.created_at ?? '').localeCompare(b.created_at ?? '') || a.id.localeCompare(b.id));
+ // A notice is dropped once its work is no longer queued, or once it waits behind a turn in
+ // its own conversation (that room is re-read anyway). A failed read or claim keeps it for the next pass.
+ for (const [executionId, hinted] of hints) if (hinted === room && !queued.some(row => row.id === executionId)) hints.delete(executionId);
for (const row of queued) {
- const lane = await executionLane(row);
- if (lanes.has(lane)) continue;
+ let lane: string;
+ try { lane = await executionLane(row); } catch { continue; }
+ if (lanes.has(lane)) { hints.delete(row.id); continue; }
+ // A claim failure (such as a rate limit) is reported to the poll, and keeps the notice.
const execution = await claim(actorId, row.id);
if (!execution) continue;
+ hints.delete(row.id);
lanes.add(lane);
void runExecution(execution, lane);
}
@@ -1853,6 +1865,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
// installation is not yet confirmed to run it (the server only tells devices apart): never claim.
&& !(companionHome && (companion?.isShadowed(a.externalId) || !companion?.installConfirmed(a.externalId))));
// A turn whose conversation is not yet known holds back the rest of its companion's work.
+ for (const actor of owned) for (const run of runsOf(actor.id)) resolveLane(run);
const ready = owned.filter(a => runsOf(a.id).every(run => run.lane));
settledValues(await settleBounded(ready, ready.length, async actor => {
const runs = runsOf(actor.id);