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(chat): deliver talk reply images and honor PUT rate limits

ylliuuu668628ef0c946d
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 9ffd070a04..4c4018532f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -567,6 +567,21 @@ describe('Chat Server result delivery and refresh', () => {
await vi.advanceTimersByTimeAsync(16000); expect(failures()).toHaveLength(1); expect(deps.dispatch).toHaveBeenCalledOnce();
});
+ it.each([undefined, 30_000, 120_000])('waits for PUT 429 cooldown %s before retrying the same reply', async delay => {
+ replyImages.mockResolvedValue({ text: 'image', attachments: [replyImage] });
+ await start();
+ const wait = Math.max(60_000, delay ?? 0);
+ fixture.upload.mockRejectedValueOnce(Object.assign(new Error('MEDIA_UPLOAD_FAILED'),
+ { status: 429, retryAt: delay === undefined ? undefined : Date.now() + delay })).mockResolvedValue([imageBlock]);
+ await service.settleLaneTurn({ ...terminal, resultText: '![](cindy-media://image)' });
+ await vi.advanceTimersByTimeAsync(wait - 1000);
+ expect(fixture.upload).toHaveBeenCalledOnce(); expect(deliveries()).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(fixture.upload).toHaveBeenCalledTimes(2);
+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'image' }, imageBlock]);
+ expect(replyImages).toHaveBeenCalledOnce(); expect(deps.dispatch).toHaveBeenCalledOnce();
+ });
+
it.each([{ codexErrorInfo: 'serverOverloaded' }, { reason: 'upstream-overload' }, { errorStatus: 529 }])
('submits only the capacity category after the SDK terminal %j', async signals => {
@@ -1542,6 +1557,16 @@ describe('Chat Server result delivery and refresh', () => {
expect(prompt()).toContain('unrelated main group chatter');
expect(downloaded).toEqual(expect.arrayContaining([answerFile, unrelatedFile]));
}
+ // #6708: a talk step is an ordinary reply despite having a plan; work keeps its artifact path.
+ replyImages.mockResolvedValue({ text: 'image', attachments: [replyImage] });
+ fixture.upload.mockResolvedValue([imageBlock]);
+ await service.settleLaneTurn({ ...terminal, resultText: '![](cindy-media://image)' });
+ if (kind === 'talk') {
+ expect(replyImages).toHaveBeenCalledOnce();
+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'image' }, imageBlock]);
+ expect(fixture.upload).toHaveBeenCalledWith(roomId, expect.any(String), [replyImage], botId, expect.any(Function));
+ } else expect(replyImages).not.toHaveBeenCalled();
+ expect(deliveries()[0][2]).not.toHaveProperty('continueDiscussion');
});
it('sends without holding the request for a helper-model arrangement decision', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
index 940de3d83c..5b490804e3 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
@@ -12,6 +12,18 @@ import type { BotGroupAttachment } from '../../../shared/botGroupChat.js';
const attachment: BotGroupAttachment = { id: 'file', name: 'picture.png', category: 'image', mimeType: 'image/png', size: 3, url: 'cindy-media://test', path: null };
describe('chat private media', () => {
+ it.each([undefined, '120'])('preserves PUT 429 Retry-After %s for settlement backoff', async retryAfter => {
+ f.read.mockResolvedValue({ buffer: Buffer.from('png') });
+ f.fetch.mockResolvedValue(new Response('', { status: 429, headers: retryAfter ? { 'Retry-After': retryAfter } : {} }));
+ const api = vi.fn(async () => ({ id: 'media', uploadUrl: 'https://upload.example.test/signed' })) as unknown as ChatApi;
+ const before = Date.now();
+ const error = await createChatMedia(api, () => true).upload('room', 'reply', [attachment], 'actor').catch(error => error);
+ expect(error).toMatchObject({ message: 'MEDIA_UPLOAD_FAILED', status: 429 });
+ if (retryAfter) expect(error.retryAt).toBeGreaterThanOrEqual(before + 120_000);
+ else expect(error.retryAt).toBeUndefined();
+ expect(vi.mocked(api).mock.calls.some(([route]) => route.endsWith('/complete'))).toBe(false);
+ });
+
it('does not PUT an ordinary reply after execution changes during prepare', async () => {
let current = true; f.read.mockResolvedValueOnce({ buffer: Buffer.from('png') }); f.fetch.mockClear();
const api = vi.fn(async () => { current = false; return { id: 'media', uploadUrl: 'https://upload.example.test/signed' }; }) as unknown as ChatApi;
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 940027bdd6..e579a5c70d 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -1473,15 +1473,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
};
let contentText = text;
let files: ChatContentBlock[] = [];
+ const ordinaryReply = !run.plan || run.plan.kind === 'talk';
try {
if (terminal.outcome !== 'error') {
- if (!run.plan) {
+ if (ordinaryReply) {
pending.reply ??= { sourceText: text, ...await prepareChatReplyImages(text, run.sessionId, assertCurrent) };
contentText = pending.reply.text;
produced.push(...pending.reply.attachments);
}
files = await media.upload(run.execution.conversation_id, `step:${run.execution.id}:${run.execution.epoch}`,
- produced, run.execution.bot_id, run.plan ? undefined : assertCurrent);
+ produced, run.execution.bot_id, ordinaryReply ? assertCurrent : undefined);
assertCurrent();
}
} catch (error) {
@@ -1491,7 +1492,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
&& !['STALE_EXECUTOR', 'STALE_EXECUTION', 'EXECUTION_EXPIRED'].includes(code);
const permanentUpload = code === 'MEDIA_UPLOAD_FAILED' && status !== undefined
&& status >= 400 && status < 500 && ![408, 429].includes(status);
- if (run.plan || !(fileRefusedHere(error) || permanentMediaResponse || permanentUpload
+ if (!ordinaryReply || !(fileRefusedHere(error) || permanentMediaResponse || permanentUpload
|| ['INVALID_MEDIA_URL', 'ERR_INVALID_URL'].includes(code))) throw error;
terminal = pending.terminal = { ...terminal, outcome: 'error', failureCode: 'RUNTIME_ERROR' };
}
@@ -1520,10 +1521,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
// or post the private result under a new execution identity.
const recoveringAuth = error instanceof ChatResponseError && recoverableAuth(error);
if (!(error instanceof ChatResponseError) || retryableResponse(error)) {
- const delayed = recoveringAuth || (error instanceof ChatResponseError && error.status === 429);
+ const rateLimited = chatErrorDiagnostic(error).status === 429;
+ const retryAt = rateLimited && error instanceof Error && 'retryAt' in error && typeof error.retryAt === 'number' ? error.retryAt : 0;
+ const delayed = recoveringAuth || rateLimited;
pending.keepLease = delayed;
pending.retryAt = delayed
- ? Math.max(Date.now() + CHAT_AUTH_RETRY_MS, error instanceof ChatResponseError ? error.retryAt ?? 0 : 0)
+ ? Math.max(Date.now() + CHAT_AUTH_RETRY_MS, retryAt)
: Date.now() + 15000;
return;
}
diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
index 8d99007cd3..89b4d25f61 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
@@ -1,4 +1,5 @@
import { chatErrorDiagnostic } from './chatServerErrors.js';
+import { retryAfterDeadline } from '@cindy/auth-client';
import { net } from 'electron';
import fs from 'node:fs/promises';
import path from 'node:path';
@@ -78,7 +79,8 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa
stage = 'upload';
const response = await net.fetch(signedUrl(upload.uploadUrl), { method: 'PUT', redirect: 'error',
headers: { 'Content-Type': attachment.mimeType }, body: new Uint8Array(bytes), signal: AbortSignal.timeout(60000) });
- if (!response.ok) throw Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: response.status });
+ if (!response.ok) throw Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: response.status,
+ ...(response.status === 429 ? { retryAt: retryAfterDeadline(response) } : {}) });
checkUpload();
stage = 'complete';
await api(`/conversations/${roomId}/media/${upload.id}/complete`, 'POST', { operationId: `seal:${upload.id}` }, actorId);