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): count reconciled images and guard metadata lookups

ylliuuu66551f2a30cd45
diff --git a/apps/desktop/src/main/cindy-media/__tests__/taskImageDelivery.test.ts b/apps/desktop/src/main/cindy-media/__tests__/taskImageDelivery.test.ts
index d1572456b8..3687d59a10 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/taskImageDelivery.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/taskImageDelivery.test.ts
@@ -167,16 +167,29 @@ describe('task image delivery', () => {
expect((await attachments[1]!.readBytes!()).toString()).toBe('%PDF-1.4');
});
- it('reconciles different local paths imported as the same image at the first file occurrence', async () => {
- const first = path.join(work, 'first.png'), second = path.join(work, 'second.png');
- await fs.writeFile(first, PNG);
- await fs.writeFile(second, PNG);
- const files = await prepareChatReplyFiles(`[download](<${second}>) ![a](<${first}>) ![b](<${second}>)`, 's', () => {});
+ it.each([2, 21])('reconciles %s local image paths before the combined attachment limit', async count => {
+ const sources = Array.from({ length: count }, (_, i) => path.join(work, `same-${i}.png`));
+ for (const source of sources) await fs.writeFile(source, PNG);
+ const files = await prepareChatReplyFiles(sources.map(source => `[download](<${source}>) ![preview](<${source}>)`).join(' '), 's', () => {});
const images = await prepareChatReplyImages(files.text, 's', () => {}, files.attachments);
const attachments = mergeChatReplyAttachments(images.attachments, files.attachments);
expect(attachments).toHaveLength(1);
expect(attachments[0]).toMatchObject({ category: 'image', sourceOffset: 0 });
- expect(attachments[0]!.sourcePaths).toEqual(expect.arrayContaining([await fs.realpath(first), await fs.realpath(second)]));
+ expect(attachments[0]!.sourcePaths).toEqual(await Promise.all(sources.map(source => fs.realpath(source))));
+ });
+
+ it.each([false, true])('rejects 21 non-image files even with rendered images (shared references: %s)', async shared => {
+ const image = path.join(work, 'preview.png');
+ await fs.writeFile(image, PNG);
+ const sources = Array.from({ length: 21 }, (_, i) => path.join(work, `report-${i}.pdf`));
+ for (const source of sources) await fs.writeFile(source, '%PDF-1.4');
+ const body = shared
+ ? sources.map((source, i) => `[file][r${i}] ![preview][r${i}]\n\n[r${i}]: <${source}>\n`).join('\n')
+ : `![preview](<${image}>) ` + sources.map(source => `[file](<${source}>)`).join(' ');
+ await expect((async () => {
+ const files = await prepareChatReplyFiles(body, 's', () => {});
+ return prepareChatReplyImages(files.text, 's', () => {}, files.attachments);
+ })()).rejects.toThrow('ATTACHMENT_UNAVAILABLE');
});
it('retains file read safeguards when a rendered image also has a hard-linked download target', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts
index b1d9c7263e..f9b46a1567 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts
@@ -52,6 +52,13 @@ describe('generated reply image attachments', () => {
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.each(['//attacker/share/image.png', 'xdt-file:///%2Fattacker/share/image.png'])('rejects network image sources before metadata lookup: %s', async source => {
+ const text = `![image](<${source}>)`;
+ f.materialize.mockResolvedValue({ text, replacements: new Map(), failures: [source] });
+ await expect(prepareChatReplyImages(text, 'lane', vi.fn())).rejects.toThrow('ATTACHMENT_UNAVAILABLE');
+ expect(f.realpath).not.toHaveBeenCalled();
+ });
+
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');
diff --git a/apps/desktop/src/main/maker-ipc/chatServerReplyAttachments.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyAttachments.ts
index e2e9aeaeaa..ce252df263 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerReplyAttachments.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyAttachments.ts
@@ -1,5 +1,10 @@
import type { ChatUploadAttachment } from './chatServerMedia.js';
+/** Check decoded paths before any filesystem lookup can contact a remote share. */
+export function isNetworkOrDevicePath(value: string): boolean {
+ return /^[\\/]{2}|^[\\/]\?\?[\\/]/.test(value);
+}
+
/** A rendered image and its download link share one upload at their first occurrence. */
export function mergeChatReplyAttachments(images: ChatUploadAttachment[], files: ChatUploadAttachment[]): ChatUploadAttachment[] {
const imageSources = new Map<string, ChatUploadAttachment>();
diff --git a/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts
index 2a8c7024b6..89d88502d8 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts
@@ -13,7 +13,8 @@ import { messages, sessions } from '../localDb/schema.js';
import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';
import { visibleMessageText } from '../localDb/conversationSearch.pure.js';
import { safeDecodeHrefForLookup } from '../pathResolver.js';
-import { isPathWithin } from '../cindy-media/taskImageMarkdown.js';
+import { isPathWithin, localTaskImagePath, taskImageReferences } from '../cindy-media/taskImageMarkdown.js';
+import { isNetworkOrDevicePath } from './chatServerReplyAttachments.js';
import { BOT_GROUP_ATTACHMENTS_MAX } from '../../shared/botGroupChat.js';
import type { ChatUploadAttachment } from './chatServerMedia.js';
@@ -144,7 +145,7 @@ function localPath(url: string, workDir: string): string {
}
} catch { throw unavailable(); }
// Never resolve a network/device path, including on another host platform.
- if (/^[\\/]{2}|^[\\/]\?\?[\\/]/.test(value) || value.includes('\0')) throw unavailable();
+ if (isNetworkOrDevicePath(value) || value.includes('\0')) throw unavailable();
if (/^[A-Za-z]:/.test(value) && process.platform !== 'win32') throw unavailable();
return path.resolve(workDir, value);
}
@@ -214,6 +215,19 @@ export async function prepareChatReplyFiles(text: string, sessionId: string, ass
assertCurrent();
const attachments: ChatUploadAttachment[] = [];
const seen = new Set<string>();
+ const imageSources = new Set<string>();
+ if (parsed.links.length > BOT_GROUP_ATTACHMENTS_MAX) {
+ const inspected = new Set<string>();
+ for (const ref of taskImageReferences(parsed.text)) {
+ const local = localTaskImagePath(ref.url);
+ if (!local || isNetworkOrDevicePath(local) || inspected.has(ref.url)) continue;
+ inspected.add(ref.url);
+ const real = await fs.realpath(local).catch(() => undefined);
+ assertCurrent();
+ if (real && isPathWithin(root, real)) imageSources.add(real);
+ }
+ }
+ let fileCount = 0;
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.
@@ -243,11 +257,16 @@ export async function prepareChatReplyFiles(text: string, sessionId: string, ass
}
assertCurrent();
if (seen.has(identity)) continue;
- if (attachments.length >= BOT_GROUP_ATTACHMENTS_MAX) throw unavailable();
- seen.add(identity);
// Metadata only: bytes still require the live authority and descriptor checks below.
const realSource = singleFile ? await fs.realpath(canonicalSource).catch(() => undefined) : undefined;
assertCurrent();
+ // Only potential rendered-image aliases defer counting to the validated
+ // image merger. Independent files still fail at the existing limit here.
+ if (!realSource || !imageSources.has(realSource)) {
+ if (fileCount >= BOT_GROUP_ATTACHMENTS_MAX) throw unavailable();
+ fileCount++;
+ }
+ seen.add(identity);
let digest: string | undefined;
attachments.push({ id: canonicalSource, sourceOffset: link.outputStart, name: path.basename(source), category: 'file',
sourceUrl: link.url,
diff --git a/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts
index 415e5c5901..ab17b3e677 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts
@@ -8,6 +8,7 @@ import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
import { hasLocalTaskImages, localTaskImagePath, taskImageReferences, rewriteTaskImageReferences } from '../cindy-media/taskImageMarkdown.js';
import type { ChatUploadAttachment } from './chatServerMedia.js';
import { getDbClient } from '../localDb/client/current.js';
+import { isNetworkOrDevicePath } from './chatServerReplyAttachments.js';
const imageLabel = (image: { alt: string }) => image.alt.replace(/[\\`*_{}[\]<>#!|]/g, '\\$&');
@@ -19,12 +20,13 @@ export async function prepareChatReplyImages(text: string, sessionId: string, as
const localSources = new Map<string, string>();
for (const ref of originalImages) {
const local = localTaskImagePath(ref.url);
- if (!local || localSources.has(ref.url)) continue;
+ if (!local || isNetworkOrDevicePath(local) || localSources.has(ref.url)) continue;
const real = await fs.realpath(local).catch(() => undefined);
assertCurrent();
if (real) localSources.set(ref.url, real);
}
const fileOnly = new Map<string, string>();
+ const fileOnlyAttachments = new Set<ChatUploadAttachment>();
const inspected = new Set<string>();
for (const ref of originalImages) {
if (!ref.identifier || inspected.has(ref.url)) continue;
@@ -36,11 +38,15 @@ export async function prepareChatReplyImages(text: string, sessionId: string, as
// A shared PDF definition must not enter image import, while real images
// (including extensionless ones) retain the existing materialization path.
// The caller verifies live file authority before these bounded descriptor reads.
- if (!localTaskImagePath(ref.url)) { fileOnly.set(ref.url, ref.url); continue; }
- if (!file.readBytes) throw new Error('ATTACHMENT_UNAVAILABLE');
- const bytes = await file.readBytes();
- assertCurrent();
- if (!sniffMediaMime(bytes)?.startsWith('image/')) fileOnly.set(ref.url, ref.url);
+ if (localTaskImagePath(ref.url)) {
+ if (!file.readBytes) throw new Error('ATTACHMENT_UNAVAILABLE');
+ const bytes = await file.readBytes();
+ assertCurrent();
+ if (sniffMediaMime(bytes)?.startsWith('image/')) continue;
+ }
+ fileOnly.set(ref.url, ref.url);
+ fileOnlyAttachments.add(file);
+ if (fileOnlyAttachments.size > BOT_GROUP_ATTACHMENTS_MAX) throw new Error('ATTACHMENT_UNAVAILABLE');
}
text = rewriteTaskImageReferences(text, fileOnly, imageLabel);
let replacements = new Map<string, string>();