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(claude-code): harden queued image inputs

DavidShen198ff04db8ca
diff --git a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts b/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
index 646f0ed9c2..0c3b8d5806 100644
--- a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
+++ b/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
@@ -79,6 +79,7 @@ describe('agentInputQueue', () => {
size: 128,
category: 'image',
mimeType: 'image/png',
+ pathOrigin: 'desktop-host',
url: 'xdt-image://session/shot.png',
},
]),
@@ -87,7 +88,12 @@ describe('agentInputQueue', () => {
type: 'user',
content: [
{ type: 'text', text: 'inspect attachment' },
- { type: 'image', path: 'xdt-image://session/shot.png', mimeType: 'image/png' },
+ {
+ type: 'image',
+ path: 'xdt-image://session/shot.png',
+ mimeType: 'image/png',
+ pathOrigin: 'desktop-host',
+ },
],
});
});
diff --git a/apps/desktop/src/main/__tests__/claudeInput.test.ts b/apps/desktop/src/main/__tests__/claudeInput.test.ts
index 6460adde44..c968907b51 100644
--- a/apps/desktop/src/main/__tests__/claudeInput.test.ts
+++ b/apps/desktop/src/main/__tests__/claudeInput.test.ts
@@ -25,7 +25,10 @@ describe('Claude Code SDK input', () => {
const imagePath = path.join(tempDir, 'small.png');
const imageBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
await fs.writeFile(imagePath, imageBytes);
- const imageResizer = { process: vi.fn(async (inputPath: string) => inputPath) };
+ const imageResizer = {
+ process: vi.fn(async (inputPath: string) => inputPath),
+ validate: vi.fn(async () => true),
+ };
const content: UserMessage['content'] = [
{ type: 'text', text: 'Inspect these' },
{ type: 'file', path: 'E:\\repo\\large.txt', mimeType: 'text/plain' },
@@ -52,7 +55,10 @@ describe('Claude Code SDK input', () => {
const resizedPath = path.join(tempDir, 'large.webp');
const resizedBytes = Buffer.from('RIFF0000WEBP', 'ascii');
await fs.writeFile(resizedPath, resizedBytes);
- const imageResizer = { process: vi.fn(async () => resizedPath) };
+ const imageResizer = {
+ process: vi.fn(async () => resizedPath),
+ validate: vi.fn(async () => true),
+ };
const content: UserMessage['content'] = [
{ type: 'image', path: sourcePath, mimeType: 'image/png' },
{ type: 'text', text: 'Read the image' },
@@ -77,7 +83,10 @@ describe('Claude Code SDK input', () => {
const imagePath = path.join(tempDir, 'misleading.png');
const imageBytes = Buffer.from([0xff, 0xd8, 0xff, 0xe0]);
await fs.writeFile(imagePath, imageBytes);
- const imageResizer = { process: vi.fn(async () => imagePath) };
+ const imageResizer = {
+ process: vi.fn(async () => imagePath),
+ validate: vi.fn(async () => true),
+ };
const content: UserMessage['content'] = [
{ type: 'image', path: imagePath, mimeType: 'image/webp' },
{ type: 'text', text: 'Inspect this' },
@@ -99,7 +108,10 @@ describe('Claude Code SDK input', () => {
it('falls back to a quoted path when the final image cannot be read', async () => {
const tempDir = await createTempDir();
const missingPath = path.join(tempDir, 'missing.png');
- const imageResizer = { process: vi.fn(async () => missingPath) };
+ const imageResizer = {
+ process: vi.fn(async () => missingPath),
+ validate: vi.fn(async () => true),
+ };
const content: UserMessage['content'] = [
{ type: 'image', path: missingPath, mimeType: 'image/png' },
{ type: 'text', text: 'Inspect this' },
@@ -116,7 +128,10 @@ describe('Claude Code SDK input', () => {
const imageBytes = Buffer.alloc(Math.floor((5 * 1024 * 1024) / 4) * 3 + 1);
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(imageBytes);
await fs.writeFile(imagePath, imageBytes);
- const imageResizer = { process: vi.fn(async () => imagePath) };
+ const imageResizer = {
+ process: vi.fn(async () => imagePath),
+ validate: vi.fn(async () => true),
+ };
const content: UserMessage['content'] = [
{ type: 'image', path: imagePath, mimeType: 'image/png' },
{ type: 'text', text: 'Inspect this' },
@@ -133,7 +148,10 @@ describe('Claude Code SDK input', () => {
const imageBytes = Buffer.alloc(Math.floor((5 * 1024 * 1024) / 4) * 3);
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(imageBytes);
await fs.writeFile(imagePath, imageBytes);
- const imageResizer = { process: vi.fn(async () => imagePath) };
+ const imageResizer = {
+ process: vi.fn(async () => imagePath),
+ validate: vi.fn(async () => true),
+ };
const content: UserMessage['content'] = [
{ type: 'image', path: imagePath, mimeType: 'image/png' },
];
@@ -159,7 +177,10 @@ describe('Claude Code SDK input', () => {
imagePath,
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
);
- const imageResizer = { process: vi.fn(async () => imagePath) };
+ const imageResizer = {
+ process: vi.fn(async () => imagePath),
+ validate: vi.fn(async () => true),
+ };
const content: UserMessage['content'] = [
{ type: 'image', path: imagePath, mimeType: 'image/png' },
{ type: 'text', text: 'Inspect this' },
diff --git a/apps/desktop/src/renderer/__tests__/messageAttachmentPayload.test.ts b/apps/desktop/src/renderer/__tests__/messageAttachmentPayload.test.ts
index df580710d6..b39d0e5fdc 100644
--- a/apps/desktop/src/renderer/__tests__/messageAttachmentPayload.test.ts
+++ b/apps/desktop/src/renderer/__tests__/messageAttachmentPayload.test.ts
@@ -49,6 +49,7 @@ describe('messageAttachmentPayload', () => {
path: 'clipboard://paste-1',
url: 'xdt-image://session/shot.png',
originalName: 'original.png',
+ pathOrigin: 'desktop-host',
}),
]);
expect(payload.imageAttachments).toEqual([
diff --git a/apps/desktop/src/renderer/lib/fileTypes.ts b/apps/desktop/src/renderer/lib/fileTypes.ts
index e37c0cbe98..3278c34b65 100644
--- a/apps/desktop/src/renderer/lib/fileTypes.ts
+++ b/apps/desktop/src/renderer/lib/fileTypes.ts
@@ -142,6 +142,8 @@ export interface SerializedAttachedFile {
size: number;
category: FileCategory;
mimeType: string;
+ /** Image source was selected or pasted on the Desktop host. */
+ pathOrigin?: 'desktop-host';
url?: string;
originalName?: string;
/**
diff --git a/apps/desktop/src/renderer/lib/messageAttachmentPayload.ts b/apps/desktop/src/renderer/lib/messageAttachmentPayload.ts
index f1ba8785c6..cf83dd898f 100644
--- a/apps/desktop/src/renderer/lib/messageAttachmentPayload.ts
+++ b/apps/desktop/src/renderer/lib/messageAttachmentPayload.ts
@@ -123,7 +123,11 @@ function buildImageAttachment(file: AttachedFile): RenderImageAttachment | null
export function buildUserMessageAttachmentPayload(
files?: readonly AttachedFile[],
): UserMessageAttachmentPayload {
- const serializedFiles = serializeAttachedFiles(files);
+ const serializedFiles = serializeAttachedFiles(files)?.map((file) => (
+ getAgentInputAttachmentBlockType(file.category, file.ext) === 'image'
+ ? { ...file, pathOrigin: 'desktop-host' as const }
+ : file
+ ));
const imageAttachments = files
?.map(buildImageAttachment)
.filter((image): image is RenderImageAttachment => image !== null);
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index fe099af5c4..263ff89e96 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -30,6 +30,8 @@ export interface AgentInputSerializedFile {
size: number;
category: AgentInputFileCategory;
mimeType: string;
+ /** Renderer-owned image path that originated on this Desktop host. */
+ pathOrigin?: 'desktop-host';
url?: string;
originalName?: string;
base64?: string;
@@ -933,12 +935,15 @@ export function buildMakerUserMessage(
let hasAnnotatedImage = false;
for (const f of queued.files ?? []) {
const type = getAgentInputAttachmentBlockType(f.category, f.ext);
+ const pathOrigin = type === 'image' && f.pathOrigin === 'desktop-host'
+ ? { pathOrigin: f.pathOrigin }
+ : {};
if (f.url) {
- blocks.push({ type, path: f.url, mimeType: f.mimeType });
+ blocks.push({ type, path: f.url, mimeType: f.mimeType, ...pathOrigin });
} else if (f.path && !f.path.startsWith('clipboard://')) {
- blocks.push({ type, path: f.path, mimeType: f.mimeType });
+ blocks.push({ type, path: f.path, mimeType: f.mimeType, ...pathOrigin });
} else if (f.base64) {
- blocks.push({ type, base64: f.base64, mimeType: f.mimeType });
+ blocks.push({ type, base64: f.base64, mimeType: f.mimeType, ...pathOrigin });
} else {
continue;
}
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
index 3a664a6ada..853338f617 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
@@ -36,6 +36,7 @@ const asyncQueueMock = vi.hoisted(() => ({
}));
const imageResizerMock = vi.hoisted(() => ({
process: vi.fn(async (p: string) => p),
+ validate: vi.fn(async () => true),
}));
vi.mock('@anthropic-ai/claude-agent-sdk', () => ({
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/invalid-resume-recovery.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/invalid-resume-recovery.test.ts
index 94ed177f81..aecc77437d 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/invalid-resume-recovery.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/invalid-resume-recovery.test.ts
@@ -15,6 +15,7 @@ const sdkMock = vi.hoisted(() => ({ query: vi.fn(), forkSession: vi.fn() }));
const imageResizerMock = vi.hoisted(() => ({
process: vi.fn(async (p: string) => p),
+ validate: vi.fn(async () => true),
}));
vi.mock('@anthropic-ai/claude-agent-sdk', () => ({
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
index fce16f76bb..6c85a1441c 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/plan-mode.test.ts
@@ -200,7 +200,7 @@ describe('ClaudeCodeAgent plan mode', () => {
await fs.writeFile(markdownPath, '# Launch\nBudget: 100 vs 80 + 50');
await fs.writeFile(pdfPath, '%PDF-1.4\n% review transport fixture');
const imageBase64 =
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC';
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
await fs.writeFile(
imagePath,
Buffer.from(imageBase64, 'base64'),
@@ -507,6 +507,28 @@ describe('ClaudeCodeAgent plan mode', () => {
await handle.close();
});
+ it('keeps a truncated image as a path reference instead of native inline data', async () => {
+ const { handle, queryPrompt, workingDir } = await startPlanSession(false);
+ const imagePath = path.join(workingDir, 'truncated.png');
+ await fs.writeFile(
+ imagePath,
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ );
+ const nextInput = queryPrompt[Symbol.asyncIterator]().next();
+
+ await handle.send({
+ type: 'user',
+ content: [
+ { type: 'text', text: 'Inspect this image.' },
+ { type: 'image', path: imagePath, mimeType: 'image/png' },
+ ],
+ });
+
+ const sdkInput = (await nextInput).value;
+ expect(sdkInput?.message?.content).toBe(`@"${imagePath}" Inspect this image.`);
+ await handle.close();
+ });
+
it('forwards SSH image paths without reading a same-named desktop file', async () => {
const configDir = await makeTempDir();
process.env.CLAUDE_CONFIG_DIR = configDir;
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts
index 33aa0577b1..d89e8a6865 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts
@@ -32,6 +32,7 @@ const sdkMock = vi.hoisted(() => ({
const imageResizerMock = vi.hoisted(() => ({
process: vi.fn(async (p: string) => p),
+ validate: vi.fn(async () => true),
}));
vi.mock('@anthropic-ai/claude-agent-sdk', () => ({
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index df9886b765..0cfd76580d 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -418,6 +418,7 @@ type ClaudeSdkContentBlock =
interface ClaudeInputImageResizer {
process(absPath: string): Promise<string>;
+ validate(absPath: string): Promise<boolean>;
}
const CLAUDE_INLINE_IMAGE_MAX_ENCODED_BYTES = 5 * 1024 * 1024;
@@ -510,10 +511,13 @@ export async function toClaudeSdkContent(
if (block.type === 'image' && readImagePathsLocally) {
imageBlockPromises.set(
idx,
- imageResizer.process(block.path).then(async (finalPath) => ({
- block: await toClaudeImageBlock(finalPath),
- finalPath,
- })),
+ imageResizer.process(block.path).then(async (finalPath) => {
+ const isValidImage = await imageResizer.validate(finalPath);
+ return {
+ block: isValidImage ? await toClaudeImageBlock(finalPath) : null,
+ finalPath,
+ };
+ }),
);
}
});
diff --git a/packages/maker-core/src/agents/shared/image-resizer.ts b/packages/maker-core/src/agents/shared/image-resizer.ts
index 7e704e5d9e..8c07e8e290 100644
--- a/packages/maker-core/src/agents/shared/image-resizer.ts
+++ b/packages/maker-core/src/agents/shared/image-resizer.ts
@@ -83,6 +83,8 @@ const DEFAULTS = {
cacheVersion: 'v1',
};
+const VALIDATION_MAX_INPUT_PIXELS = 100_000_000;
+
interface QueueTask {
run: () => Promise<void>;
}
@@ -180,6 +182,54 @@ export class ImageResizer {
return task;
}
+ /**
+ * Fully decode an image before it is embedded as model-native base64 input.
+ * Magic bytes identify a container but cannot prove that the payload is complete.
+ * Missing sharp, decode errors, and timeouts all fail closed so callers can keep
+ * the existing path-reference fallback.
+ */
+ async validate(absPath: string): Promise<boolean> {
+ if (!absPath || typeof absPath !== 'string') return false;
+ const sharp = loadSharp();
+ if (!sharp) return false;
+
+ return this.acquireSlot(async () => {
+ const work = sharp(absPath, {
+ failOn: 'error',
+ limitInputPixels: VALIDATION_MAX_INPUT_PIXELS,
+ sequentialRead: true,
+ })
+ .rotate()
+ .resize({
+ width: this.cfg.maxEdgePx,
+ height: this.cfg.maxEdgePx,
+ fit: 'inside',
+ withoutEnlargement: true,
+ })
+ .toBuffer()
+ .then(() => true)
+ .catch((error) => {
+ this.cfg.logger?.warn('image-resizer: image validation failed', {
+ absPath,
+ error: String(error),
+ });
+ return false;
+ });
+ const timeout = new Promise<'timeout'>((resolve) => {
+ setTimeout(() => resolve('timeout'), this.cfg.timeoutMs).unref?.();
+ });
+ const result = await Promise.race([work, timeout]);
+ if (result === 'timeout') {
+ this.cfg.logger?.warn('image-resizer: image validation timeout', {
+ absPath,
+ timeoutMs: this.cfg.timeoutMs,
+ });
+ return false;
+ }
+ return result;
+ });
+ }
+
/** 内部: 跑实际的 resize, 含并发闸门 + 超时 + 错误降级。 */
private async runResize(
absPath: string,