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): attach generated images from ordinary group replies

ylliuuu66eeb7c09090a8
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 dc4a35defd..9ffd070a04 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -3,6 +3,8 @@ const fixture = vi.hoisted(() => ({ upload: vi.fn(async (): Promise<unknown[]> =
vi.mock('../../authManager.js', () => ({ getAccessToken: () => fixture.token, refresh: fixture.refresh }));
vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.cindy.app' }));
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 }));
// Persists across adapter recreation; the SQLite implementation has its own persistence tests.
const taskPosts = vi.hoisted(() => new Map<string, unknown>());
vi.mock('../botGroupTaskPostSnapshot.js', () => ({ prepareBotGroupTaskPost: async (taskId: string, scope: unknown, prepare: () => Promise<unknown>) => {
@@ -148,6 +150,8 @@ describe('Chat Server result delivery and refresh', () => {
fixture.refresh.mockReset().mockResolvedValue(true);
migration.read.mockReset().mockReturnValue(null);
taskPosts.clear();
+ fixture.upload.mockReset().mockResolvedValue([]);
+ replyImages.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(),
@@ -513,6 +517,57 @@ describe('Chat Server result delivery and refresh', () => {
const terminal = { sessionId: 'lane', activeInputClientId: null, outcome: 'done' as const, resultText: 'Finished reply' };
const deliveries = () => fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'complete');
+ // #6418: media visibility changes, but the original reply still determines
+ // continuation. The helper mock isolates import/ledger tests from settlement.
+ const replyImage = { id: 'image', name: 'image.png', category: 'image' as const,
+ mimeType: 'image/png', size: 3, url: 'cindy-media://image', path: null };
+ const imageBlock = { type: 'media', mediaId: '60000000-0000-4000-8000-000000000001' };
+ it.each(['Here is ![image](cindy-media://image)', '![](cindy-media://image)'])('delivers images with baseline continuation for %s', async resultText => {
+ const display = resultText.startsWith('Here') ? 'Here is image' : '';
+ replyImages.mockResolvedValue({ text: display, attachments: [replyImage] }); fixture.upload.mockResolvedValue([imageBlock]);
+ await start(); await service.settleLaneTurn({ ...terminal, resultText });
+ expect(deliveries()[0][2]).toMatchObject({ continueDiscussion: true,
+ content: [{ type: 'text', text: display || '已完成' }, imageBlock] });
+ });
+ it.each(['Hello', '', 'NO_REPLY'])('keeps the baseline no-image result for %j', async resultText => {
+ await start(); await service.settleLaneTurn({ ...terminal, resultText });
+ expect(deliveries()[0][2].continueDiscussion).toBe(resultText === 'Hello');
+ if (resultText === 'Hello') expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'Hello' }]);
+ else expect(deliveries()[0][2]).not.toHaveProperty('content');
+ });
+ it.each([408, 429, 503])('reuses imported images after HTTP %s and completion ACK loss', async status => {
+ replyImages.mockResolvedValueOnce({ text: 'Original image', attachments: [replyImage] }).mockRejectedValue(new Error('ATTACHMENT_UNAVAILABLE'));
+ fixture.upload.mockRejectedValueOnce(new ChatResponseError('TEMPORARY_UPLOAD', status)).mockResolvedValue([imageBlock]);
+ let attempts = 0;
+ fixture.handle.mockImplementation((route, _method, body) => {
+ if (body?.action === 'complete' && attempts++ === 0) throw new Error('lost ACK'); return response(route);
+ });
+ await start(); await service.settleLaneTurn({ ...terminal, resultText: '![](xdt-image:///task/generated.png)' });
+ expect(deliveries()).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(status === 429 ? 61000 : 16000);
+ expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'Original image' }, imageBlock]);
+ await vi.advanceTimersByTimeAsync(16000);
+ expect(deliveries()).toHaveLength(2); expect(deliveries()[1][2]).toEqual(deliveries()[0][2]);
+ expect(replyImages).toHaveBeenCalledOnce(); expect(fixture.upload).toHaveBeenCalledTimes(2);
+ expect(fixture.upload.mock.calls[1].slice(0, 4)).toEqual(fixture.upload.mock.calls[0].slice(0, 4));
+ expect(deps.dispatch).toHaveBeenCalledOnce();
+ });
+ it.each([
+ ['prepare', new Error('ATTACHMENT_UNAVAILABLE')],
+ ['upload', Object.assign(new Error('denied'), { code: 'EACCES', syscall: 'open' })],
+ ['upload', new ChatResponseError('UPLOAD_QUOTA', 413)],
+ ['upload', Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: 400 })],
+ ['upload', Object.assign(new TypeError('invalid URL'), { code: 'ERR_INVALID_URL' })],
+ ] as const)('settles permanent image refusal at %s: %s', async (phase, error) => {
+ replyImages.mockResolvedValue({ text: 'image', attachments: [replyImage] });
+ if (phase === 'prepare') replyImages.mockRejectedValue(error); else fixture.upload.mockRejectedValue(error);
+ await start(); await service.settleLaneTurn(terminal);
+ const failures = () => fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'fail');
+ expect(failures()).toHaveLength(1); expect(deliveries()).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(16000); expect(failures()).toHaveLength(1); 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 => {
await start();
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 804ba6cbfc..940de3d83c 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,13 @@ 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('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;
+ await expect(createChatMedia(api, () => true).upload('room', 'reply', [attachment], 'actor', () => { if (!current) throw new Error('STALE_EXECUTOR'); })).rejects.toThrow('STALE_EXECUTOR');
+ expect(f.fetch).not.toHaveBeenCalled();
+ });
+
it('uploads the bytes without a Cindy token and seals before returning the message reference', async () => {
f.read.mockResolvedValue({ buffer: Buffer.from('png'), mimeType: 'image/png' });
f.fetch.mockResolvedValue(new Response('', { status: 200 }));
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts
new file mode 100644
index 0000000000..92c85914b9
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts
@@ -0,0 +1,52 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import path from 'node:path';
+const f = vi.hoisted(() => ({ stat: vi.fn(), canRead: vi.fn(), resolve: vi.fn(), materialize: vi.fn(), db: {} }));
+vi.mock('node:fs/promises', () => ({ default: { stat: f.stat } }));
+vi.mock('../../cindy-media/taskImageDelivery.js', () => ({ materializeTaskImageTextResult: f.materialize }));
+vi.mock('../../cindy-media/ledger.js', () => ({ sessionCanRead: f.canRead }));
+vi.mock('../../cindy-media/blobStore.js', async original => ({ ...await original<typeof import('../../cindy-media/blobStore.js')>(), resolveSafe: f.resolve }));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: f.db }) }));
+import { prepareChatReplyImages } from '../chatServerReplyImages.js';
+const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;
+// Unit: public preparation entry; fake ledger/files isolate authorization and
+// Markdown collection from settlement. Actual task importer has its own tests.
+describe('generated reply image attachments', () => {
+ beforeEach(() => {
+ 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: [] }));
+ });
+ it('imports local task images and deduplicates only rendered references', async () => {
+ f.materialize.mockResolvedValue({ text: `![First](${url}) ![Again](${url})`, failures: [] });
+ const source = '![First](xdt-image:///task/generated.png)';
+ const result = await prepareChatReplyImages(source, 'lane', vi.fn());
+ expect(f.materialize).toHaveBeenCalledExactlyOnceWith('lane', source);
+ expect(result.text).toBe('First Again');
+ expect(result.attachments).toEqual([expect.objectContaining({ url, path: null, category: 'image', size: 3 })]);
+ expect(f.canRead).toHaveBeenCalledExactlyOnceWith('a'.repeat(64), 'lane', f.db);
+ });
+ it('leaves text, code samples, external images and unreferenced definitions unchanged', async () => {
+ const text = `Hello \`![sample](${url})\`\n![web](https://example.test/image.png)\n\n[unused]: ${url}`;
+ expect(await prepareChatReplyImages(text, 'lane', vi.fn())).toEqual({ text, attachments: [] });
+ expect(f.stat).not.toHaveBeenCalled(); expect(f.canRead).not.toHaveBeenCalled();
+ });
+ it.each(['foreign', 'invalid', 'video', 'legacy', 'unimported'])('refuses an unavailable image: %s', async kind => {
+ if (kind === 'foreign') f.canRead.mockResolvedValue(false);
+ if (kind === 'video') f.resolve.mockReturnValue({ absPath: path.resolve('fixture', 'video.mp4'), mimeType: 'video/mp4' });
+ const ref = kind === 'invalid' ? url + '?other=1' : kind === 'legacy' ? 'xdt-image://lane/image.png'
+ : kind === 'unimported' ? 'xdt-image:///outside/image.png' : url;
+ await expect(prepareChatReplyImages(`![image](${ref})`, 'lane', vi.fn())).rejects.toThrow('ATTACHMENT_UNAVAILABLE');
+ expect(f.stat).not.toHaveBeenCalled();
+ });
+ it('rejects over 20 unique attachments without silently truncating', async () => {
+ const images = Array.from({ length: 21 }, (_, i) => `![image](cindy-media://blobs/${i.toString(16).padStart(64, '0')}.png)`);
+ expect((await prepareChatReplyImages(images.slice(0, 20).join(' '), 'lane', vi.fn())).attachments).toHaveLength(20);
+ await expect(prepareChatReplyImages(images.join(' '), 'lane', vi.fn())).rejects.toThrow('ATTACHMENT_UNAVAILABLE');
+ });
+ it('stops after an execution changes during authorization', async () => {
+ let current = true; f.canRead.mockImplementation(async () => { current = false; return true; });
+ await expect(prepareChatReplyImages(`![image](${url})`, 'lane', () => { if (!current) throw new Error('STALE_EXECUTOR'); })).rejects.toThrow('STALE_EXECUTOR');
+ expect(f.stat).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 2816d61f3e..940027bdd6 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -16,6 +16,7 @@ import { request as httpsRequest } from 'node:https';
import { migrateLocalGroups, type ChatContentBlock } from './chatServerMigration.js';
import { chatErrorDiagnostic, chatGroupFailure, missingGroupCode } from './chatServerErrors.js';
import { createChatMedia } from './chatServerMedia.js';
+import { prepareChatReplyImages } from './chatServerReplyImages.js';
import { chatServerWorkspaces } from './chatServerWorkspaces.js';
import { buildPlanStepBrief } from './botGroupDivision.js';
import { chatMigrationReceipts } from './chatMigrationReceipts.js';
@@ -90,7 +91,7 @@ interface Running {
lane?: string;
laneLookup?: Promise<void>;
context?: ExecutionContext;
- settlement?: { terminal: BotGroupLaneTerminal; payload?: Record<string, unknown>; retryAt: number; keepLease?: boolean };
+ settlement?: { terminal: BotGroupLaneTerminal; payload?: Record<string, unknown>; reply?: { sourceText: string; text: string; attachments: BotGroupAttachment[] }; retryAt: number; keepLease?: boolean };
delivery?: Promise<void>;
plan?: ServerPlan;
workspace?: { workDir: string; branch: string | null; ownerSessionId: string | null };
@@ -1454,9 +1455,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
run.delivery = (async () => {
try {
if (!pending.payload) {
- const terminal = pending.terminal;
- let text = terminal.resultText;
- if (!text.trim() && terminal.resultMessageClientId) text = (await readPersistedReplyText(terminal.sessionId, terminal.resultMessageClientId)) ?? '';
+ let 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[] = [];
if (terminal.outcome !== 'error' && run.workspace && run.beforeFiles && deps.workDir) {
const files = await deps.workDir.changedFiles(run.workspace.workDir, run.beforeFiles);
@@ -1467,13 +1468,39 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (stat.isFile()) produced.push({ id: name, name: path.basename(name), category: 'file', mimeType: 'application/octet-stream', size: stat.size, path: fullPath, url: null });
}
}
- const files = await media.upload(run.execution.conversation_id, `step:${run.execution.id}:${run.execution.epoch}`, produced, run.execution.bot_id);
+ const assertCurrent = () => {
+ if (!current() || running.get(run.execution.id) !== run) throw new Error('STALE_EXECUTOR');
+ };
+ let contentText = text;
+ let files: ChatContentBlock[] = [];
+ try {
+ if (terminal.outcome !== 'error') {
+ if (!run.plan) {
+ 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);
+ assertCurrent();
+ }
+ } catch (error) {
+ const { code, status } = chatErrorDiagnostic(error);
+ const permanentMediaResponse = error instanceof ChatResponseError && !retryableResponse(error)
+ && !['AUTH_REQUIRED', 'PERMISSION_DENIED', 'NOT_FOUND', 'GROUP_DISSOLVED', 'GROUP_ARCHIVED'].includes(chatGroupFailure(error).errorCode)
+ && !['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
+ || ['INVALID_MEDIA_URL', 'ERR_INVALID_URL'].includes(code))) throw error;
+ terminal = pending.terminal = { ...terminal, outcome: 'error', failureCode: 'RUNTIME_ERROR' };
+ }
if (terminal.outcome === 'error') {
failureCodes.set(`${run.execution.id}:${run.execution.epoch}`, terminal.failureCode ?? 'RUNTIME_ERROR');
if (failureCodes.size > 1000) failureCodes.delete(failureCodes.keys().next().value!);
}
pending.payload = terminal.outcome === 'error' ? { detail: botGroupRuntimeFailureDetail(terminal.failureCode ?? 'RUNTIME_ERROR') }
- : { ...(isBotGroupNoReplyText(text) && !files.length ? {} : { content: [{ type: 'text', text: text.slice(0, 16000) || '已完成' }, ...files] }),
+ : { ...(isBotGroupNoReplyText(text) && !files.length ? {} : { content: [{ type: 'text', text: contentText.slice(0, 16000) || '已完成' }, ...files] }),
// A single-speaker server never chains rounds, so there is nothing to continue.
...(singleSpeaker ? {} : { continueDiscussion: run.context?.kind !== 'member.joined' && !run.plan && !isBotGroupNoReplyText(text) }) };
}
diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
index a7e69ea01b..8d99007cd3 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
@@ -29,7 +29,8 @@ 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): Promise<ChatContentBlock[]> {
+ async upload(roomId: string, source: string, attachments: BotGroupAttachment[], actorId: string, assertCurrent?: () => void): Promise<ChatContentBlock[]> {
+ const checkUpload = () => { check(); assertCurrent?.(); };
const results: Array<PromiseSettledResult<ChatContentBlock>> = new Array(attachments.length);
let next = 0;
const worker = async () => {
@@ -48,15 +49,15 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa
let stage = 'read';
const started = Date.now();
try {
- check();
+ checkUpload();
if (attachment.size > MAX_SIZE) throw new Error('ATTACHMENT_TOO_LARGE');
if (attachment.path) {
- const stat = await fs.stat(attachment.path); check();
+ const stat = await fs.stat(attachment.path); checkUpload();
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
: attachment.path ? await fs.readFile(attachment.path) : null;
- check();
+ checkUpload();
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
@@ -73,12 +74,12 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa
operationId: `media:${key}:${randomUUID()}`, name: attachment.name, type: attachment.mimeType, size: bytes.length,
}, actorId);
}
- check();
+ checkUpload();
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 });
- check();
+ checkUpload();
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/chatServerReplyImages.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts
new file mode 100644
index 0000000000..5491840182
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts
@@ -0,0 +1,38 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { BOT_GROUP_ATTACHMENTS_MAX, type BotGroupAttachment } 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 { 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();
+ 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;
+ }
+ const attachments: BotGroupAttachment[] = [];
+ 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;
+ const blob = parseBlobUrl(ref.url);
+ if (!blob || attachments.length >= BOT_GROUP_ATTACHMENTS_MAX
+ || !await sessionCanRead(blob.hash, sessionId, getDbClient().drizzle)) throw new Error('ATTACHMENT_UNAVAILABLE');
+ assertCurrent();
+ const image = resolveSafe(ref.url);
+ if (!image.mimeType.startsWith('image/')) throw new Error('ATTACHMENT_UNAVAILABLE');
+ const 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',
+ mimeType: image.mimeType, size: stat.size, url: ref.url, path: null });
+ delivered.set(ref.url, ref.url);
+ }
+ return { attachments, text: rewriteTaskImageReferences(text, delivered, image =>
+ image.alt.replace(/[\\`*_{}[\]<>#!|]/g, '\\$&')) };
+}
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 8574eb1c06..45d6dda5ca 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -456,6 +456,8 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下
## 10. Chat Server 多账号群的授权补充(2026-10-03)
+普通回复中明确展示的当前任务生成图片作为群附件交付,其他有权限的成员可以查看和下载;图片交付失败不降级为丢图的纯文字成功回复。
+
Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授权」。正式群聊统一使用 Chat Server;已有本地群及消息自动迁移,不保留并行本地群入口。Agent 工作目录与私人资料仍留在执行端,外部成员的访问继续受下述授权边界约束。服务端群历史与 Agent 本机/云端执行分离,人和伙伴共用成员、群角色和消息合同,国内与国际账号可以互邀。
正式适配器同时接通继续讨论、负责人、项目文件夹和交互式分工。计划、步骤、批注和执行状态由服务器保存;开始、继续、重试、更换伙伴、移除步骤及停止沿用同一执行租约与主人授权。旧安排导入后可继续操作,原运行中的步骤转为等待明确重试,不自动重放工具。项目目录及 worktree 路径只保存在对应账号的执行电脑上;步骤产物通过私有附件交接。仅聊天的分工专线同样隔离主人上下文、工作目录和工具权限。第 1–9 节中的本地表描述仅保留为迁移源/计算缓存的历史实现说明,群消息的最终存储要求以本节为准。代码接线不等于部署完成:部署仓登记、两区 CDN 清单和生产双账号/设备验收仍为发布前置。