Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): deliver linked reply files as group attachments
ylliuuu66bdbbca3813e4
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex 4c4018532f..02c10f1cdd 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';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 }> }));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: [] })));vi.mock('../chatServerReplyImages.js', () => ({ prepareChatReplyImages: replyImages }));@@ -152,6 +154,7 @@ describe('Chat Server result delivery and refresh', () => {taskPosts.clear();fixture.upload.mockReset().mockResolvedValue([]);replyImages.mockReset().mockImplementation(async text => ({ text, attachments: [] }));+ replyFiles.prepare.mockReset().mockImplementation(async text => ({ text, attachments: [] }));deps = { ensureLane: vi.fn(async () => ({ ok: true, sessionId: 'lane' })), abortLane: vi.fn(async () => {}),dispatch: vi.fn(async (input: Parameters<BotGroupChatServiceDeps['dispatch']>[0]) => { await input.onAccepted?.(); return { ok: true }; }),onChanged: vi.fn(),@@ -582,6 +585,85 @@ describe('Chat Server result delivery and refresh', () => {expect(replyImages).toHaveBeenCalledOnce(); expect(deps.dispatch).toHaveBeenCalledOnce();});+ // #6761: ordinary reply files must reach the completion payload, not remain local links.+ it('delivers a PDF reply and retries a lost completion ACK without another upload', async () => {+ const file = { id: 'pdf', name: 'report.pdf', category: 'file', mimeType: 'application/pdf', size: 0, path: null, url: null };+ replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [file] });+ fixture.upload.mockResolvedValueOnce([{ type: 'media', mediaId: 'pdf', caption: 'report.pdf' }]);+ let attempts = 0;+ fixture.handle.mockImplementation((route, _method, body) => {+ if (body?.action === 'complete' && ++attempts === 1) throw new Error('ECONNRESET');+ return response(route);+ });+ await start();+ const uploads = fixture.upload.mock.calls.length;+ await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'Report' }, { type: 'media', mediaId: 'pdf', caption: 'report.pdf' }]);+ await vi.advanceTimersByTimeAsync(16000);+ expect(deliveries()).toHaveLength(2);+ expect(deliveries()[1][2]).toEqual(deliveries()[0][2]);+ expect(fixture.upload.mock.calls.length - uploads).toBe(1);+ 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' };+ replyFiles.prepare.mockResolvedValue({ text: 'Images and report', attachments: [pdf] });+ replyImages.mockResolvedValue({ text: 'Delivered', attachments: images });+ const blocks = [...images, pdf].map(file => ({ type: 'media', mediaId: file.id }));+ fixture.upload.mockRejectedValueOnce(Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: 503 })).mockResolvedValue(blocks);+ await start();+ await service.settleLaneTurn({ ...terminal, resultText: ' [Report](./report.pdf)' });+ expect(deliveries()).toHaveLength(0);+ await vi.advanceTimersByTimeAsync(16000);+ expect(fixture.upload).toHaveBeenLastCalledWith(roomId, expect.any(String), [...images, pdf], expect.any(String), expect.any(Function));+ expect(deliveries()).toHaveLength(1);+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'Delivered' }, ...blocks]);+ expect(replyFiles.prepare).toHaveBeenCalledOnce(); expect(replyImages).toHaveBeenCalledOnce();+ expect(deps.dispatch).toHaveBeenCalledOnce();+ });++ it('refuses mixed attachments exceeding the shared twenty-file limit before upload', async () => {+ replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf' }] });+ replyImages.mockResolvedValue({ text: 'Images', attachments: Array.from({ length: 20 }, (_, i) => ({ ...replyImage, id: `image-${i}` })) });+ await start();+ const uploads = fixture.upload.mock.calls.length;+ await service.settleLaneTurn({ ...terminal, resultText: 'Images and PDF' });+ expect(fixture.upload.mock.calls.length).toBe(uploads);+ expect(deliveries()).toHaveLength(0);+ expect(fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'fail')).toHaveLength(1);+ });++ it('fails a refused reply file instead of publishing a successful local path', async () => {+ replyFiles.prepare.mockRejectedValue(new Error('ATTACHMENT_UNAVAILABLE'));+ await start();+ await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });+ expect(deliveries()).toHaveLength(0);+ expect(fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'fail')).toHaveLength(1);+ });++ it.each([400, 413, 415, 422])('reports a file rejected by the media service (%s)', async status => {+ replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf', name: 'report.pdf' }] });+ fixture.upload.mockRejectedValueOnce(new ChatResponseError('FILE_REFUSED', status));+ await start();+ await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });+ expect(deliveries()).toHaveLength(0);+ expect(fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'fail')).toHaveLength(1);+ });++ it('retries a transient file upload without preparing files or running the Agent again', async () => {+ replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf', name: 'report.pdf' }] });+ fixture.upload.mockRejectedValueOnce(Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: 503 }))+ .mockResolvedValueOnce([{ type: 'media', mediaId: 'pdf', caption: 'report.pdf' }]);+ await start();+ await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });+ expect(deliveries()).toHaveLength(0);+ await vi.advanceTimersByTimeAsync(16000);+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'Report' }, { type: 'media', mediaId: 'pdf', caption: 'report.pdf' }]);+ expect(replyFiles.prepare).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 => {@@ -1569,6 +1651,29 @@ describe('Chat Server result delivery and refresh', () => {expect(deliveries()[0][2]).not.toHaveProperty('continueDiscussion');});+ it.each(['talk', 'work'] as const)('delivers explicit files for talk replies without changing the work pipeline (%s)', async kind => {+ const planId = '80000000-0000-4000-8000-000000000001';+ const plan = { id: planId, revision: 1, source_message_id: execution.source_message_id, request_text: 'Report', organizer_id: botId, creator_id: selfId,+ status: 'running', current_step: 0, kind, steps: [{ position: 0, botId, botName: 'Bot', task: 'report', status: 'running' }] };+ singleSpeaker(route => {+ if (route === '/executions/claim' && !claimed) { claimed = true; return { body: { execution: { ...execution, access_mode: kind === 'talk' ? 'owner' : 'chat', plan_id: planId, plan_step: 0 } } }; }+ if (route.includes('/plans?ids=')) return { body: [plan] };+ if (route.endsWith(`/messages/${execution.source_message_id}`)) return { body: message(execution.source_message_id, 'Report') };+ return undefined;+ });+ replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf', name: 'report.pdf' }] });+ fixture.upload.mockImplementationOnce(async () => kind === 'talk' ? [{ type: 'media', mediaId: 'pdf', caption: 'report.pdf' }] : []);+ await start();+ await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });+ expect(deliveries()[0][2]).not.toHaveProperty('continueDiscussion');+ if (kind === 'talk') {+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'Report' }, { type: 'media', mediaId: 'pdf', caption: 'report.pdf' }]);+ } else {+ expect(replyFiles.prepare).not.toHaveBeenCalled();+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: '[Report](./report.pdf)' }]);+ }+ });+it('sends without holding the request for a helper-model arrangement decision', async () => {singleSpeaker();deps.decidePlan = vi.fn() as typeof deps.decidePlan;@@ -3343,6 +3448,7 @@ describe('Chat authentication recovery and polling backoff', () => {fixture.refresh.mockReset().mockResolvedValue(true);migration.read.mockReset().mockReturnValue(null);taskPosts.clear();+ replyFiles.prepare.mockReset().mockImplementation(async text => ({ text, attachments: [] }));fixture.handle.mockReset().mockImplementation(healthy);service = withChatServer({ dispose: vi.fn(), listGroups: async () => ({ ok: true, groups: [] }) } as unknown as BotGroupChatService, {} as BotGroupChatServiceDeps);});@@ -3353,6 +3459,7 @@ describe('Chat authentication recovery and polling backoff', () => {fixture.refresh.mockReset().mockResolvedValue(true);migration.read.mockReset().mockReturnValue(null);taskPosts.clear();+ replyFiles.prepare.mockReset().mockImplementation(async text => ({ text, attachments: [] }));vi.useRealTimers();});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.tsindex 5b490804e3..ed238d1c30 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts@@ -40,6 +40,22 @@ describe('chat private media', () => {expect(f.fetch).toHaveBeenLastCalledWith('https://upload.example.test/signed', expect.objectContaining({ redirect: 'error', headers: { 'Content-Type': 'image/png' } }));expect(vi.mocked(api).mock.calls.at(-1)?.[0]).toBe('/conversations/room/media/media/complete');});+ it('uploads authorized reply bytes and refuses an expired execution before PUT', async () => {+ f.fetch.mockReset().mockResolvedValue(new Response('', { status: 200 }));+ const readBytes = vi.fn(async () => Buffer.from('%PDF-1.4'));+ let valid = true;+ const file = { ...attachment, name: 'report.pdf', mimeType: 'application/pdf', url: null, path: null, readBytes,+ assertCurrent: () => { if (!valid) throw new Error('STALE_EXECUTOR'); } };+ const api = vi.fn(async (route: string) => route.endsWith('/media') ? { id: 'pdf', uploadUrl: 'https://upload.example.test/signed' } : {}) as unknown as ChatApi;+ const media = createChatMedia(api, () => true);+ expect(await media.upload('room', 'operation', [file], 'actor')).toEqual([{ type: 'media', mediaId: 'pdf', caption: 'report.pdf' }]);+ expect(f.fetch).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ body: new Uint8Array(Buffer.from('%PDF-1.4')) }));+ f.fetch.mockClear();+ vi.mocked(api).mockImplementationOnce(async () => { valid = false; return { id: 'pdf', uploadUrl: 'https://upload.example.test/signed' }; });+ await expect(media.upload('room', 'retry', [file], 'actor')).rejects.toThrow('STALE_EXECUTOR');+ expect(f.fetch).not.toHaveBeenCalled();+ });+it.each(['prepare', 'upload', 'complete'])('reports the failing %s stage without signed URLs or filenames', async (stage) => {f.read.mockResolvedValue({ buffer: Buffer.from('png') });const log = { warn: vi.fn() };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.tsnew file mode 100644index 0000000000..acd593cb89--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.ts@@ -0,0 +1,116 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { pathToFileURL } from 'node:url';++const scope = vi.hoisted(() => ({ snapshot: null as unknown, row: {} as Record<string, unknown>, reply: null as { content: string } | null }));+vi.mock('../../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => scope.snapshot }));+import { messages } from '../../localDb/schema.js';+import { prepareChatReplyFiles, readReplyFile } from '../chatServerReplyFiles.js';++// #6761: production file preparation and descriptor reading. Group adapter tests mock+// this boundary; these unit cases verify real scope, bytes and Markdown (small temp files).+describe('group reply file delivery', () => {+ let root: string, work: string, pdf: string;+ beforeAll(async () => {+ root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'chat-reply-files-')));+ work = path.join(root, 'task'); await fs.mkdir(work);+ pdf = path.join(work, 'report 中文.pdf');+ await fs.writeFile(path.join(root, 'private.pdf'), 'private');+ });+ beforeEach(async () => {+ await fs.writeFile(pdf, '%PDF-1.4\nreport');+ scope.row = { workingDir: work, remoteHostId: null, status: 'active', clearedAt: null };+ scope.reply = null;+ scope.snapshot = { client: { drizzle: { select: () => ({ from: (table: unknown) => ({ where: () => ({ limit: async () => table === messages ? (scope.reply ? [scope.reply] : []) : [{ ...scope.row }] }) }) }) } } };+ });+ afterAll(async () => { await fs.rm(root, { recursive: true, force: true }); });++ it('delivers explicit PDF links once with their bytes and removes local links from the body', async () => {+ const url = pathToFileURL(pdf).href.replace(/^file:/, 'xdt-file:');+ const result = await prepareChatReplyFiles(`[报告](${url}) and [再次](${url})`, 'lane', () => {});+ expect(result.text).toBe('报告 and 再次');+ expect(result.attachments).toHaveLength(1);+ expect(result.attachments[0]).toMatchObject({ name: path.basename(pdf), mimeType: 'application/pdf', path: null, url: null });+ expect((await result.attachments[0]!.readBytes!()).toString()).toBe('%PDF-1.4\nreport');+ });++ it('supports angle-bracket paths, relative and reference links without consuming images or examples', async () => {+ const body = `[报告](<${pdf}>)\n[再次][r]\n\n[r]: <${pdf}>\n\n\`[example](./x.pdf)\`\n\n[web](https://example.test/r.pdf)`;+ const result = await prepareChatReplyFiles(body, 'lane', () => {});+ expect(result.attachments).toHaveLength(1);+ expect(result.text).not.toContain(pdf);+ expect(result.text).toContain('`[example](./x.pdf)`');+ expect(result.text).toContain('');+ expect(result.text).toContain('[web](https://example.test/r.pdf)');+ const relative = await prepareChatReplyFiles('[报告](<./report 中文.pdf>)', 'lane', () => {});+ expect((await relative.attachments[0]!.readBytes!()).length).toBeGreaterThan(0);+ const escaped = await prepareChatReplyFiles(`[报告](<${pdf}>)`, 'lane', () => {});+ expect(escaped.text).toBe('报告');+ expect((await escaped.attachments[0]!.readBytes!()).toString()).toBe('%PDF-1.4\nreport');+ });++ 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');+ expect(result.attachments).toHaveLength(1);+ expect((await result.attachments[0]!.readBytes!()).toString()).toBe('%PDF-1.4\nreport');+ expect(result.text.trim()).toBe('报告');+ scope.reply = { content: JSON.stringify({ text: 'First\nSecond' }) };+ expect(await prepareChatReplyFiles('First Second', 'lane', () => {}, 'reply-client')).toEqual({ text: 'First Second', attachments: [] });+ });++ it('does not access session scope for ordinary text, remote links, fenced examples or images', async () => {+ scope.snapshot = null;+ const text = '```md\n[example](./x.pdf)\n```\n\n[web](https://example.test)';+ expect(await prepareChatReplyFiles(text, 'lane', () => { throw new Error('unexpected'); })).toEqual({ text, attachments: [] });+ });++ it.each(['../private.pdf', 'file://server/private.pdf', '//server/private.pdf'])('refuses an out-of-scope or network file %s', async url => {+ await expect(prepareChatReplyFiles(`[file](${url})`, 'lane', () => {})).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ });++ it('refuses a symlink escaping the task before reading its bytes', async () => {+ const link = path.join(work, 'escape');+ // A real directory junction also works on unprivileged Windows runners.+ await fs.symlink(root, link, process.platform === 'win32' ? 'junction' : 'dir');+ try {+ const result = await prepareChatReplyFiles('[file](./escape/private.pdf)', 'lane', () => {});+ await expect(result.attachments[0]!.readBytes!()).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ } finally { await fs.unlink(link); }+ });++ it.each([{ remoteHostId: 'ssh-host' }, { status: 'deleted' }, { workingDir: null }])('refuses a task without local authority %j', async change => {+ Object.assign(scope.row, change);+ await expect(prepareChatReplyFiles('[file](./report.pdf)', 'lane', () => {})).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ });++ it('rechecks ownership, task clearing and the execution after preparation', async () => {+ let valid = true;+ const result = await prepareChatReplyFiles(`[file](<${pdf}>)`, 'lane', () => { if (!valid) throw new Error('STALE_EXECUTOR'); });+ scope.row.clearedAt = 1;+ await expect(result.attachments[0]!.readBytes!()).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ scope.row.clearedAt = null;+ valid = false;+ await expect(result.attachments[0]!.readBytes!()).rejects.toThrow('STALE_EXECUTOR');+ valid = true; scope.snapshot = null;+ await expect(result.attachments[0]!.readBytes!()).rejects.toThrow('OWNER_CHANGED');+ });++ it('refuses changed bytes on retry instead of uploading a second version under the same reply', async () => {+ const result = await prepareChatReplyFiles(`[file](<${pdf}>)`, 'lane', () => {});+ const first = await result.attachments[0]!.readBytes!();+ expect(await result.attachments[0]!.readBytes!()).toEqual(first);+ await fs.writeFile(pdf, '%PDF-1.4\nchanged');+ await expect(result.attachments[0]!.readBytes!()).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ });++ it('refuses too many files, empty files and directories', async () => {+ const text = Array.from({ length: 21 }, (_, i) => `[file](./${i}.pdf)`).join('\n');+ await expect(prepareChatReplyFiles(text, 'lane', () => {})).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ await fs.writeFile(pdf, '');+ await expect(readReplyFile(pdf, work, () => {})).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ await expect(readReplyFile(work, root, () => {})).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ });+});diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex e579a5c70d..9d8e45de70 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -1,3 +1,5 @@+import { prepareChatReplyFiles } from './chatServerReplyFiles.js';+import type { ChatUploadAttachment } from './chatServerMedia.js';import { createConversationListState } from '@cindy/maker-shared/chatConversationList';/** Production chat transport. The server owns messages and execution leases;* local group rows only supply Agent lane metadata and the upgrade source. */@@ -91,7 +93,7 @@ interface Running {lane?: string;laneLookup?: Promise<void>;context?: ExecutionContext;- settlement?: { terminal: BotGroupLaneTerminal; payload?: Record<string, unknown>; reply?: { sourceText: string; text: string; attachments: BotGroupAttachment[] }; retryAt: number; keepLease?: boolean };+ settlement?: { terminal: BotGroupLaneTerminal; payload?: Record<string, unknown>; reply?: { sourceText: string; text: string; attachments: ChatUploadAttachment[] }; fileReply?: Awaited<ReturnType<typeof prepareChatReplyFiles>>; retryAt: number; keepLease?: boolean };delivery?: Promise<void>;plan?: ServerPlan;workspace?: { workDir: string; branch: string | null; ownerSessionId: string | null };@@ -1458,7 +1460,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDlet terminal = pending.terminal;let text = pending.reply?.sourceText ?? terminal.resultText;if (!pending.reply && !text.trim() && terminal.resultMessageClientId) text = (await readPersistedReplyText(terminal.sessionId, terminal.resultMessageClientId)) ?? '';- const produced: BotGroupAttachment[] = [];+ const produced: ChatUploadAttachment[] = [];if (terminal.outcome !== 'error' && run.workspace && run.beforeFiles && deps.workDir) {const files = await deps.workDir.changedFiles(run.workspace.workDir, run.beforeFiles);for (const name of files) {@@ -1477,9 +1479,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDtry {if (terminal.outcome !== 'error') {if (ordinaryReply) {- pending.reply ??= { sourceText: text, ...await prepareChatReplyImages(text, run.sessionId, assertCurrent) };+ pending.fileReply ??= await prepareChatReplyFiles(text, run.sessionId, () => {+ assertCurrent();+ if (run.execution.access_mode === 'chat') throw new Error('ATTACHMENT_UNAVAILABLE');+ }, !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);+ produced.push(...pending.reply.attachments, ...pending.fileReply.attachments);+ if (produced.length > BOT_GROUP_ATTACHMENTS_MAX) throw new Error('ATTACHMENT_UNAVAILABLE');}files = await media.upload(run.execution.conversation_id, `step:${run.execution.id}:${run.execution.epoch}`,produced, run.execution.bot_id, ordinaryReply ? assertCurrent : undefined);diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.tsindex 89b4d25f61..0dbaa2e1e4 100644--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts@@ -13,6 +13,12 @@ import { safeAttachmentFileName } from './botGroupAttachments.js';import type { BotGroupAttachment } from '../../shared/botGroupChat.js';import type { ChatApi, ChatContentBlock } from './chatServerMigration.js';+/** Internal-only readers: never serialized in group messages or IPC. */+export type ChatUploadAttachment = BotGroupAttachment & {+ readBytes?: () => Promise<Buffer>;+ assertCurrent?: () => void;+};+const MAX_SIZE = 100 * 1024 * 1024;/** Files of one send uploaded at once; each holds its bytes in memory until sealed. */const UPLOAD_CONCURRENCY = 3;@@ -30,7 +36,7 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa* blocks in the files' order. Every file settles before a failure is reported, so no* upload keeps running after the send has given up; the first failure in order wins.*/- async upload(roomId: string, source: string, attachments: BotGroupAttachment[], actorId: string, assertCurrent?: () => void): Promise<ChatContentBlock[]> {+ async upload(roomId: string, source: string, attachments: ChatUploadAttachment[], actorId: string, assertCurrent?: () => void): Promise<ChatContentBlock[]> {const checkUpload = () => { check(); assertCurrent?.(); };const results: Array<PromiseSettledResult<ChatContentBlock>> = new Array(attachments.length);let next = 0;@@ -46,19 +52,20 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { waif (failed) throw failed.reason;return results.map(result => (result as PromiseFulfilledResult<ChatContentBlock>).value);- async function uploadOne(attachment: BotGroupAttachment): Promise<ChatContentBlock> {+ async function uploadOne(attachment: ChatUploadAttachment): Promise<ChatContentBlock> {let stage = 'read';const started = Date.now();+ const checkFile = () => { checkUpload(); attachment.assertCurrent?.(); };try {- checkUpload();+ checkFile();if (attachment.size > MAX_SIZE) throw new Error('ATTACHMENT_TOO_LARGE');- if (attachment.path) {- const stat = await fs.stat(attachment.path); checkUpload();+ if (attachment.path && !attachment.readBytes) {+ const stat = await fs.stat(attachment.path); checkFile();if (!stat.isFile() || stat.size > MAX_SIZE) throw new Error('ATTACHMENT_TOO_LARGE');}- const bytes = attachment.url?.startsWith('cindy-media://') ? (await readMedia(attachment.url)).buffer+ const bytes = attachment.readBytes ? await attachment.readBytes() : attachment.url?.startsWith('cindy-media://') ? (await readMedia(attachment.url)).buffer: attachment.path ? await fs.readFile(attachment.path) : null;- checkUpload();+ checkFile();if (!bytes || !bytes.length || bytes.length > MAX_SIZE) throw new Error('ATTACHMENT_UNAVAILABLE');const key = createHash('sha256').update(source).update(attachment.id).update(bytes).digest('hex');// Expired abandoned uploads must get a new prepare receipt, but a successful@@ -75,13 +82,13 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { waoperationId: `media:${key}:${randomUUID()}`, name: attachment.name, type: attachment.mimeType, size: bytes.length,}, actorId);}- checkUpload();+ checkFile();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,...(response.status === 429 ? { retryAt: retryAfterDeadline(response) } : {}) });- checkUpload();+ checkFile();stage = 'complete';await api(`/conversations/${roomId}/media/${upload.id}/complete`, 'POST', { operationId: `seal:${upload.id}` }, actorId);return { type: 'media', mediaId: upload.id, caption: attachment.name };diff --git a/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.tsnew file mode 100644index 0000000000..dd517a8fe4--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts@@ -0,0 +1,167 @@+import fs from 'node:fs/promises';+import { constants } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { createHash } from 'node:crypto';+import { and, eq, isNull } from 'drizzle-orm';+import { unified } from 'unified';+import remarkParse from 'remark-parse';+import remarkGfm from 'remark-gfm';+import { visit } from 'unist-util-visit';+import type { Definition } from 'mdast';+import { messages, sessions } from '../localDb/schema.js';+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';+import { visibleMessageText } from '../localDb/conversationSearch.pure.js';+import { isPathWithin } from '../cindy-media/taskImageMarkdown.js';+import { BOT_GROUP_ATTACHMENTS_MAX } from '../../shared/botGroupChat.js';+import type { ChatUploadAttachment } from './chatServerMedia.js';++const parser = unified().use(remarkParse).use(remarkGfm);+const MAX_BYTES = 100 * 1024 * 1024;+const unavailable = () => new Error('ATTACHMENT_UNAVAILABLE');++/** Only actual Markdown file links are deliveries; code, images and remote URLs are not. */+export function replyFileLinks(text: string) {+ // The reported reply HTML-escaped the angle brackets around paths with spaces.+ // Recover only these file links in prose, never examples inside code or HTML.+ const escaped: Array<{ start: number; end: number; text: string }> = [];+ visit(parser.parse(text), 'text', node => {+ const start = node.position?.start.offset, end = node.position?.end.offset;+ if (start === undefined || end === undefined) return;+ const raw = text.slice(start, end);+ const normalized = raw.replace(/(\[[^\]\n]+\]\()<((?:\/|[A-Za-z]:[\\/]|\.{1,2}\/|xdt-file:\/\/|file:\/\/)[^\n]*?)>(\))/g, '$1<$2>$3');+ if (normalized !== raw) escaped.push({ start, end, text: normalized });+ });+ for (const edit of escaped.sort((a, b) => b.start - a.start))+ text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);+ const tree = parser.parse(text);+ const definitions = new Map<string, Definition>();+ visit(tree, 'definition', node => {+ if (!definitions.has(node.identifier)) definitions.set(node.identifier, node);+ });+ const links: Array<{ url: string; start: number; end: number; label: string }> = [];+ const usedDefinitions = new Set<string>();+ const imageDefinitions = new Set<string>();+ visit(tree, 'imageReference', node => { imageDefinitions.add(node.identifier); });+ visit(tree, node => {+ if (node.type !== 'link' && node.type !== 'linkReference') return;+ const target = node.type === 'link' ? node : definitions.get(node.identifier);+ if (!target || !/^(?:\/|[A-Za-z]:[\\/]|\.{1,2}\/|xdt-file:\/\/|file:\/\/)/.test(target.url)) return;+ const start = node.position?.start.offset, end = node.position?.end.offset;+ const first = node.children[0]?.position?.start.offset, last = node.children.at(-1)?.position?.end.offset;+ // A linked image belongs to image delivery, not this file path.+ if (node.children.some(child => child.type === 'image' || child.type === 'imageReference')) return;+ if (start === undefined || end === undefined || first === undefined || last === undefined) return;+ links.push({ url: target.url, start, end, label: text.slice(first, last) });+ if (node.type === 'linkReference') usedDefinitions.add(node.identifier);+ });+ const edits = links.map(link => ({ start: link.start, end: link.end, text: link.label }));+ for (const identifier of usedDefinitions) {+ const node = definitions.get(identifier)!;+ if (!imageDefinitions.has(identifier) && node.position?.start.offset !== undefined && node.position.end.offset !== undefined)+ edits.push({ start: node.position.start.offset, end: node.position.end.offset, text: '' });+ }+ 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 };+}++function localPath(url: string, workDir: string): string {+ let value = url;+ if (/^(?:xdt-file|file):/.test(url)) {+ try { value = fileURLToPath(url.replace(/^xdt-file:/, 'file:')); } catch { throw unavailable(); }+ }+ // Never resolve a network/device path, including on another host platform.+ if (/^[\\/]{2}|^[\\/]\?\?[\\/]/.test(value) || value.includes('\0')) throw unavailable();+ if (/^[A-Za-z]:/.test(value) && process.platform !== 'win32') throw unavailable();+ return path.resolve(workDir, value);+}++/** One descriptor, bounded reads and inode checks keep a symlink swap from exporting another file. */+export async function readReplyFile(source: string, root: string, assertCurrent: () => void): Promise<Buffer> {+ assertCurrent();+ if (!isPathWithin(root, source)) throw unavailable();+ const real = await fs.realpath(source);+ if (!isPathWithin(root, real)) throw unavailable();+ const expected = await fs.stat(real, { bigint: true });+ const handle = await fs.open(real, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));+ try {+ const before = await handle.stat({ bigint: true });+ const checked = await fs.realpath(source);+ if (!before.isFile() || before.size <= 0n || before.size > BigInt(MAX_BYTES)) throw unavailable();+ if (before.ino === 0n || expected.ino !== before.ino || expected.dev !== before.dev || checked !== real) throw unavailable();+ assertCurrent();+ const buffer = Buffer.alloc(Number(before.size));+ let offset = 0;+ while (offset < buffer.length) {+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);+ if (!bytesRead) throw unavailable();+ offset += bytesRead;+ }+ const after = await handle.stat({ bigint: true });+ if (before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) throw unavailable();+ assertCurrent();+ return buffer;+ } finally { await handle.close(); }+}++/** Files stay outside the media store; the existing group uploader receives authorized bytes. */+export async function prepareChatReplyFiles(text: string, sessionId: string, assertExecution: () => void, fallbackMessageClientId?: string | null) {+ const snapshot = getCurrentDbClientSnapshot();+ let markdown = text;+ if (fallbackMessageClientId) {+ if (!snapshot) throw unavailable();+ const [row] = await snapshot.client.drizzle.select({ content: messages.content }).from(messages)+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, fallbackMessageClientId),+ eq(messages.role, 'assistant'), isNull(messages.rewindAt))).limit(1);+ if (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;+ }+ const parsed = replyFileLinks(markdown);+ if (!parsed.links.length) return { text, attachments: [] as ChatUploadAttachment[] };+ if (!snapshot) throw unavailable();+ const assertCurrent = () => {+ assertExecution();+ if (getCurrentDbClientSnapshot() !== snapshot) throw new Error('OWNER_CHANGED');+ };+ const readSession = async () => {+ const [row] = await snapshot.client.drizzle.select({ workingDir: sessions.workingDir,+ remoteHostId: sessions.remoteHostId, status: sessions.status, clearedAt: sessions.clearedAt })+ .from(sessions).where(eq(sessions.id, sessionId)).limit(1);+ assertCurrent();+ if (!row?.workingDir || row.remoteHostId || row.status === 'deleted') throw unavailable();+ return row;+ };+ const scope = await readSession();+ const root = await fs.realpath(scope.workingDir!);+ assertCurrent();+ const attachments: ChatUploadAttachment[] = [];+ const seen = new Set<string>();+ for (const link of parsed.links) {+ const source = localPath(link.url, scope.workingDir!);+ // /tmp can alias /private/tmp; normalize the trusted workdir prefix without following the file.+ if (!isPathWithin(path.resolve(scope.workingDir!), source)) throw unavailable();+ const canonicalSource = path.resolve(root, path.relative(scope.workingDir!, source));+ if (seen.has(canonicalSource)) continue;+ if (attachments.length >= BOT_GROUP_ATTACHMENTS_MAX) throw unavailable();+ seen.add(canonicalSource);+ let digest: string | undefined;+ attachments.push({ id: canonicalSource, 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 () => {+ const current = await readSession();+ if (current.workingDir !== scope.workingDir || current.clearedAt !== scope.clearedAt+ || await fs.realpath(current.workingDir!) !== root) throw unavailable();+ const bytes = await readReplyFile(canonicalSource, root, assertCurrent);+ const next = createHash('sha256').update(bytes).digest('hex');+ if (digest && digest !== next) throw unavailable();+ digest = next;+ return bytes;+ } });+ }+ return { text: parsed.text, attachments };+}diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 4b999abd63..af7f7b506d 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -459,6 +459,7 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下## 10. Chat Server 多账号群的授权补充(2026-10-03)普通回复中明确展示的当前任务生成图片作为群附件交付,其他有权限的成员可以查看和下载;图片交付失败不降级为丢图的纯文字成功回复。+有文件访问授权的伙伴普通回复(含讨论队列)中,明确链接的当前任务工作目录内 PDF 等文件作为群附件交付;交付失败明确报错,不把本机路径当作成功交付,也不自动收集目录内其他文件。Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授权」。正式群聊统一使用 Chat Server;已有本地群及消息自动迁移,不保留并行本地群入口。Agent 工作目录与私人资料仍留在执行端,外部成员的访问继续受下述授权边界约束。服务端群历史与 Agent 本机/云端执行分离,人和伙伴共用成员、群角色和消息合同,国内与国际账号可以互邀。