TypeScript
fix(opencode): send pasted images with turns and steers (#16145)
Nikita Koynova1e391744933
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.tsindex 6a56b55400a..6a9f2ffbd04 100644--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts@@ -1,6 +1,11 @@+import * as NodeURL from "node:url";import * as NodeCrypto from "@effect/platform-node/NodeCrypto";+import * as NodeServices from "@effect/platform-node/NodeServices";import { assert, it } from "@effect/vitest";import {+ ChatAttachmentId,+ ChatFileAttachment,+ ChatImageAttachment,CheckpointId,EnvironmentId,MessageId,@@ -23,6 +28,7 @@ import * as DateTime from "effect/DateTime";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Logger from "effect/Logger";import * as Option from "effect/Option";@@ -43,6 +49,7 @@ import {OPENCODE_PROVIDER,t3McpServerName,} from "@t3tools/provider-opencode/testing";+import { resolveAttachmentPath } from "../../attachmentStore.ts";import { openCode2ReplayRuntime } from "./OpenCode2AdapterV2.testkit.ts";import {makeProviderReplayGate,@@ -305,6 +312,9 @@ const resumed = (readonly external?: boolean;readonly supervised?: boolean;readonly replayGate?: ProviderReplayGate;+ readonly attachmentsDir?: string;+ readonly fileSystem?: FileSystem.FileSystem;+ readonly onPrompt?: (input: unknown) => void;},) =>Effect.gen(function* () {@@ -325,8 +335,13 @@ const resumed = (...entries,]),{+ ...(options?.fileSystem === undefined ? {} : { fileSystem: options.fileSystem }),+ ...(options?.onPrompt === undefined ? {} : { onPrompt: options.onPrompt }),...(options?.external === undefined ? {} : { external: options.external }),...(options?.replayGate === undefined ? {} : { replayGate: options.replayGate }),+ ...(options?.attachmentsDir === undefined+ ? {}+ : { attachmentsDir: options.attachmentsDir }),},);const thread = yield* runtime.resumeThread({@@ -3377,6 +3392,257 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {}).pipe(Effect.provide(NodeCrypto.layer)),);+ it.effect.each([+ {+ external: false,+ name: "sends only existing supported images as turn and steer prompt files with path text",+ },+ {+ external: true,+ name: "keeps turn and steer attachment paths without local files for external servers",+ },+ ])("$name", ({ external }) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3 oc2 #images-",+ });+ const image = (id: string, name: string, mimeType = "image/png") =>+ ChatImageAttachment.make({+ type: "image",+ id: ChatAttachmentId.make(`thread-opencode2-adapter-${id}-1234-1234-1234-123456789abc`),+ name,+ mimeType,+ sizeBytes: 4,+ });+ const screenshot = image("12345678", "screen shot.png");+ const chart = image("abcdefab", "chart.webp", "image/webp");+ const missing = image("23456789", "missing.png");+ const unsupported = image("34567890", "diagram.svg", "image/svg+xml");+ const document = ChatFileAttachment.make({+ type: "file",+ id: ChatAttachmentId.make("thread-opencode2-adapter-45678901-1234-1234-1234-123456789abc"),+ name: "requirements.pdf",+ mimeType: "application/pdf",+ sizeBytes: 4,+ });+ for (const attachment of [screenshot, chart, unsupported, document]) {+ yield* fileSystem.writeFileString(+ resolveAttachmentPath({ attachmentsDir, attachment })!,+ "data",+ );+ }+ const prompts: Array<unknown> = [];+ const steerId = "msg_recorded_steer_image";+ const { runtime, thread } = yield* resumed(+ [+ out("session.prompt", { sessionID: SESSION, text: "<any>" }),+ promptAccepted,+ event("session.execution.started", { sessionID: SESSION }),+ out("session.prompt", { sessionID: SESSION, id: steerId, delivery: "steer" }),+ replyData("session.prompt", {+ id: steerId,+ sessionID: SESSION,+ time: { created: 1790656601500 },+ type: "user",+ payload: { text: "And this one?" },+ delivery: "steer",+ }),+ event("session.inbox.delivered", { sessionID: SESSION, inboxID: steerId }),+ event("session.execution.succeeded", { sessionID: SESSION }),+ ],+ { attachmentsDir, external, onPrompt: (input) => prompts.push(input) },+ );+ const ids = yield* IdAllocator.IdAllocatorV2;+ const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);+ const input = turnInput(thread);+ yield* runtime.startTurn({+ ...input,+ message: {+ ...input.message,+ text: "What is in this image?",+ attachments: [screenshot, missing, unsupported, document],+ },+ });+ yield* runtime.steerTurn({+ threadId,+ runId: input.runId,+ providerThread: thread,+ providerTurnId: ids.derive.providerTurn({+ driver: OPENCODE_PROVIDER,+ nativeTurnId: `${SESSION}:attempt:attempt:opencode2-adapter`,+ }),+ message: {+ ...input.message,+ messageId: MessageId.make("message:opencode2-adapter:steer"),+ text: "And this one?",+ attachments: [chart, missing, unsupported, document],+ },+ });+ assert.equal((yield* Fiber.join(terminal))?.status, "completed");+ assert.equal(prompts.length, 2);+ for (const [index, attachment] of [screenshot, chart].entries()) {+ const path = resolveAttachmentPath({ attachmentsDir, attachment })!;+ assert.deepInclude(prompts[index], {+ text: [+ index === 0 ? "What is in this image?" : "And this one?",+ `[Attached image "${attachment.name}" is saved at: ${path}]`,+ `[Attached image "missing.png" is saved at: ${attachmentsDir}/${missing.id}.png]`,+ `[Attached image "diagram.svg" is saved at: ${attachmentsDir}/${unsupported.id}.svg]`,+ `[Attached file "requirements.pdf" is saved at: ${attachmentsDir}/${document.id}.pdf]`,+ ].join("\n\n"),+ });+ if (external) {+ assert.notProperty(prompts[index], "files");+ } else {+ assert.deepInclude(prompts[index], {+ files: [+ {+ uri: NodeURL.pathToFileURL(path).href,+ name: attachment.name,+ },+ ],+ });+ }+ }+ }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(IdAllocator.layer, NodeServices.layer))),+ );++ it.effect.each([false, true])(+ "rejects an image steer stopped during attachment resolution (held end: %s)",+ (heldEnd) =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-oc2-stopped-image-",+ });+ const image = ChatImageAttachment.make({+ type: "image",+ id: ChatAttachmentId.make(+ "thread-opencode2-adapter-12345678-1234-1234-1234-123456789abc",+ ),+ name: "screen.png",+ mimeType: "image/png",+ sizeBytes: 4,+ });+ const path = resolveAttachmentPath({ attachmentsDir, attachment: image })!;+ yield* fileSystem.writeFileString(path, "data");+ const resolving = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ const gate = makeProviderReplayGate(["execution-end", "interrupt-reply"]);+ const executionEnded = yield* Deferred.make<void>();+ const prompts: Array<unknown> = [];+ const { runtime, thread } = yield* resumed(+ [+ out("session.prompt", { sessionID: SESSION, text: "<any>" }),+ promptAccepted,+ event("session.execution.started", { sessionID: SESSION }),+ ...(heldEnd+ ? [+ event("session.execution.succeeded", { sessionID: SESSION }, "execution-end"),+ event("session.text.ended", {+ sessionID: SESSION,+ assistantMessageID: "msg_finished_before_stop",+ ordinal: 0,+ text: "Finished before Stop.",+ }),+ ]+ : []),+ out("session.interrupt", { sessionID: SESSION }),+ ...(heldEnd+ ? [event("session.usage.updated", { sessionID: SESSION }, "interrupt-reply")]+ : []),+ reply("session.interrupt", { interrupted: !heldEnd }),+ ...(heldEnd ? [] : [event("session.execution.interrupted", { sessionID: SESSION })]),+ out("session.prompt", { sessionID: SESSION, text: "<any>" }),+ promptAccepted,+ event("session.execution.started", { sessionID: SESSION }),+ event("session.execution.succeeded", { sessionID: SESSION }),+ ],+ {+ attachmentsDir,+ replayGate: gate,+ onPrompt: (input) => prompts.push(input),+ fileSystem: {+ ...fileSystem,+ exists: (file) =>+ file === path+ ? Effect.gen(function* () {+ yield* Deferred.succeed(resolving, undefined);+ yield* Deferred.await(release);+ return yield* fileSystem.exists(file);+ })+ : fileSystem.exists(file),+ },+ },+ );+ const stopped = yield* Deferred.make<void>();+ const completed = yield* Deferred.make<void>();+ const terminals: Array<string> = [];+ yield* runtime.events.pipe(+ Stream.tap((event) => {+ if (+ event.type === "turn_item.updated" &&+ event.turnItem.type === "assistant_message" &&+ event.turnItem.text === "Finished before Stop."+ ) {+ return Deferred.succeed(executionEnded, undefined);+ }+ if (event.type !== "turn.terminal") return Effect.void;+ terminals.push(event.status);+ return Deferred.succeed(terminals.length === 1 ? stopped : completed, undefined);+ }),+ Stream.runDrain,+ Effect.forkScoped,+ );+ yield* runtime.startTurn(turnInput(thread));+ const steer = yield* runtime+ .steerTurn({+ threadId,+ runId: RunId.make("run:opencode2-adapter"),+ providerThread: thread,+ providerTurnId: yield* providerTurnId,+ message: {+ ...turnInput(thread).message,+ messageId: MessageId.make("message:opencode2-adapter:steer"),+ text: "Do not send this image after Stop.",+ attachments: [image],+ },+ })+ .pipe(Effect.exit, Effect.forkScoped);+ yield* Deferred.await(resolving);+ if (heldEnd) {+ gate.release("execution-end");+ yield* Deferred.await(executionEnded);+ }+ const interrupt = yield* runtime+ .interruptTurn({+ providerThread: thread,+ providerTurnId: yield* providerTurnId,+ })+ .pipe(Effect.forkScoped);+ if (heldEnd) {+ assert.isTrue(yield* Effect.promise(() => gate.waitForReached("interrupt-reply")));+ } else {+ yield* Deferred.await(stopped);+ }+ yield* Deferred.succeed(release, undefined);+ const result = yield* Fiber.join(steer);+ assert.lengthOf(prompts, 1);+ assert.isTrue(Exit.isFailure(result));+ if (Exit.isFailure(result)) {+ assert.deepInclude(Cause.squash(result.cause), { _tag: "ProviderAdapterProtocolError" });+ }+ yield* Deferred.await(stopped);+ gate.release("interrupt-reply");+ yield* Fiber.join(interrupt);+ yield* runtime.startTurn(secondTurn(thread));+ yield* Deferred.await(completed);+ assert.lengthOf(prompts, 2);+ assert.deepEqual(terminals, ["interrupted", "completed"]);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+ );+it.effect("reads user and assistant text from the session's message list", () =>Effect.gen(function* () {const runtime = yield* openCode2ReplayRuntimeWithInstructions([diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.tsindex 6edb8d4e194..0b29a15d9e9 100644--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts@@ -7,6 +7,7 @@ import {type ProviderReplayTranscript,} from "@t3tools/contracts";import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Schema from "effect/Schema";import * as HttpClient from "effect/http/HttpClient";@@ -17,6 +18,8 @@ import * as UrlParams from "effect/http/UrlParams";import * as OpenCode2Client from "@t3tools/provider-opencode/server/v2/OpenCode2Client";import * as OpenCode2Server from "@t3tools/provider-opencode/server/v2/OpenCode2Server";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";+import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";+import { resolveAttachmentPath } from "../../attachmentStore.ts";import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";import type { ProviderReplayGate } from "@t3tools/provider-testing/replayGate";import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";@@ -127,6 +130,7 @@ const operationOf = (const replayHttpClient = (controller: OpenCodeReplayController,replayGate: ProviderReplayGate | undefined,+ onPrompt: ((input: unknown) => void) | undefined,) =>HttpClient.make((request, url) =>Effect.tryPromise({@@ -148,6 +152,7 @@ const replayHttpClient = (// The event stream and requests are separate connections: a request// is matched only once what was recorded before it was delivered.if (operation.type !== "event.subscribe") await controller.untilInboundDelivered();+ if (operation.type === "session.prompt") onPrompt?.(operation.input);await controller.expectOutbound(operation);if (operation.type === "event.subscribe") {controller.exited = false;@@ -187,6 +192,7 @@ export const replayServer = (transcript: ProviderReplayTranscript,options?: {readonly external?: boolean;+ readonly onPrompt?: (input: unknown) => void;readonly replayGate?: ProviderReplayGate;readonly borrowers?: { current: number };},@@ -202,7 +208,7 @@ export const replayServer = (const opencode = yield* OpenCode2Client.make.pipe(Effect.provideService(HttpClient.HttpClient,- replayHttpClient(controller, options?.replayGate),+ replayHttpClient(controller, options?.replayGate, options?.onPrompt),),);const connection = {@@ -233,6 +239,7 @@ const makeReplayAdapter = (transcript: ProviderReplayTranscript,options?: {readonly external?: boolean;+ readonly onPrompt?: (input: unknown) => void;readonly replayGate?: ProviderReplayGate;readonly borrowers?: { current: number };},@@ -246,6 +253,20 @@ const makeReplayAdapter = (const layerReplayHost = TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer));+const layerReplayHostWithAttachments = (attachmentsDir: string) =>+ Layer.effect(+ ProviderHost.ProviderHost,+ Effect.gen(function* () {+ const host = yield* ProviderHost.ProviderHost;+ return ProviderHost.ProviderHost.of({+ ...host,+ paths: { ...host.paths, attachmentsDir },+ resolveAttachmentPath: (attachment) =>+ resolveAttachmentPath({ attachmentsDir, attachment }),+ });+ }),+ ).pipe(Layer.provide(layerReplayHost));+function layerRegistry(transcript: OpenCode2ReplayTranscript,options?: { readonly replayGate?: ProviderReplayGate },@@ -261,11 +282,15 @@ export const openCode2ReplayRuntime = (entries: ReadonlyArray<ProviderReplayEntry>,options?: {readonly external?: boolean;+ readonly onPrompt?: (input: unknown) => void;readonly borrowers?: { current: number };readonly replayGate?: ProviderReplayGate;+ readonly attachmentsDir?: string;+ readonly fileSystem?: FileSystem.FileSystem;},) =>Effect.gen(function* () {+ const fileSystem = options?.fileSystem ?? (yield* FileSystem.FileSystem);const adapter = yield* makeReplayAdapter({provider: OPENCODE_PROVIDER,@@ -275,7 +300,7 @@ export const openCode2ReplayRuntime = (entries,},options,- );+ ).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem));return yield* adapter.openSession({threadId: ThreadId.make("thread:opencode2-adapter"),providerSessionId: ProviderSessionId.make("provider-session:opencode2-adapter"),@@ -289,7 +314,17 @@ export const openCode2ReplayRuntime = (cwd: "/work/opencode2",},});- }).pipe(Effect.provide(Layer.mergeAll(layerReplayHost, IdAllocator.layer, NodeServices.layer)));+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ options?.attachmentsDir === undefined+ ? layerReplayHost+ : layerReplayHostWithAttachments(options.attachmentsDir),+ IdAllocator.layer,+ NodeServices.layer,+ ),+ ),+ );export const OpenCode2OrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<OpenCode2ReplayTranscript,diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.tsindex 736a01d715c..1af260b9d05 100644--- a/packages/provider-opencode/src/server/v2/adapter.ts+++ b/packages/provider-opencode/src/server/v2/adapter.ts@@ -1,3 +1,5 @@+import * as NodeURL from "node:url";+import {AbsolutePath,Agent,@@ -14,6 +16,7 @@ import {import { Mcp } from "@opencode/schema/mcp";import {isOrchestrationV2WorkActive,+ type ChatAttachment,type OrchestrationV2AppThread,type OrchestrationV2ConversationMessage,type OrchestrationV2ExecutionNode,@@ -39,6 +42,7 @@ import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";import * as Hex from "effect/encoding/Hex";import * as Exit from "effect/Exit";+import * as FileSystem from "effect/FileSystem";import * as Option from "effect/Option";import * as Queue from "effect/Queue";import * as Schedule from "effect/Schedule";@@ -59,7 +63,10 @@ import * as KeyedLock from "@t3tools/shared/KeyedLock";import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model";import { causeErrorTag } from "@t3tools/shared/observability";-import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt";+import {+ isProviderNativeImageAttachment,+ providerMessageTextWithAttachmentPaths,+} from "@t3tools/provider-core/server/attachmentPrompt";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import {backgroundWorkNotification,@@ -665,6 +672,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prconst idAllocator = yield* IdAllocator.IdAllocatorV2;const host = yield* ProviderHost.ProviderHost;const mcpSessions = yield* McpProviderSessions.McpProviderSessions;+ const fileSystem = yield* FileSystem.FileSystem;const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;const crypto = yield* Crypto.Crypto;const driver = OPENCODE_PROVIDER;@@ -2920,6 +2928,21 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: PrresolveAttachmentPath: host.resolveAttachmentPath,}).trim();+ const promptFiles = Effect.fnUntraced(function* (attachments: ReadonlyArray<ChatAttachment>) {+ const files: Array<{ uri: string; name: string }> = [];+ // An external server may not share T3's attachment directory.+ if (connection.external) return files;+ for (const attachment of attachments) {+ if (!isProviderNativeImageAttachment(attachment)) continue;+ const path = host.resolveAttachmentPath(attachment);+ if (path === null) continue;+ // OpenCode rejects the whole prompt if an attached file is missing.+ const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false));+ if (exists) files.push({ uri: NodeURL.pathToFileURL(path).href, name: attachment.name });+ }+ return files;+ });+const removeMcp = (mcp: { readonly name: string; readonly directory: string }) =>Effect.suspend(() =>client.mcp.remove({ server: mcp.name, location: { directory: mcp.directory } }),@@ -3260,12 +3283,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr),): [];+ const files = yield* promptFiles(turnInput.message.attachments);if (!sending()) return;return yield* client.session.prompt({sessionID,id,text: promptText(turnInput),+ ...(files.length === 0 ? {} : { files }),...(skills.length === 0? {}: { skills: skills.map((id) => ({ id: Skill.ID.make(id) })) }),@@ -3587,6 +3612,26 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prif (turn.settledInbox.has(inboxID)) return;turn.steers.add(inboxID);state.strandedSteers.delete(inboxID);+ const files = yield* promptFiles(steerInput.message.attachments);+ if (state.active !== turn || turn.interrupted) {+ yield* lock.withPermit(+ Effect.gen(function* () {+ turn.steers.delete(inboxID);+ // Stop may have stranded this steer, but it never reached OpenCode.+ state.strandedSteers.delete(inboxID);+ if (state.active === turn) {+ if (turn.interrupted && turn.heldEnd !== undefined) {+ turn.heldEnd = { status: "interrupted" };+ }+ yield* endIfSettled(state, turn);+ }+ }),+ );+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({+ driver: OPENCODE_PROVIDER,+ detail: `OpenCode turn ${steerInput.providerTurnId} is not active`,+ });+ }yield* client.session.prompt({sessionID: Session.ID.make(sessionId),@@ -3596,6 +3641,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prattachments: steerInput.message.attachments,resolveAttachmentPath: host.resolveAttachmentPath,}).trim(),+ ...(files.length === 0 ? {} : { files }),delivery: "steer",}).pipe(