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): start context downloads only after lane setup

Chris1fc4d0dabc4d
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 76224a5b6c..3f724f71f8 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -489,20 +489,41 @@ describe('Chat Server result delivery and refresh', () => {
expect(JSON.stringify(failures)).not.toContain('private preparation details');
});
- it('settles a failed lane preparation at once instead of waiting for the turn\'s attachment downloads', async () => {
+ it.each(['failure', 'success'] as const)('starts attachment downloads only after lane preparation: %s', async (outcome) => {
fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];
const files = Array.from({ length: 12 }, (_, n) => ({ type: 'media', mediaId: `60000000-0000-4000-8000-${String(n + 1).padStart(12, '0')}`, caption: `f${n}.pdf` }));
const source = { id: execution.source_message_id, seq: '1', authorId: selfId, author: { kind: 'human', name: 'Me' },
content: [{ type: 'text', text: 'Read these' }, ...files], createdAt: new Date().toISOString(), deleted: false, threadRootId: null };
fixture.handle.mockImplementation(route => route.includes('/messages?') ? { body: [source] } : response(route));
- // Slow media never finishes within this test.
- fixture.download.mockImplementation(() => new Promise(() => {}));
- deps.ensureLane = vi.fn(async () => ({ ok: false as const, errorCode: 'NO_MODEL', message: 'private preparation details' }));
+ // A slow setup lets context reads finish first. No bytes may start until setup succeeds.
+ let releaseLane!: () => void;
+ const laneGate = new Promise<void>(resolve => { releaseLane = resolve; });
+ deps.ensureLane = vi.fn(async () => {
+ await laneGate;
+ return outcome === 'failure'
+ ? { ok: false as const, errorCode: 'NO_MODEL', message: 'private preparation details' }
+ : { ok: true as const, sessionId: 'lane' };
+ });
+ fixture.download.mockImplementation(async (_room: string, mediaId: string) => ({
+ id: mediaId, name: 'f.pdf', category: 'file', mimeType: 'application/pdf', size: 1, path: '/test/f.pdf', url: null,
+ }));
await vi.advanceTimersByTimeAsync(2000);
+ expect(deps.ensureLane).toHaveBeenCalledOnce();
+ expect(fixture.handle.mock.calls.some(([route]) => route.includes('/messages?'))).toBe(true);
+ expect(fixture.download).not.toHaveBeenCalled();
+ releaseLane();
+ await vi.advanceTimersByTimeAsync(0);
const failures = fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'fail');
- expect(failures).toHaveLength(1);
- expect(failures[0][2]).toMatchObject({ detail: 'cindy-runtime-error:MODEL_UNAVAILABLE' });
- expect(fixture.download.mock.calls.length).toBeLessThan(files.length);
+ if (outcome === 'failure') {
+ expect(failures).toHaveLength(1);
+ expect(failures[0][2]).toMatchObject({ detail: 'cindy-runtime-error:MODEL_UNAVAILABLE' });
+ expect(fixture.download).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
+ } else {
+ expect(failures).toHaveLength(0);
+ expect(fixture.download).toHaveBeenCalledTimes(files.length);
+ expect(deps.dispatch).toHaveBeenCalledOnce();
+ }
});
it.each([
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 6b3308819d..fcb4bdc8a2 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -1249,10 +1249,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (ownDirectRoom) { await runDirectExecution(run, bot.id, s.room.id); return; }
// Any other 1:1 room is never answered as a group.
if (s.room.kind === 'direct') throw new Error('INVALID_EXECUTION_TRIGGER');
- // Lane setup (local) and the turn's context (server reads, attachment downloads) are
- // independent; both finish before the single lease check that precedes the dispatch.
- // A failed setup settles at once: no further downloads start and none are waited for.
- let laneFailed = false;
+ // Lane setup and context metadata reads run together; attachment bytes wait for setup
+ // to succeed so a failed setup cannot leave downloads running after settlement.
const laneSetup = (async () => {
// Metadata only: the server remains the sole message store and scheduler.
if (!metadata.has(s.room.id)) metadata.set(s.room.id, (async () => {
@@ -1322,7 +1320,6 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
await deps.syncLanePermission?.(lane.sessionId, bot.id);
return lane;
})();
- laneSetup.catch(() => { laneFailed = true; });
const contextRead = (async () => {
const history = await historyRead;
let page = [...history];
@@ -1367,6 +1364,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
page = await api<Message[]>(`/conversations/${s.room.id}/messages?all=true&limit=100&before=${before}`);
attachmentHistory.push(...page);
}
+ // Downloads share the media cache with other consumers. Start them only after the
+ // lane is ready, rather than cancelling a shared download on setup failure.
+ await laneSetup;
const attachments: BotGroupAttachment[] = [];
const missingAttachments: string[] = [];
// Attach a bounded newest set, and retain the names of older files in context.
@@ -1386,11 +1386,10 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
// The first 40 files in that order that download are attached, as when they were read
// one by one; a few download at once. A failed file frees its place for the next one.
let next = 0;
- while (!laneFailed && next < candidates.length && attachments.length < 40) {
+ while (next < candidates.length && attachments.length < 40) {
const batch = candidates.slice(next, next + 40 - attachments.length);
next += batch.length;
const results = await settleBounded(batch, TURN_DOWNLOAD_CONCURRENCY, async candidate => {
- if (laneFailed) throw new Error('LANE_FAILED');
return media.download(s.room.id, id.parse(candidate.mediaId));
});
results.forEach((result, index) => {