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): 统一图片附件为原生输入

DavidShen69c15cb7fd0d
diff --git a/apps/desktop/src/main/__tests__/claudeInput.test.ts b/apps/desktop/src/main/__tests__/claudeInput.test.ts
index 0a806cf71b..786881079c 100644
--- a/apps/desktop/src/main/__tests__/claudeInput.test.ts
+++ b/apps/desktop/src/main/__tests__/claudeInput.test.ts
@@ -1,21 +1,103 @@
-import { describe, expect, it } from 'vitest';
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { toClaudeSdkContent } from '../../../../../packages/maker-core/src/agents/claude-code/index';
import type { UserMessage } from '../../../../../packages/maker-core/src/types/common';
-// 注意: toClaudeSdkContent 自 image-resizer 接通后改为 async。image block 的 path
-// 会先经 resizer.process() 透明替换 — 但测试里用的虚拟 path (C:\tmp\shot.png) 在
-// 磁盘上不存在, fs.stat 失败后 resizer 直接返回原 path, 期望值不变。
describe('Claude Code SDK input', () => {
- it('keeps file and image attachments as @path refs instead of inline blocks', async () => {
+ const tempDirs: string[] = [];
+
+ async function createTempDir(): Promise<string> {
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-claude-input-'));
+ tempDirs.push(tempDir);
+ return tempDir;
+ }
+
+ afterEach(async () => {
+ await Promise.all(tempDirs.splice(0).map((tempDir) => fs.rm(tempDir, { recursive: true })));
+ });
+
+ it('inlines an original image while keeping file attachments as path refs', async () => {
+ const tempDir = await createTempDir();
+ const imagePath = path.join(tempDir, 'small.png');
+ const imageBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
+ await fs.writeFile(imagePath, imageBytes);
+ const imageResizer = { process: vi.fn(async (inputPath: string) => inputPath) };
const content: UserMessage['content'] = [
{ type: 'text', text: 'Inspect these' },
{ type: 'file', path: 'E:\\repo\\large.txt', mimeType: 'text/plain' },
- { type: 'image', path: 'C:\\tmp\\shot.png', mimeType: 'image/png' },
+ { type: 'image', path: imagePath, mimeType: 'image/png' },
+ ];
+
+ expect(await toClaudeSdkContent(content, imageResizer)).toEqual([
+ {
+ type: 'image',
+ source: {
+ type: 'base64',
+ media_type: 'image/png',
+ data: imageBytes.toString('base64'),
+ },
+ },
+ { type: 'text', text: '@"E:\\repo\\large.txt" Inspect these' },
+ ]);
+ expect(imageResizer.process).toHaveBeenCalledWith(imagePath);
+ });
+
+ it('uses the resized file format and bytes for the native image block', async () => {
+ const tempDir = await createTempDir();
+ const sourcePath = path.join(tempDir, 'large.png');
+ const resizedPath = path.join(tempDir, 'large.webp');
+ const resizedBytes = Buffer.from([0x52, 0x49, 0x46, 0x46]);
+ await fs.writeFile(resizedPath, resizedBytes);
+ const imageResizer = { process: vi.fn(async () => resizedPath) };
+ const content: UserMessage['content'] = [
+ { type: 'image', path: sourcePath, mimeType: 'image/png' },
+ { type: 'text', text: 'Read the image' },
+ ];
+
+ expect(await toClaudeSdkContent(content, imageResizer)).toEqual([
+ {
+ type: 'image',
+ source: {
+ type: 'base64',
+ media_type: 'image/webp',
+ data: resizedBytes.toString('base64'),
+ },
+ },
+ { type: 'text', text: 'Read the image' },
+ ]);
+ expect(imageResizer.process).toHaveBeenCalledWith(sourcePath);
+ });
+
+ 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 content: UserMessage['content'] = [
+ { type: 'image', path: missingPath, mimeType: 'image/png' },
+ { type: 'text', text: 'Inspect this' },
+ ];
+
+ expect(await toClaudeSdkContent(content, imageResizer)).toBe(
+ `@"${missingPath}" Inspect this`,
+ );
+ });
+
+ it('falls back to a quoted path when the final image is too large to embed', async () => {
+ const tempDir = await createTempDir();
+ const imagePath = path.join(tempDir, 'too-large.png');
+ await fs.writeFile(imagePath, Buffer.alloc(5 * 1024 * 1024 + 1));
+ const imageResizer = { process: vi.fn(async () => imagePath) };
+ const content: UserMessage['content'] = [
+ { type: 'image', path: imagePath, mimeType: 'image/png' },
+ { type: 'text', text: 'Inspect this' },
];
- expect(await toClaudeSdkContent(content)).toBe(
- '@"E:\\repo\\large.txt" @"C:\\tmp\\shot.png" Inspect these',
+ expect(await toClaudeSdkContent(content, imageResizer)).toBe(
+ `@"${imagePath}" Inspect this`,
);
});
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 3a4bd97cd2..3d193d61ea 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
@@ -187,7 +187,7 @@ afterEach(async () => {
});
describe('ClaudeCodeAgent plan mode', () => {
- it('keeps review text, Markdown, PDF, and image references in one real SDK turn', async () => {
+ it('keeps review text, file references, and a native image in one real SDK turn', async () => {
const { handle, queryPrompt, workingDir } = await startPlanSession(
false,
{},
@@ -199,16 +199,14 @@ describe('ClaudeCodeAgent plan mode', () => {
const imagePath = path.join(workingDir, 'poster.png');
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';
await fs.writeFile(
imagePath,
- Buffer.from(
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC',
- 'base64',
- ),
+ Buffer.from(imageBase64, 'base64'),
);
const realMarkdownPath = await fs.realpath(markdownPath);
const realPdfPath = await fs.realpath(pdfPath);
- const realImagePath = await fs.realpath(imagePath);
const nextInput = queryPrompt[Symbol.asyncIterator]().next();
await handle.send({
@@ -222,9 +220,20 @@ describe('ClaudeCodeAgent plan mode', () => {
});
const sdkInput = (await nextInput).value;
- expect(sdkInput?.message?.content).toBe(
- `@"${realMarkdownPath}" @"${realPdfPath}" @"${realImagePath}" Review the Markdown, PDF, and image evidence.`,
- );
+ expect(sdkInput?.message?.content).toEqual([
+ {
+ type: 'image',
+ source: {
+ type: 'base64',
+ media_type: 'image/png',
+ data: imageBase64,
+ },
+ },
+ {
+ type: 'text',
+ text: `@"${realMarkdownPath}" @"${realPdfPath}" Review the Markdown, PDF, and image evidence.`,
+ },
+ ]);
await handle.close();
});
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 1dec247916..eda4cec5a7 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -403,19 +403,92 @@ function hasMentionText(existingText: string, block: { path: string; kind?: 'fil
return existingText.includes(rawMentionText(block)) || existingText.includes(quotedMentionText(block));
}
+type ClaudeImageMediaType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
+
+type ClaudeSdkContentBlock =
+ | {
+ type: 'image';
+ source: {
+ type: 'base64';
+ media_type: ClaudeImageMediaType;
+ data: string;
+ };
+ }
+ | { type: 'text'; text: string };
+
+interface ClaudeInputImageResizer {
+ process(absPath: string): Promise<string>;
+}
+
+const CLAUDE_INLINE_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
+
+function resolveClaudeImageMediaType(
+ imagePath: string,
+ mimeType?: string,
+): ClaudeImageMediaType | null {
+ const extensionMediaType: Record<string, ClaudeImageMediaType> = {
+ '.gif': 'image/gif',
+ '.jfif': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.jpg': 'image/jpeg',
+ '.png': 'image/png',
+ '.webp': 'image/webp',
+ };
+ const fromExtension = extensionMediaType[path.extname(imagePath).toLowerCase()];
+ if (fromExtension) return fromExtension;
+
+ switch (mimeType?.toLowerCase()) {
+ case 'image/gif':
+ case 'image/jpeg':
+ case 'image/png':
+ case 'image/webp':
+ return mimeType.toLowerCase() as ClaudeImageMediaType;
+ case 'image/jpg':
+ return 'image/jpeg';
+ default:
+ return null;
+ }
+}
+
+async function toClaudeImageBlock(
+ imagePath: string,
+ mimeType?: string,
+): Promise<ClaudeSdkContentBlock | null> {
+ const mediaType = resolveClaudeImageMediaType(imagePath, mimeType);
+ if (!mediaType) return null;
+
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
+ try {
+ handle = await fs.open(imagePath, 'r');
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size <= 0 || stat.size > CLAUDE_INLINE_IMAGE_MAX_BYTES) {
+ return null;
+ }
+ const data = await handle.readFile();
+ if (data.length === 0 || data.length > CLAUDE_INLINE_IMAGE_MAX_BYTES) return null;
+ return {
+ type: 'image',
+ source: {
+ type: 'base64',
+ media_type: mediaType,
+ data: data.toString('base64'),
+ },
+ };
+ } catch {
+ return null;
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
+}
+
/**
* 把 maker-core 的 UserMessage content 装配成 Claude SDK 接受的形式。
- *
- * Async 而非 sync —— image block 的 absPath 会先经过 image-resizer 透明替换为
- * 缩好的缓存副本路径(命中走缓存近乎 0ms, miss 后台 sharp 处理 ~200-500ms),
- * 再以 @"resizedAbsPath" 形态注入到 prefix。Claude SDK 后续读 mention 引用的
- * 就是缩好的文件, 显著节省 vision token。
- *
- * 失败 (sharp 不可用 / 文件不存在 / GIF / 超时) 安全降级回原 path, 不阻塞 send。
+ * 图片按需压缩后统一发送为原生 image block;无法安全内联时回退为原有路径引用。
*/
export async function toClaudeSdkContent(
content: UserMessage['content'],
-): Promise<string | Array<{ type: string; [k: string]: unknown }>> {
+ imageResizer: ClaudeInputImageResizer = getDefaultImageResizer(),
+): Promise<string | ClaudeSdkContentBlock[]> {
if (typeof content === 'string') return content;
const textParts = content
@@ -424,18 +497,27 @@ export async function toClaudeSdkContent(
const existingText = textParts.join('\n');
const refs: string[] = [];
- // 先把所有 image block 的 path 收集出来批量 resize (并发由 resizer 内部 semaphore 控)。
- // 同 turn 多张图能并发处理, 不需要在这里串行 await。
- const resizer = getDefaultImageResizer();
- const imagePathPromises = new Map<number, Promise<string>>();
+ const imageBlockPromises = new Map<
+ number,
+ Promise<{ block: ClaudeSdkContentBlock | null; finalPath: string }>
+ >();
content.forEach((block, idx) => {
if (block.type === 'image') {
- imagePathPromises.set(idx, resizer.process(block.path));
+ imageBlockPromises.set(
+ idx,
+ imageResizer.process(block.path).then(async (finalPath) => ({
+ block: await toClaudeImageBlock(finalPath, block.mimeType),
+ finalPath,
+ })),
+ );
}
});
- const resizedPaths = new Map<number, string>();
- for (const [idx, p] of imagePathPromises) {
- resizedPaths.set(idx, await p);
+ const resolvedImages = new Map<
+ number,
+ { block: ClaudeSdkContentBlock | null; finalPath: string }
+ >();
+ for (const [idx, promise] of imageBlockPromises) {
+ resolvedImages.set(idx, await promise);
}
content.forEach((block, idx) => {
@@ -444,7 +526,9 @@ export async function toClaudeSdkContent(
if (block.type === 'mention') {
mentionBlock = { path: block.path, kind: block.kind };
} else if (block.type === 'image') {
- mentionBlock = { path: resizedPaths.get(idx) ?? block.path, kind: 'file' as const };
+ const resolvedImage = resolvedImages.get(idx);
+ if (resolvedImage?.block) return;
+ mentionBlock = { path: resolvedImage?.finalPath ?? block.path, kind: 'file' as const };
} else {
mentionBlock = { path: block.path, kind: 'file' as const };
}
@@ -455,7 +539,9 @@ export async function toClaudeSdkContent(
const prefix = refs.length > 0 ? `${refs.join(' ')} ` : '';
const text = `${prefix}${textParts.join('\n')}`.trim();
- return text || prefix.trim();
+ const imageBlocks = [...resolvedImages.values()].flatMap(({ block }) => (block ? [block] : []));
+ if (imageBlocks.length === 0) return text || prefix.trim();
+ return text ? [...imageBlocks, { type: 'text', text }] : imageBlocks;
}
function userMessageTextForCapabilityRouting(content: UserMessage['content']): string {
@@ -1303,7 +1389,7 @@ export class ClaudeCodeAgent extends BaseAgent {
// checkpoint snapshot 的 messageId (cli.js:7086382), rewind preview 反查同款 uuid。
type SdkUserInput = {
type: 'user';
- message: { role: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> };
+ message: { role: 'user'; content: string | ClaudeSdkContentBlock[] };
parent_tool_use_id: null;
uuid?: string;
};
@@ -5059,23 +5145,28 @@ export class ClaudeCodeAgent extends BaseAgent {
throw new Error('Claude send cancelled before acceptance');
}
// **Remote attachment guard (MVP)**: 远端 session 走 cc 进程在 SSH host 上跑,
- // 本地图片/文件附件转出来的 `@"<desktop-local-path>"` 引用在远端找不到文件,
+ // 本地文件附件转出来的 `@"<desktop-local-path>"` 引用在远端找不到文件,
// 模型看不见 → silent context loss。完整修法是 upload 文件到远端 (follow-up),
// 这里 MVP 检测到附件就 emit warn event 让用户知道,实际请求里把附件 ref 留着
// (daemon 端 SDK 读不到就跳过, 不会 crash)。
if (opts.remoteHostId && Array.isArray(message.content)) {
- const hasAttachment = message.content.some(
- (b) => b.type === 'image' || b.type === 'file' || b.type === 'mention',
+ const hasFileAttachment = message.content.some(
+ (b) => b.type === 'file' || b.type === 'mention',
);
- if (hasAttachment) {
- log.warn('cc remote: local file/image attachment not accessible on remote session', {
+ const sourceImageCount = message.content.filter((b) => b.type === 'image').length;
+ const inlineImageCount = Array.isArray(content)
+ ? content.filter((b) => b.type === 'image').length
+ : 0;
+ const hasPathBackedImage = sourceImageCount > inlineImageCount;
+ if (hasFileAttachment || hasPathBackedImage) {
+ log.warn('cc remote: local attachment not accessible on remote session', {
sessionId: opts.sessionId,
hostId: opts.remoteHostId,
});
eventQueue.push({
type: 'error',
data: {
- message: '[REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED] Local file/image attachments are not accessible on remote sessions. Paste content directly instead.',
+ message: '[REMOTE_LOCAL_ATTACHMENT_UNSUPPORTED] Local file attachments and images that cannot be embedded are not accessible on remote sessions. Paste content directly instead.',
isTerminal: false,
},
source: 'claude-code',
diff --git a/packages/maker-core/src/agents/shared/image-resizer.ts b/packages/maker-core/src/agents/shared/image-resizer.ts
index 1b3b5296d5..7e704e5d9e 100644
--- a/packages/maker-core/src/agents/shared/image-resizer.ts
+++ b/packages/maker-core/src/agents/shared/image-resizer.ts
@@ -3,8 +3,8 @@
* ---------------------------------------------------------------------------
* Last-mile shrink for images that go INTO the LLM context. UI / IM 仍然显示
* 原图,只在 toClaudeSdkContent / toAppServerInput 这一步把 image-block 的
- * absPath 透明替换为缩好的副本路径,Claude SDK / codex app-server 读到的就是
- * resized 文件,显著节省 vision token。
+ * absPath 透明替换为缩好的副本路径,再由下游转换为模型原生图片输入,
+ * 显著节省 vision token。
*
* 设计要点:
* - 用 sharp (libvips Node binding)。所有 decode/resize/encode 都在 libuv