diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index 2220bda234..adff395cd3 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -1,3 +1,8 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; import type { Options as ClaudeQueryOptions, PermissionMode, @@ -7,8 +12,10 @@ import type { } from "@anthropic-ai/claude-agent-sdk"; import { ApprovalRequestId, ProviderItemId, ThreadId } from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; -import { Effect, Fiber, Random, Stream } from "effect"; +import { Effect, Fiber, Layer, Random, Stream } from "effect"; +import { attachmentRelativePath } from "../../attachmentStore.ts"; +import { ServerConfig } from "../../config.ts"; import { ProviderAdapterValidationError } from "../Errors.ts"; import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts"; import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts"; @@ -93,21 +100,12 @@ class FakeClaudeQuery implements AsyncIterable { } } -interface Harness { - readonly layer: ReturnType; - readonly query: FakeClaudeQuery; - readonly getLastCreateQueryInput: () => - | { - readonly prompt: AsyncIterable; - readonly options: ClaudeQueryOptions; - } - | undefined; -} - function makeHarness(config?: { readonly nativeEventLogPath?: string; readonly nativeEventLogger?: ClaudeAdapterLiveOptions["nativeEventLogger"]; -}): Harness { + readonly cwd?: string; + readonly stateDir?: string; +}) { const query = new FakeClaudeQuery(); let createInput: | { @@ -134,7 +132,15 @@ function makeHarness(config?: { }; return { - layer: makeClaudeAdapterLive(adapterOptions), + layer: makeClaudeAdapterLive(adapterOptions).pipe( + Layer.provideMerge( + ServerConfig.layerTest( + config?.cwd ?? "/tmp/claude-adapter-test", + config?.stateDir ?? "/tmp", + ), + ), + Layer.provideMerge(NodeServices.layer), + ), query, getLastCreateQueryInput: () => createInput, }; @@ -178,6 +184,24 @@ async function readFirstPromptText( return content.text; } +async function readFirstPromptMessage( + input: + | { + readonly prompt: AsyncIterable; + } + | undefined, +): Promise { + const iterator = input?.prompt[Symbol.asyncIterator](); + if (!iterator) { + return undefined; + } + const next = await iterator.next(); + if (next.done) { + return undefined; + } + return next.value; +} + const THREAD_ID = ThreadId.makeUnsafe("thread-claude-1"); const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-claude-resume"); @@ -461,6 +485,70 @@ describe("ClaudeAdapterLive", () => { ); }); + it.effect("embeds image attachments in Claude user messages", () => { + const stateDir = mkdtempSync(path.join(os.tmpdir(), "claude-attachments-")); + const harness = makeHarness({ + cwd: "/tmp/project-claude-attachments", + stateDir, + }); + return Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => + rmSync(stateDir, { + recursive: true, + force: true, + }), + ), + ); + + const adapter = yield* ClaudeAdapter; + + const attachment = { + type: "image" as const, + id: "thread-claude-attachment-12345678-1234-1234-1234-123456789abc", + name: "diagram.png", + mimeType: "image/png", + sizeBytes: 4, + }; + const attachmentPath = path.join(stateDir, "attachments", attachmentRelativePath(attachment)); + mkdirSync(path.dirname(attachmentPath), { recursive: true }); + writeFileSync(attachmentPath, Uint8Array.from([1, 2, 3, 4])); + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "What's in this image?", + attachments: [attachment], + }); + + const createInput = harness.getLastCreateQueryInput(); + const promptMessage = yield* Effect.promise(() => readFirstPromptMessage(createInput)); + assert.isDefined(promptMessage); + assert.deepEqual(promptMessage?.message.content, [ + { + type: "text", + text: "What's in this image?", + }, + { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "AQIDBA==", + }, + }, + ]); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + it.effect("maps Claude stream/runtime messages to canonical provider runtime events", () => { const harness = makeHarness(); return Effect.gen(function* () { diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 4af2b940ec..e080894921 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -46,8 +46,21 @@ import { supportsClaudeThinkingToggle, supportsClaudeUltrathinkKeyword, } from "@t3tools/shared/model"; -import { Cause, DateTime, Deferred, Effect, Layer, Queue, Random, Ref, Stream } from "effect"; +import { + Cause, + DateTime, + Deferred, + Effect, + FileSystem, + Layer, + Queue, + Random, + Ref, + Stream, +} from "effect"; +import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import { ServerConfig } from "../../config.ts"; import { ProviderAdapterProcessError, ProviderAdapterRequestError, @@ -363,21 +376,14 @@ function titleForTool(itemType: CanonicalItemType): string { } } -function buildUserMessage(input: ProviderSendTurnInput): SDKUserMessage { - const fragments: string[] = []; - - if (input.input && input.input.trim().length > 0) { - fragments.push(input.input.trim()); - } - - for (const attachment of input.attachments ?? []) { - if (attachment.type === "image") { - fragments.push( - `Attached image: ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes).`, - ); - } - } +const SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = new Set([ + "image/gif", + "image/jpeg", + "image/png", + "image/webp", +]); +function buildPromptText(input: ProviderSendTurnInput): string { const requestedEffort = resolveReasoningEffortForProvider( "claudeAgent", input.modelOptions?.claudeAgent?.effort ?? null, @@ -389,19 +395,101 @@ function buildUserMessage(input: ProviderSendTurnInput): SDKUserMessage { : requestedEffort && supportedEffortOptions.includes(requestedEffort) ? requestedEffort : null; - const text = applyClaudePromptEffortPrefix(fragments.join("\n\n"), promptEffort); + return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort); +} +function buildUserMessage(input: { + readonly sdkContent: Array>; +}): SDKUserMessage { return { type: "user", session_id: "", parent_tool_use_id: null, message: { role: "user", - content: [{ type: "text", text }], + content: input.sdkContent, }, } as SDKUserMessage; } +function buildClaudeImageContentBlock(input: { + readonly mimeType: string; + readonly bytes: Uint8Array; +}): Record { + return { + type: "image", + source: { + type: "base64", + media_type: input.mimeType, + data: Buffer.from(input.bytes).toString("base64"), + }, + }; +} + +function buildUserMessageEffect( + input: ProviderSendTurnInput, + dependencies: { + readonly fileSystem: FileSystem.FileSystem; + readonly stateDir: string; + }, +): Effect.Effect { + return Effect.gen(function* () { + const text = buildPromptText(input); + const sdkContent: Array> = []; + + if (text.length > 0) { + sdkContent.push({ type: "text", text }); + } + + for (const attachment of input.attachments ?? []) { + if (attachment.type !== "image") { + continue; + } + + if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`, + }); + } + + const attachmentPath = resolveAttachmentPath({ + stateDir: dependencies.stateDir, + attachment, + }); + if (!attachmentPath) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: `Invalid attachment id '${attachment.id}'.`, + }); + } + + const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: toMessage(cause, "Failed to read attachment file."), + cause, + }), + ), + ); + + sdkContent.push( + buildClaudeImageContentBlock({ + mimeType: attachment.mimeType, + bytes, + }), + ); + } + + return buildUserMessage({ sdkContent }); + }); +} + function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus { if (result.subtype === "success") { return "completed"; @@ -699,6 +787,8 @@ function sdkNativeItemId(message: SDKMessage): string | undefined { function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const serverConfig = yield* ServerConfig; const nativeEventLogger = options?.nativeEventLogger ?? (options?.nativeEventLogPath !== undefined @@ -2571,7 +2661,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { providerRefs: {}, }); - const message = buildUserMessage(input); + const message = yield* buildUserMessageEffect(input, { + fileSystem, + stateDir: serverConfig.stateDir, + }); yield* Queue.offer(context.promptQueue, { type: "message",