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(local-agent): 补发终稿尾段并清理未送达消息的图片

david9942f99176d9
diff --git a/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts b/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
index bb69e223d5..f6fa43eee3 100644
--- a/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
+++ b/apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts
@@ -66,7 +66,7 @@ async function fixture() {
model: 'model',
engine: 'pi',
efforts: ['high'],
- images: false,
+ images: true,
isDefault: true,
},
access: 'none',
@@ -75,7 +75,13 @@ async function fixture() {
{ url: 'http://127.0.0.1:1/mcp/fixture', token: 'invalid-fixture-token', emit: () => {} },
);
cleanups.push(() => runtime.close());
- return { runtime, maker, first };
+ return { runtime, maker, first, directory };
+}
+const image = { type: 'image', mimeType: 'image/png', data: Buffer.from('png').toString('base64') };
+async function inputFiles(directory: string) {
+ const root = path.join(directory, 'clients', 'grant-a');
+ const inputs = (await fs.readdir(root)).filter((name) => name.startsWith('input-'));
+ return (await Promise.all(inputs.map((name) => fs.readdir(path.join(root, name))))).flat();
}
const message = { parts: [{ type: 'text', text: 'hello' }], effort: 'high' };
@@ -213,4 +219,17 @@ describe('local client runtime lifecycle', () => {
await vi.waitFor(() => expect(f.runtime.call('send', message)).resolves.toEqual({}));
expect(f.first.send).toHaveBeenCalledTimes(2);
});
+ it('removes images written for a send that is rejected before the engine takes it', async () => {
+ const f = await fixture();
+ await expect(
+ f.runtime.call('send', { parts: [image, { type: 'unsupported' }] }),
+ ).rejects.toMatchObject({ code: 'INVALID_INPUT' });
+ f.first.setEffort.mockRejectedValueOnce(new Error('effort unavailable'));
+ await expect(f.runtime.call('send', { ...message, parts: [image] })).rejects.toThrow(
+ 'effort unavailable',
+ );
+ expect(await inputFiles(f.directory)).toEqual([]);
+ await f.runtime.call('send', { parts: [image] });
+ expect(await inputFiles(f.directory)).toHaveLength(1);
+ });
});
diff --git a/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts b/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts
index e8df049662..b7fa5c1566 100644
--- a/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts
+++ b/apps/desktop/src/main/local-agent/__tests__/runtime.test.ts
@@ -155,6 +155,27 @@ describe('native event projection', () => {
expect(emit.mock.calls[2][0].data).toEqual({ input: 15, cached: 5, output: 2 });
},
);
+ it('appends a final-only tail per message and never repeats a diverged snapshot', () => {
+ const emit = vi.fn(),
+ p = createEventProjection(emit);
+ p.begin();
+ for (const event of [
+ // Codex holds a citation-boundary tail out of deltas and only publishes it in completed.
+ { type: 'text', data: { text: 'See ', isFinal: false, agentMessageId: 'a' } },
+ { type: 'text', data: { text: 'See docs.', isFinal: true, agentMessageId: 'a' } },
+ { type: 'text', data: { text: 'Only final', isFinal: true, agentMessageId: 'b' } },
+ { type: 'text', data: { text: 'Hello worxd', isFinal: false, agentMessageId: 'c' } },
+ { type: 'text', data: { text: 'Hello wonderful', isFinal: true, agentMessageId: 'c' } },
+ { type: 'done', data: { result: 'Hello wonderful', status: 'completed' } },
+ ])
+ p.accept(event as any);
+ expect(emit.mock.calls.filter(([e]) => e.type === 'text').map(([e]) => e.data)).toEqual([
+ 'See ',
+ 'docs.',
+ 'Only final',
+ 'Hello worxd',
+ ]);
+ });
it('keeps native tool activity and emits one failure per turn', () => {
const emit = vi.fn(),
p = createEventProjection(emit);
diff --git a/apps/desktop/src/main/local-agent/runtime.ts b/apps/desktop/src/main/local-agent/runtime.ts
index b3badb471f..b2f184ab61 100644
--- a/apps/desktop/src/main/local-agent/runtime.ts
+++ b/apps/desktop/src/main/local-agent/runtime.ts
@@ -57,9 +57,11 @@ export function createEventProjection(
}
};
const ignoredTools = new Set<string>();
+ const streamed = new Map<string, string>();
return {
begin() {
textSeen = false;
+ streamed.clear();
ended = false;
usageReported = false;
usage = { input: 0, cached: 0, output: 0 };
@@ -78,9 +80,23 @@ export function createEventProjection(
return;
}
if (event.type === 'text') {
- if (d.isFinal !== true && string(d.text)) {
- textSeen = true;
- emit({ type: 'text', data: d.text });
+ const text = string(d.text),
+ key = string(d.agentMessageId);
+ if (d.isFinal !== true) {
+ if (text) {
+ streamed.set(key, (streamed.get(key) ?? '') + text);
+ textSeen = true;
+ emit({ type: 'text', data: text });
+ }
+ } else {
+ // The wire is append-only: a final snapshot can only supply the tail that
+ // was never streamed (held citation boundary, final-only notices).
+ const sent = streamed.get(key) ?? '';
+ streamed.delete(key);
+ if (text.length > sent.length && text.startsWith(sent)) {
+ textSeen = true;
+ emit({ type: 'text', data: text.slice(sent.length) });
+ }
}
} else if (event.type === 'thinking') {
if (d.stage !== 'final' && string(d.text)) emit({ type: 'thinking', data: d.text });
@@ -123,6 +139,7 @@ export function createEventProjection(
addEventUsage(d);
if (!terminal) {
textSeen = false;
+ streamed.clear();
return;
}
reportUsage();
@@ -267,11 +284,29 @@ export async function openLocalAgentRuntime(
await fs.rm(temporary, { recursive: true, force: true });
throw error;
}
+ // Images are written per message; a message the engine never took must not leave them behind.
+ const discard = async (content: UserMessage) => {
+ if (Array.isArray(content.content))
+ await Promise.all(
+ content.content.map((block) =>
+ block.type === 'image' ? fs.rm(block.path, { force: true }) : undefined,
+ ),
+ ).catch(() => {});
+ };
const message = async (params: Record<string, unknown>): Promise<UserMessage> => {
if (!Array.isArray(params.parts) || !params.parts.length || params.parts.length > 64)
throw new LocalAgentError('INVALID_INPUT', '消息内容无效。');
const blocks: UserContentBlock[] = [];
- for (const raw of params.parts) {
+ try {
+ await collect(params.parts, blocks);
+ } catch (error) {
+ await discard({ type: 'user', content: blocks });
+ throw error;
+ }
+ return { type: 'user', content: blocks };
+ };
+ const collect = async (parts: unknown[], blocks: UserContentBlock[]) => {
+ for (const raw of parts) {
const part = object(raw);
if (part.type === 'text' && typeof part.text === 'string') {
// A tool policy is not an input blacklist: paths and slash-prefixed text
@@ -299,16 +334,15 @@ export async function openLocalAgentRuntime(
'image/gif': '.gif',
}[string(part.mimeType)] ?? ''),
);
- await fs.writeFile(file, bytes, { mode: 0o600 });
blocks.push({
type: 'image',
path: file,
mimeType: string(part.mimeType),
pathOrigin: 'desktop-host',
});
+ await fs.writeFile(file, bytes, { mode: 0o600 });
} else throw new LocalAgentError('INVALID_INPUT', '所选 Cindy 模型不支持这类输入。');
}
- return { type: 'user', content: blocks };
};
return {
get id() {
@@ -348,17 +382,23 @@ export async function openLocalAgentRuntime(
if (!busy || preparing)
throw new LocalAgentError('NOT_RUNNING', '当前没有正在运行的回答。');
const content = await message(params);
- assertCurrent(current);
- if (!busy) throw new LocalAgentError('NOT_RUNNING', '当前没有正在运行的回答。');
- await handle.steer(content);
+ try {
+ assertCurrent(current);
+ if (!busy) throw new LocalAgentError('NOT_RUNNING', '当前没有正在运行的回答。');
+ await handle.steer(content);
+ } catch (error) {
+ await discard(content);
+ throw error;
+ }
return {};
}
if (busy) throw new LocalAgentError('BUSY', '当前回答尚未结束。');
const current = ++epoch;
busy = true;
preparing = true;
+ let content: UserMessage | undefined;
try {
- const content = await message(params);
+ content = await message(params);
assertCurrent(current);
if (appliedInstructions !== instructionsVersion) {
const previous = handle;
@@ -374,8 +414,10 @@ export async function openLocalAgentRuntime(
preparing = false;
projection.begin();
// Some harnesses await the entire turn; acceptance must not block tool delivery/control RPCs.
+ const sending = content;
void (async () => {
- const result = await handle.send(content);
+ const result = await handle.send(sending);
+ if (!result.accepted) await discard(sending);
assertSendDispatched(result, 'local-agent/send');
})().catch(() => {
if (!closed && epoch === current) {
@@ -389,6 +431,7 @@ export async function openLocalAgentRuntime(
busy = false;
preparing = false;
}
+ if (content) await discard(content);
throw error;
}
},