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): 保留图片来源并绑定校验字节

DavidShen64113034ed46
diff --git a/apps/desktop/src/main/__tests__/claudeInput.test.ts b/apps/desktop/src/main/__tests__/claudeInput.test.ts
index c968907b51..36bfdb4007 100644
--- a/apps/desktop/src/main/__tests__/claudeInput.test.ts
+++ b/apps/desktop/src/main/__tests__/claudeInput.test.ts
@@ -27,7 +27,7 @@ describe('Claude Code SDK input', () => {
await fs.writeFile(imagePath, imageBytes);
const imageResizer = {
process: vi.fn(async (inputPath: string) => inputPath),
- validate: vi.fn(async () => true),
+ validateBuffer: vi.fn(async () => true),
};
const content: UserMessage['content'] = [
{ type: 'text', text: 'Inspect these' },
@@ -57,7 +57,7 @@ describe('Claude Code SDK input', () => {
await fs.writeFile(resizedPath, resizedBytes);
const imageResizer = {
process: vi.fn(async () => resizedPath),
- validate: vi.fn(async () => true),
+ validateBuffer: vi.fn(async () => true),
};
const content: UserMessage['content'] = [
{ type: 'image', path: sourcePath, mimeType: 'image/png' },
@@ -85,7 +85,7 @@ describe('Claude Code SDK input', () => {
await fs.writeFile(imagePath, imageBytes);
const imageResizer = {
process: vi.fn(async () => imagePath),
- validate: vi.fn(async () => true),
+ validateBuffer: vi.fn(async () => true),
};
const content: UserMessage['content'] = [
{ type: 'image', path: imagePath, mimeType: 'image/webp' },
@@ -110,7 +110,7 @@ describe('Claude Code SDK input', () => {
const missingPath = path.join(tempDir, 'missing.png');
const imageResizer = {
process: vi.fn(async () => missingPath),
- validate: vi.fn(async () => true),
+ validateBuffer: vi.fn(async () => true),
};
const content: UserMessage['content'] = [
{ type: 'image', path: missingPath, mimeType: 'image/png' },
@@ -130,7 +130,7 @@ describe('Claude Code SDK input', () => {
await fs.writeFile(imagePath, imageBytes);
const imageResizer = {
process: vi.fn(async () => imagePath),
- validate: vi.fn(async () => true),
+ validateBuffer: vi.fn(async () => true),
};
const content: UserMessage['content'] = [
{ type: 'image', path: imagePath, mimeType: 'image/png' },
@@ -150,7 +150,7 @@ describe('Claude Code SDK input', () => {
await fs.writeFile(imagePath, imageBytes);
const imageResizer = {
process: vi.fn(async () => imagePath),
- validate: vi.fn(async () => true),
+ validateBuffer: vi.fn(async () => true),
};
const content: UserMessage['content'] = [
{ type: 'image', path: imagePath, mimeType: 'image/png' },
@@ -179,7 +179,7 @@ describe('Claude Code SDK input', () => {
);
const imageResizer = {
process: vi.fn(async () => imagePath),
- validate: vi.fn(async () => true),
+ validateBuffer: vi.fn(async () => true),
};
const content: UserMessage['content'] = [
{ type: 'image', path: imagePath, mimeType: 'image/png' },
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
index 8c3e5db797..f508410704 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
@@ -35,6 +35,7 @@ import {
cleanupSessionTempAttachments,
configureTempAttachmentOwner,
materializeDirectSendOssAttachments,
+ materializeQueuedOssAttachmentsDeferred,
normalizeUserMessage,
} from '../normalizeAttachments.js';
import * as cindyMediaBlobStore from '../../cindy-media/blobStore.js';
@@ -110,6 +111,115 @@ describe('inline attachment temporary files', () => {
expect(removeRemote).toHaveBeenCalledWith('cindy/device-link/user/image.png');
});
+ it('marks queued OSS images as desktop-host attachments after materialization', async () => {
+ const hash = 'b'.repeat(64);
+ const mediaUrl = `cindy-media://blobs/${hash}.png`;
+ const absPath = path.join(tempRoot.value, 'queued-materialized.png');
+ vi.mocked(downloadToFile).mockImplementationOnce(async (_ossKey, destination) => {
+ await fs.writeFile(destination, Buffer.from([0x89, 0x50, 0x4e, 0x47]));
+ });
+ vi.mocked(cindyMediaBlobStore.supportedMime).mockReturnValue(true);
+ vi.mocked(cindyMediaBlobStore.resolveSafe).mockReturnValue({
+ absPath,
+ mimeType: 'image/png',
+ hash,
+ });
+ vi.mocked(ingestMedia).mockResolvedValueOnce({
+ hash,
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 4,
+ url: mediaUrl,
+ deduplicated: false,
+ refIds: ['ref-2'],
+ });
+ const ossRef = buildAttachmentOssRef({
+ ossKey: 'cindy/device-link/user/queued-image.png',
+ mimeType: 'image/png',
+ originalName: 'queued-image.png',
+ });
+
+ const materialized = await materializeQueuedOssAttachmentsDeferred(
+ 'queued-oss-image',
+ {
+ clientId: 'queued-image-1',
+ files: [{
+ category: 'image',
+ ext: '.png',
+ path: ossRef,
+ mimeType: 'image/png',
+ }],
+ },
+ );
+
+ expect(materialized.item).toEqual({
+ clientId: 'queued-image-1',
+ files: [{
+ category: 'image',
+ ext: '.png',
+ path: absPath,
+ url: mediaUrl,
+ mimeType: 'image/png',
+ pathOrigin: 'desktop-host',
+ base64: undefined,
+ }],
+ persistedContent: undefined,
+ });
+ materialized.cleanupAfterAcceptance?.();
+ expect(removeRemote).toHaveBeenCalledWith('cindy/device-link/user/queued-image.png');
+ });
+
+ it('marks queued local images as desktop-host attachments after materialization', async () => {
+ const sourcePath = path.join(tempRoot.value, 'device-link-local.png');
+ await fs.writeFile(sourcePath, Buffer.from([0x89, 0x50, 0x4e, 0x47]));
+ const hash = 'c'.repeat(64);
+ const mediaUrl = `cindy-media://blobs/${hash}.png`;
+ const absPath = path.join(tempRoot.value, 'queued-local-materialized.png');
+ vi.mocked(cindyMediaBlobStore.mimeForExt).mockReturnValue('image/png');
+ vi.mocked(cindyMediaBlobStore.resolveSafe).mockReturnValue({
+ absPath,
+ mimeType: 'image/png',
+ hash,
+ });
+ vi.mocked(ingestMedia).mockResolvedValueOnce({
+ hash,
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 4,
+ url: mediaUrl,
+ deduplicated: false,
+ refIds: ['ref-3'],
+ });
+
+ const materialized = await materializeQueuedOssAttachmentsDeferred(
+ 'queued-local-image',
+ {
+ clientId: 'queued-image-2',
+ files: [{
+ category: 'image',
+ ext: '.png',
+ path: sourcePath,
+ mimeType: 'image/png',
+ }],
+ },
+ );
+
+ expect(materialized.item).toEqual({
+ clientId: 'queued-image-2',
+ files: [{
+ category: 'image',
+ ext: '.png',
+ path: absPath,
+ url: mediaUrl,
+ mimeType: 'image/png',
+ pathOrigin: 'desktop-host',
+ base64: undefined,
+ }],
+ persistedContent: undefined,
+ });
+ expect(downloadToFile).not.toHaveBeenCalled();
+ });
+
it('writes private bytes and removes them even before Maker owns the session', async () => {
const sessionId = 'reviewer-session';
const normalized = await normalizeUserMessage(sessionId, {
diff --git a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
index e426e38af0..303105d41a 100644
--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
@@ -410,7 +410,24 @@ export async function normalizeUserMessage(
// device-link 出方向:被控端入队消息的 OSS 引用一次性物化(files[] + persistedContent 共用下载)
// ───────────────────────────────────────────────────────────────────────────
-type SerializedFileLike = { url?: unknown; path?: unknown; base64?: unknown; mimeType?: unknown };
+type SerializedFileLike = {
+ url?: unknown;
+ path?: unknown;
+ base64?: unknown;
+ mimeType?: unknown;
+ type?: unknown;
+ category?: unknown;
+ ext?: unknown;
+};
+
+function isQueuedImageFile(file: SerializedFileLike): boolean {
+ if (file.type === 'image') return true;
+ return (
+ file.category === 'image'
+ && typeof file.ext === 'string'
+ && file.ext.toLowerCase() !== '.gif'
+ );
+}
/** 该字段是 device-link 出方向附件 OSS 引用串。 */
function isOssRefField(v: unknown): v is string {
@@ -441,6 +458,15 @@ function needsImageMaterialize(v: unknown): v is string {
return isOssRefField(v) || isLocalImagePathField(v);
}
+function queuedFileMaterializeRef(file: SerializedFileLike): string | null {
+ if (isOssRefField(file.url)) return file.url;
+ if (isOssRefField(file.path)) return file.path;
+ if (!isQueuedImageFile(file)) return null;
+ if (isLocalImagePathField(file.url)) return file.url;
+ if (isLocalImagePathField(file.path)) return file.path;
+ return null;
+}
+
/** persistedContent JSON 串里是否含需物化引用(images[].url / files[].path)。解析失败 → 视作无。 */
function persistedContentNeedsMaterialize(json: string): boolean {
try {
@@ -543,15 +569,14 @@ async function materializeQueuedOssAttachmentsInternal(
const files = Array.isArray(it.files) ? it.files : null;
const pcStr = typeof it.persistedContent === 'string' ? it.persistedContent : null;
- const filesHaveOss =
+ const filesNeedMaterialize =
files?.some(
(f) =>
!!f &&
typeof f === 'object' &&
- (isOssRefField((f as SerializedFileLike).url) ||
- isOssRefField((f as SerializedFileLike).path)),
+ queuedFileMaterializeRef(f as SerializedFileLike) !== null,
) ?? false;
- if (!filesHaveOss && !(pcStr && persistedContentNeedsMaterialize(pcStr))) return { item }; // 无需物化 → 原样
+ if (!filesNeedMaterialize && !(pcStr && persistedContentNeedsMaterialize(pcStr))) return { item }; // 无需物化 → 原样
const byRef = new Map<string, MaterializedRef>(); // 引用串 → 物化结果(同串只下载/拷贝+入库一次)
const ossKeys = new Set<string>();
@@ -697,7 +722,7 @@ async function materializeQueuedOssAttachmentsInternal(
continue;
}
const sf = f as SerializedFileLike;
- const refStr = isOssRefField(sf.url) ? sf.url : isOssRefField(sf.path) ? sf.path : null;
+ const refStr = queuedFileMaterializeRef(sf);
if (!refStr) {
out.push(f);
continue;
@@ -706,7 +731,15 @@ async function materializeQueuedOssAttachmentsInternal(
refStr,
typeof sf.mimeType === 'string' ? sf.mimeType : undefined,
);
- out.push(m ? { ...(f as object), url: m.url, path: m.absPath, base64: undefined } : f);
+ out.push(m
+ ? {
+ ...(f as object),
+ url: m.url,
+ path: m.absPath,
+ ...(isQueuedImageFile(sf) ? { pathOrigin: 'desktop-host' as const } : {}),
+ base64: undefined,
+ }
+ : f);
}
nextFiles = out;
}
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 853338f617..8adf87d11d 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,7 +36,7 @@ const asyncQueueMock = vi.hoisted(() => ({
}));
const imageResizerMock = vi.hoisted(() => ({
process: vi.fn(async (p: string) => p),
- validate: vi.fn(async () => true),
+ validateBuffer: 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 aecc77437d..86ea15c3fd 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,7 +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),
+ validateBuffer: 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 de58ed8dca..9d3ded90de 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
@@ -30,7 +30,7 @@ vi.mock('@anthropic-ai/claude-agent-sdk', () => ({
query: sdkMock.query,
}));
-import { ClaudeCodeAgent } from '../index.js';
+import { ClaudeCodeAgent, toClaudeSdkContent } from '../index.js';
const tempDirs: string[] = [];
const originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR;
@@ -187,6 +187,36 @@ afterEach(async () => {
});
describe('ClaudeCodeAgent plan mode', () => {
+ it('encodes the same image bytes that passed validation', async () => {
+ const workingDir = await makeTempDir();
+ const imagePath = path.join(workingDir, 'race.png');
+ const originalBase64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
+ const original = Buffer.from(originalBase64, 'base64');
+ const replacement = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+ await fs.writeFile(imagePath, original);
+ const validateBuffer = vi.fn(async (data: Buffer) => {
+ expect(data).toEqual(original);
+ await fs.writeFile(imagePath, replacement);
+ return true;
+ });
+
+ const content = await toClaudeSdkContent(
+ [{ type: 'image', path: imagePath, mimeType: 'image/png' }],
+ { process: async (input) => input, validateBuffer },
+ );
+
+ expect(content).toEqual([{
+ type: 'image',
+ source: {
+ type: 'base64',
+ media_type: 'image/png',
+ data: originalBase64,
+ },
+ }]);
+ expect(validateBuffer).toHaveBeenCalledOnce();
+ });
+
it('keeps review text, file references, and a native image in one real SDK turn', async () => {
const { handle, queryPrompt, workingDir } = await startPlanSession(
false,
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 d89e8a6865..bc6623b477 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,7 +32,7 @@ const sdkMock = vi.hoisted(() => ({
const imageResizerMock = vi.hoisted(() => ({
process: vi.fn(async (p: string) => p),
- validate: vi.fn(async () => true),
+ validateBuffer: 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 bb7382dcbf..3fd98dd05c 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -418,7 +418,7 @@ type ClaudeSdkContentBlock =
interface ClaudeInputImageResizer {
process(absPath: string): Promise<string>;
- validate(absPath: string): Promise<boolean>;
+ validateBuffer(data: Buffer): Promise<boolean>;
}
const CLAUDE_INLINE_IMAGE_MAX_ENCODED_BYTES = 5 * 1024 * 1024;
@@ -451,7 +451,10 @@ function detectClaudeImageMediaType(data: Buffer): ClaudeImageMediaType | null {
return null;
}
-async function toClaudeImageBlock(imagePath: string): Promise<ClaudeSdkContentBlock | null> {
+async function toClaudeImageBlock(
+ imagePath: string,
+ validateBuffer: (data: Buffer) => Promise<boolean>,
+): Promise<ClaudeSdkContentBlock | null> {
let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
try {
handle = await fs.open(imagePath, 'r');
@@ -470,6 +473,7 @@ async function toClaudeImageBlock(imagePath: string): Promise<ClaudeSdkContentBl
) return null;
const mediaType = detectClaudeImageMediaType(data);
if (!mediaType) return null;
+ if (!(await validateBuffer(data))) return null;
const encodedData = data.toString('base64');
return {
type: 'image',
@@ -512,9 +516,11 @@ export async function toClaudeSdkContent(
imageBlockPromises.set(
idx,
imageResizer.process(block.path).then(async (finalPath) => {
- const isValidImage = await imageResizer.validate(finalPath);
return {
- block: isValidImage ? await toClaudeImageBlock(finalPath) : null,
+ block: await toClaudeImageBlock(
+ finalPath,
+ (data) => imageResizer.validateBuffer(data),
+ ),
finalPath,
};
}),
diff --git a/packages/maker-core/src/agents/shared/image-resizer.ts b/packages/maker-core/src/agents/shared/image-resizer.ts
index 8c07e8e290..b766089a9c 100644
--- a/packages/maker-core/src/agents/shared/image-resizer.ts
+++ b/packages/maker-core/src/agents/shared/image-resizer.ts
@@ -190,11 +190,24 @@ export class ImageResizer {
*/
async validate(absPath: string): Promise<boolean> {
if (!absPath || typeof absPath !== 'string') return false;
+ return this.validateInput(absPath, { absPath });
+ }
+
+ /** Validate the exact bytes a caller is about to embed. */
+ async validateBuffer(data: Buffer): Promise<boolean> {
+ if (!Buffer.isBuffer(data) || data.length === 0) return false;
+ return this.validateInput(data, { bytes: data.length });
+ }
+
+ private async validateInput(
+ input: string | Buffer,
+ logMeta: Record<string, unknown>,
+ ): Promise<boolean> {
const sharp = loadSharp();
if (!sharp) return false;
return this.acquireSlot(async () => {
- const work = sharp(absPath, {
+ const work = sharp(input, {
failOn: 'error',
limitInputPixels: VALIDATION_MAX_INPUT_PIXELS,
sequentialRead: true,
@@ -210,7 +223,7 @@ export class ImageResizer {
.then(() => true)
.catch((error) => {
this.cfg.logger?.warn('image-resizer: image validation failed', {
- absPath,
+ ...logMeta,
error: String(error),
});
return false;
@@ -221,7 +234,7 @@ export class ImageResizer {
const result = await Promise.race([work, timeout]);
if (result === 'timeout') {
this.cfg.logger?.warn('image-resizer: image validation timeout', {
- absPath,
+ ...logMeta,
timeoutMs: this.cfg.timeoutMs,
});
return false;