Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: preserve reply Markdown and attachment source order
ylliuuu664085a6ab442c
diff --git a/apps/desktop/src/main/localDb/conversationSearch.pure.ts b/apps/desktop/src/main/localDb/conversationSearch.pure.tsindex 909ec80283..62778f5779 100644--- a/apps/desktop/src/main/localDb/conversationSearch.pure.ts+++ b/apps/desktop/src/main/localDb/conversationSearch.pure.ts@@ -265,11 +265,11 @@ export function visibleMessageTextForConversationSearch(role: string, content: u}/** Full visible content for result rendering; only search previews flatten Markdown. */-export function visibleMessageText(role: string, content: unknown): string {+export function visibleMessageText(role: string, content: unknown, options?: { preserveWhitespace?: boolean }): string {const parsed = typeof content === 'string' ? tryParseJsonLike(content) : content;const rawText = roleVisibleText(role, parsed);const text = role === 'assistant' ? stripInternalWebCitations(rawText) : rawText;- return text.trim();+ return options?.preserveWhitespace ? text : text.trim();}function roleVisibleText(role: string, content: unknown): string {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex 5e85449874..e37552014e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -1,13 +1,13 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const avatarUpload = vi.hoisted(() => vi.fn());vi.mock('../../ossPublicUpload.js', () => ({ uploadPublicAsset: avatarUpload }));-const fixture = vi.hoisted(() => ({ upload: vi.fn(async (): Promise<unknown[]> => []), download: vi.fn(), packaged: true, urls: [] as string[], wsUrls: [] as string[], exists: vi.fn(), config: '', handle: vi.fn(), profiles: [] as unknown[], sockets: [] as import('ws').WebSocket[], token: 'isolated-test-token', refresh: vi.fn(async () => true), requests: [] as Array<{ url: string; token: string; actor?: string }> }));+const fixture = vi.hoisted(() => ({ upload: vi.fn<(...args: Parameters<ReturnType<typeof import('../chatServerMedia.js').createChatMedia>['upload']>) => Promise<unknown[]>>(async () => []), download: vi.fn(), packaged: true, urls: [] as string[], wsUrls: [] as string[], exists: vi.fn(), config: '', handle: vi.fn(), profiles: [] as unknown[], sockets: [] as import('ws').WebSocket[], token: 'isolated-test-token', refresh: vi.fn(async () => true), requests: [] as Array<{ url: string; token: string; actor?: string }> }));vi.mock('../../authManager.js', () => ({ getAccessToken: () => fixture.token, refresh: fixture.refresh }));vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.cindy.app' }));const replyFiles = vi.hoisted(() => ({ prepare: vi.fn(async (text: string) => ({ text, attachments: [] as unknown[] })) }));vi.mock('../chatServerReplyFiles.js', () => ({ prepareChatReplyFiles: replyFiles.prepare }));vi.mock('../chatServerMedia.js', () => ({ createChatMedia: () => ({ upload: fixture.upload, download: fixture.download }) }));-const replyImages = vi.hoisted(() => vi.fn(async (text: string): Promise<{ text: string; attachments: import('../../../shared/botGroupChat.js').BotGroupAttachment[] }> => ({ text, attachments: [] })));+const replyImages = vi.hoisted(() => vi.fn(async (text: string): Promise<{ text: string; attachments: import('../chatServerMedia.js').ChatUploadAttachment[] }> => ({ text, attachments: [] })));vi.mock('../chatServerReplyImages.js', () => ({ prepareChatReplyImages: replyImages }));// Persists across adapter recreation; the SQLite implementation has its own persistence tests.const taskPosts = vi.hoisted(() => new Map<string, unknown>());@@ -732,6 +732,24 @@ describe('Chat Server result delivery and refresh', () => {expect(deps.dispatch).toHaveBeenCalledOnce();});+ it.each([20, 0])('keeps file/image source order across an upload retry (image offset %s)', async imageOffset => {+ const first = { id: 'pdf', name: 'report.pdf', category: 'file', sourceOffset: 0 };+ const last = { id: 'json', name: 'data.json', sourceOffset: 80 };+ const image = { ...replyImage, sourceOffset: imageOffset };+ replyFiles.prepare.mockResolvedValue({ text: 'report chart data', attachments: [first, last] });+ replyImages.mockResolvedValue({ text: 'Delivered', attachments: [image] });+ fixture.upload.mockRejectedValueOnce(Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: 503 }))+ .mockResolvedValue([first, image, last].map(file => ({ type: 'media', mediaId: file.id })));+ await startFileReply();+ const before = fixture.upload.mock.calls.length;+ await service.settleLaneTurn({ ...terminal, resultText: '[report](./report.pdf)  [data](./data.json)' });+ await vi.advanceTimersByTimeAsync(16000);+ const uploads = fixture.upload.mock.calls.slice(before);+ expect(uploads).toHaveLength(2);+ for (const call of uploads) expect(call[2]).toEqual([first, image, last]);+ expect(deps.dispatch).toHaveBeenCalledOnce();+ });+it('delivers ten images and a PDF in one completion across an upload retry', async () => {const images = Array.from({ length: 10 }, (_, i) => ({ ...replyImage, id: `image-${i}` }));const pdf = { id: 'pdf', name: 'report.pdf' };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.tsindex 15acc21d80..1541635dd1 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.ts@@ -99,16 +99,36 @@ describe('group reply file delivery', () => {expect(await prepareChatReplyFiles(text, 'lane', () => {})).toEqual({ text, attachments: [] });});- it('deduplicates case variants according to the host path semantics before applying the count limit', async () => {- const names = process.platform === 'win32'- ? Array.from({ length: 32 }, (_, mask) => [...'report'].map((c, i) => mask & (1 << i) ? c.toUpperCase() : c).join('') + '.pdf')- : ['Report.pdf', 'report.pdf'];- for (const name of names) await fs.writeFile(path.join(work, name), 'case report');- const result = await prepareChatReplyFiles(names.map(name => `[report](${name})`).join(' '), 'lane', () => {});- expect(result.attachments).toHaveLength(process.platform === 'win32' ? 1 : 2);+ it('deduplicates real filesystem identities before applying the count limit', async () => {+ const source = path.join(work, 'CaseReport.pdf');+ await fs.writeFile(source, 'case report');+ const names = Array.from({ length: 32 }, (_, mask) => [...'casereport'].map((c, i) => mask & (1 << i) ? c.toUpperCase() : c).join('') + '.pdf');+ // Probe this actual volume; neither platform nor fs metadata is mocked.+ let insensitive = false;+ try { insensitive = (await fs.stat(path.join(work, names[0]!))).ino === (await fs.stat(source)).ino; } catch { /* case-sensitive volume */ }+ if (!insensitive) for (const name of names.slice(0, 2)) await fs.writeFile(path.join(work, name), 'case report');+ const refs = insensitive ? names : names.slice(0, 2);+ const result = await prepareChatReplyFiles(refs.map(name => `[report](${name})`).join(' '), 'lane', () => {});+ expect(result.attachments).toHaveLength(insensitive ? 1 : 2);for (const attachment of result.attachments) expect((await attachment.readBytes!()).toString()).toBe('case report');});+ it.each([' ', '\t'])('never delivers an indented persisted code example (%j)', async indent => {+ scope.reply = { content: JSON.stringify({ text: `${indent}[example](<${pdf}>)` }) };+ const text = `[example](<${pdf}>)`;+ expect(await prepareChatReplyFiles(text, 'lane', () => {}, 'reply-client')).toEqual({ text, attachments: [] });+ });++ it('retains file positions relative to the body passed to image preparation', async () => {+ const image = ' + '.png)';+ const body = `[report](<${pdf}>) ${image} [data][r]\n\n[r]: <./ordered.json>`;+ await fs.writeFile(path.join(work, 'ordered.json'), '{}');+ const result = await prepareChatReplyFiles(body, 'lane', () => {});+ expect(result.attachments.map(a => a.sourceOffset)).toEqual([0, result.text.indexOf('data')]);+ expect(result.text.indexOf(image)).toBeGreaterThan(result.attachments[0]!.sourceOffset!);+ expect(result.text.indexOf(image)).toBeLessThan(result.attachments[1]!.sourceOffset!);+ });+it('preserves persisted Markdown for an empty SDK result without changing ordinary text replies', async () => {scope.reply = { content: JSON.stringify({ text: `[报告][r]\n\n[r]: <${pdf}>` }) };const result = await prepareChatReplyFiles(`[报告][r] [r]: <${pdf}>`, 'lane', () => {}, 'reply-client');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.tsindex 92c85914b9..5f0376a8a8 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts@@ -15,10 +15,10 @@ describe('generated reply image attachments', () => {vi.resetAllMocks(); f.canRead.mockResolvedValue(true);f.resolve.mockReturnValue({ absPath: path.resolve('fixture', 'image.png'), mimeType: 'image/png' });f.stat.mockResolvedValue({ isFile: () => true, size: 3 });- f.materialize.mockImplementation(async (_session, text) => ({ text, failures: [] }));+ f.materialize.mockImplementation(async (_session, text) => ({ text, replacements: new Map(), failures: [] }));});it('imports local task images and deduplicates only rendered references', async () => {- f.materialize.mockResolvedValue({ text: ` `, failures: [] });+ f.materialize.mockResolvedValue({ text: ` `, replacements: new Map([['xdt-image:///task/generated.png', url]]), failures: [] });const source = '';const result = await prepareChatReplyImages(source, 'lane', vi.fn());expect(f.materialize).toHaveBeenCalledExactlyOnceWith('lane', source);@@ -26,6 +26,14 @@ describe('generated reply image attachments', () => {expect(result.attachments).toEqual([expect.objectContaining({ url, path: null, category: 'image', size: 3 })]);expect(f.canRead).toHaveBeenCalledExactlyOnceWith('a'.repeat(64), 'lane', f.db);});+ it('retains original positions when importing images changes URL lengths', async () => {+ const local = 'xdt-image:///task/chart.png';+ const second = `cindy-media://blobs/${'b'.repeat(64)}.png`;+ const source = `report  data `;+ f.materialize.mockResolvedValue({ text: source.replace(local, url), replacements: new Map([[local, url]]), failures: [] });+ const result = await prepareChatReplyImages(source, 'lane', vi.fn());+ expect(result.attachments.map(a => a.sourceOffset)).toEqual([source.indexOf('![chart]'), source.indexOf('![next]')]);+ });it('leaves text, code samples, external images and unreferenced definitions unchanged', async () => {const text = `Hello \`\`\n\n\n[unused]: ${url}`;expect(await prepareChatReplyImages(text, 'lane', vi.fn())).toEqual({ text, attachments: [] });diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex b364be761f..3c0fec5997 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -1513,7 +1513,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}, !terminal.resultText.trim() ? terminal.resultMessageClientId : undefined);pending.reply ??= { sourceText: text, ...await prepareChatReplyImages(pending.fileReply.text, run.sessionId, assertCurrent) };contentText = pending.reply.text;- produced.push(...pending.reply.attachments, ...pending.fileReply.attachments);+ produced.push(...[...pending.reply.attachments, ...pending.fileReply.attachments]+ .sort((a, b) => {+ const position = (a.sourceOffset ?? Infinity) - (b.sourceOffset ?? Infinity);+ // An outer file link starts before its nested preview image;+ // removing its delimiters can project both to the same offset.+ return position || (a.sourceOffset !== undefined && b.sourceOffset !== undefined+ ? Number(a.category === 'image') - Number(b.category === 'image') : 0);+ }));if (produced.length > BOT_GROUP_ATTACHMENTS_MAX) throw new Error('ATTACHMENT_UNAVAILABLE');}const validateUpload = async () => {diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.tsindex 000e53aee3..1ab9abb030 100644--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts@@ -15,6 +15,8 @@ import type { ChatApi, ChatContentBlock } from './chatServerMigration.js';/** Internal-only readers: never serialized in group messages or IPC. */export type ChatUploadAttachment = BotGroupAttachment & {+ /** Offset in the file-rewritten Markdown, before image materialization. Never sent over the wire. */+ sourceOffset?: number;readBytes?: () => Promise<Buffer>;assertCurrent?: () => void;};diff --git a/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.tsindex d994433160..1623f0ef40 100644--- a/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts@@ -84,7 +84,11 @@ export function replyFileLinks(text: string) {let deliveredText = text;for (const edit of edits.sort((a, b) => b.start - a.start))deliveredText = deliveredText.slice(0, edit.start) + edit.text + deliveredText.slice(edit.end);- return { links, text: deliveredText };+ // Image preparation sees deliveredText, so both attachment kinds use its offsets.+ const positionedLinks = links.map(link => ({ ...link, outputStart: link.start + edits+ .filter(edit => edit.end <= link.start)+ .reduce((delta, edit) => delta + edit.text.length - (edit.end - edit.start), 0) }));+ return { links: positionedLinks, text: deliveredText };}function localPath(url: string, workDir: string): string {@@ -165,7 +169,7 @@ export async function prepareChatReplyFiles(text: string, sessionId: string, assif (getCurrentDbClientSnapshot() !== snapshot) throw new Error('OWNER_CHANGED');// The existing search projection flattens newlines. Only file delivery needs the// original Markdown; scheduling and replies without file links keep their old input.- markdown = row ? visibleMessageText('assistant', row.content) : text;+ markdown = row ? visibleMessageText('assistant', row.content, { preserveWhitespace: true }) : text;}const parsed = replyFileLinks(markdown);if (!parsed.links.length) return { text, attachments: [] as ChatUploadAttachment[] };@@ -193,14 +197,23 @@ export async function prepareChatReplyFiles(text: string, sessionId: string, assconst lexicalRoot = path.resolve(scope.workingDir!);if (!isPathWithin(lexicalRoot, source) && !isPathWithin(root, source)) throw unavailable();const canonicalSource = isPathWithin(root, source) ? source : path.resolve(root, path.relative(lexicalRoot, source));- // Windows path identity ignores case; preserve the original spelling for- // subsequent realpath, descriptor and workdir checks.- const identity = process.platform === 'win32' ? canonicalSource.toLowerCase() : canonicalSource;+ // Use the actual volume's inode identity (including case-insensitive APFS),+ // not a platform-wide casing assumption. Never follow the named symlink;+ // full realpath/descriptor containment is still enforced before reading.+ let identity = canonicalSource;+ try {+ const stat = await fs.lstat(canonicalSource, { bigint: true });+ if (stat.isFile() && stat.ino !== 0n) identity = `${stat.dev}:${stat.ino}`;+ } catch (error) {+ // Preserve deferred missing-file failure and the shared count limit.+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ assertCurrent();if (seen.has(identity)) continue;if (attachments.length >= BOT_GROUP_ATTACHMENTS_MAX) throw unavailable();seen.add(identity);let digest: string | undefined;- attachments.push({ id: canonicalSource, name: path.basename(source), category: 'file',+ attachments.push({ id: canonicalSource, sourceOffset: link.outputStart, name: path.basename(source), category: 'file',mimeType: path.extname(source).toLowerCase() === '.pdf' ? 'application/pdf' : 'application/octet-stream',size: 0, path: null, url: null, assertCurrent,readBytes: async () => {diff --git a/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyImages.tsindex 5491840182..42ca79e4fc 100644--- a/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts@@ -1,22 +1,31 @@import fs from 'node:fs/promises';import path from 'node:path';-import { BOT_GROUP_ATTACHMENTS_MAX, type BotGroupAttachment } from '../../shared/botGroupChat.js';+import { BOT_GROUP_ATTACHMENTS_MAX } from '../../shared/botGroupChat.js';import { parseBlobUrl, resolveSafe } from '../cindy-media/blobStore.js';import { sessionCanRead } from '../cindy-media/ledger.js';import { materializeTaskImageTextResult } from '../cindy-media/taskImageDelivery.js';import { hasLocalTaskImages, taskImageReferences, rewriteTaskImageReferences } from '../cindy-media/taskImageMarkdown.js';+import type { ChatUploadAttachment } from './chatServerMedia.js';import { getDbClient } from '../localDb/client/current.js';/** Prepare only rendered, task-owned generated images. Never reads legacy caches. */export async function prepareChatReplyImages(text: string, sessionId: string, assertCurrent: () => void) {assertCurrent();+ const originalImages = taskImageReferences(text);+ let replacements = new Map<string, string>();if (hasLocalTaskImages(text)) {const imported = await materializeTaskImageTextResult(sessionId, text);assertCurrent();if (imported.failures.length || hasLocalTaskImages(imported.text)) throw new Error('ATTACHMENT_UNAVAILABLE');text = imported.text;+ replacements = imported.replacements;}- const attachments: BotGroupAttachment[] = [];+ const positions = new Map<string, number>();+ for (const ref of originalImages) {+ const url = replacements.get(ref.url) ?? ref.url;+ if (!positions.has(url)) positions.set(url, ref.start);+ }+ const attachments: ChatUploadAttachment[] = [];const delivered = new Map<string, string>();for (const ref of taskImageReferences(text)) {if (!/^(cindy-media|xdt-image):\/\//.test(ref.url) || delivered.has(ref.url)) continue;@@ -29,7 +38,7 @@ export async function prepareChatReplyImages(text: string, sessionId: string, asconst stat = await fs.stat(image.absPath);assertCurrent();if (!stat.isFile() || stat.size <= 0 || stat.size > 100 * 1024 * 1024) throw new Error('ATTACHMENT_UNAVAILABLE');- attachments.push({ id: ref.url, name: path.basename(image.absPath), category: 'image',+ attachments.push({ id: ref.url, sourceOffset: positions.get(ref.url), name: path.basename(image.absPath), category: 'image',mimeType: image.mimeType, size: stat.size, url: ref.url, path: null });delivered.set(ref.url, ref.url);}