The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { ProviderInstanceId, settingsSecretLiteral, TextGenerationError } from "@t3tools/contracts"; |
| 2 | import { OpenCodeSettings } from "../settings.ts"; |
| 3 | import type { OpencodeClient } from "@opencode-ai/sdk/v2"; |
| 4 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 5 | import { it } from "@effect/vitest"; |
| 6 | import * as Cause from "effect/Cause"; |
| 7 | import * as Deferred from "effect/Deferred"; |
| 8 | import * as Duration from "effect/Duration"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Exit from "effect/Exit"; |
| 11 | import * as Fiber from "effect/Fiber"; |
| 12 | import * as Layer from "effect/Layer"; |
| 13 | import * as Schema from "effect/Schema"; |
| 14 | import * as TestClock from "effect/testing/TestClock"; |
| 15 | import * as NetService from "@t3tools/shared/Net"; |
| 16 | import { beforeEach, expect } from "vite-plus/test"; |
| 17 | |
| 18 | import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; |
| 19 | import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; |
| 20 | import * as OpenCodeRuntime from "./OpenCodeRuntime.ts"; |
| 21 | import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts"; |
| 22 | import * as OpenCodeTextGeneration from "./textGeneration.ts"; |
| 23 | import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration"; |
| 24 | |
| 25 | const runtimeMock = { |
| 26 | state: { |
| 27 | startCalls: [] as string[], |
| 28 | promptUrls: [] as string[], |
| 29 | promptParts: [] as ReadonlyArray<unknown>[], |
| 30 | promptInputs: [] as Array<Parameters<OpencodeClient["session"]["prompt"]>[0]>, |
| 31 | authHeaders: [] as Array<string | null>, |
| 32 | closeCalls: [] as string[], |
| 33 | sessionCreateCalls: 0, |
| 34 | sessionCalls: [] as string[], |
| 35 | onSessionCreate: undefined as ((signal?: AbortSignal) => Promise<never>) | undefined, |
| 36 | onPrompt: undefined as |
| 37 | | ((signal?: AbortSignal) => Promise<{ data: { parts: ReadonlyArray<unknown> } }>) |
| 38 | | undefined, |
| 39 | onAbort: undefined as ((signal?: AbortSignal) => Promise<never>) | undefined, |
| 40 | connectionError: undefined as Error | undefined, |
| 41 | sessionCreateError: undefined as unknown, |
| 42 | sessionResult: undefined as { data?: { id: string } } | undefined, |
| 43 | promptRequestError: undefined as unknown, |
| 44 | promptResult: undefined as |
| 45 | | { data?: { info?: { error?: unknown }; parts?: Array<unknown> } } |
| 46 | | undefined, |
| 47 | }, |
| 48 | reset() { |
| 49 | this.state.startCalls.length = 0; |
| 50 | this.state.promptUrls.length = 0; |
| 51 | this.state.promptParts.length = 0; |
| 52 | this.state.promptInputs.length = 0; |
| 53 | this.state.authHeaders.length = 0; |
| 54 | this.state.closeCalls.length = 0; |
| 55 | this.state.sessionCreateCalls = 0; |
| 56 | this.state.sessionCalls.length = 0; |
| 57 | this.state.onSessionCreate = undefined; |
| 58 | this.state.onPrompt = undefined; |
| 59 | this.state.onAbort = undefined; |
| 60 | this.state.connectionError = undefined; |
| 61 | this.state.sessionCreateError = undefined; |
| 62 | this.state.sessionResult = undefined; |
| 63 | this.state.promptRequestError = undefined; |
| 64 | this.state.promptResult = undefined; |
| 65 | }, |
| 66 | }; |
| 67 | |
| 68 | const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = { |
| 69 | startOpenCodeServerProcess: ({ binaryPath, serverPassword, environment }) => |
| 70 | Effect.gen(function* () { |
| 71 | const index = runtimeMock.state.startCalls.length + 1; |
| 72 | const url = `http://127.0.0.1:${4_300 + index}`; |
| 73 | runtimeMock.state.startCalls.push(binaryPath); |
| 74 | yield* Effect.addFinalizer(() => |
| 75 | Effect.sync(() => { |
| 76 | runtimeMock.state.closeCalls.push(url); |
| 77 | }), |
| 78 | ); |
| 79 | const effectiveServerPassword = OpenCodeRuntime.resolveOpenCodeServerPassword({ |
| 80 | external: false, |
| 81 | ...(serverPassword !== undefined ? { serverPassword } : {}), |
| 82 | ...(environment !== undefined ? { environment } : {}), |
| 83 | }); |
| 84 | return { |
| 85 | url, |
| 86 | ...(effectiveServerPassword !== undefined |
| 87 | ? { serverPassword: effectiveServerPassword } |
| 88 | : {}), |
| 89 | version: "1.14.19", |
| 90 | isRunning: Effect.succeed(true), |
| 91 | exitCode: Effect.never, |
| 92 | }; |
| 93 | }), |
| 94 | connectToOpenCodeServer: ({ serverUrl, serverPassword }) => |
| 95 | runtimeMock.state.connectionError |
| 96 | ? Effect.fail( |
| 97 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 98 | operation: "global.health", |
| 99 | detail: runtimeMock.state.connectionError.message, |
| 100 | cause: runtimeMock.state.connectionError, |
| 101 | }), |
| 102 | ) |
| 103 | : Effect.succeed({ |
| 104 | url: serverUrl ?? "http://127.0.0.1:4301", |
| 105 | ...(serverPassword ? { serverPassword } : {}), |
| 106 | version: "1.14.19", |
| 107 | exitCode: null, |
| 108 | external: Boolean(serverUrl), |
| 109 | }), |
| 110 | runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }), |
| 111 | createOpenCodeSdkClient: ({ baseUrl, serverPassword }) => |
| 112 | ({ |
| 113 | provider: { |
| 114 | list: async () => ({ |
| 115 | data: { |
| 116 | all: [{ id: "openai", models: { "gpt-5": { id: "gpt-5" } } }], |
| 117 | }, |
| 118 | }), |
| 119 | }, |
| 120 | session: { |
| 121 | create: async (_input: unknown, options?: { readonly signal?: AbortSignal }) => { |
| 122 | runtimeMock.state.sessionCreateCalls += 1; |
| 123 | if (runtimeMock.state.onSessionCreate) { |
| 124 | return runtimeMock.state.onSessionCreate(options?.signal); |
| 125 | } |
| 126 | if (runtimeMock.state.sessionCreateError !== undefined) { |
| 127 | throw runtimeMock.state.sessionCreateError; |
| 128 | } |
| 129 | return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } }; |
| 130 | }, |
| 131 | abort: async ( |
| 132 | input: { readonly sessionID: string }, |
| 133 | options?: { readonly signal?: AbortSignal }, |
| 134 | ) => { |
| 135 | runtimeMock.state.sessionCalls.push(`abort ${input.sessionID}`); |
| 136 | if (runtimeMock.state.onAbort) return runtimeMock.state.onAbort(options?.signal); |
| 137 | return { data: true }; |
| 138 | }, |
| 139 | delete: async (input: { readonly sessionID: string }) => { |
| 140 | runtimeMock.state.sessionCalls.push(`delete ${input.sessionID}`); |
| 141 | return { data: true }; |
| 142 | }, |
| 143 | prompt: async ( |
| 144 | input: Parameters<OpencodeClient["session"]["prompt"]>[0], |
| 145 | options?: { readonly signal?: AbortSignal }, |
| 146 | ) => { |
| 147 | runtimeMock.state.promptInputs.push(input); |
| 148 | runtimeMock.state.promptUrls.push(baseUrl); |
| 149 | runtimeMock.state.promptParts.push(input.parts ?? []); |
| 150 | runtimeMock.state.authHeaders.push( |
| 151 | serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null, |
| 152 | ); |
| 153 | if (runtimeMock.state.onPrompt) return runtimeMock.state.onPrompt(options?.signal); |
| 154 | if (runtimeMock.state.promptRequestError !== undefined) { |
| 155 | throw runtimeMock.state.promptRequestError; |
| 156 | } |
| 157 | return ( |
| 158 | runtimeMock.state.promptResult ?? { |
| 159 | data: { |
| 160 | parts: [ |
| 161 | { |
| 162 | type: "text", |
| 163 | text: JSON.stringify({ |
| 164 | subject: "Improve OpenCode reuse", |
| 165 | body: "Reuse one server for the full action.", |
| 166 | }), |
| 167 | }, |
| 168 | ], |
| 169 | }, |
| 170 | } |
| 171 | ); |
| 172 | }, |
| 173 | }, |
| 174 | }) as unknown as ReturnType< |
| 175 | OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"] |
| 176 | >, |
| 177 | loadOpenCodeInventory: () => |
| 178 | Effect.fail( |
| 179 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 180 | operation: "loadOpenCodeInventory", |
| 181 | detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test", |
| 182 | cause: null, |
| 183 | }), |
| 184 | ), |
| 185 | loadOpenCodeSkills: () => Effect.succeed([]), |
| 186 | }; |
| 187 | |
| 188 | const DEFAULT_TEST_MODEL_SELECTION = { |
| 189 | instanceId: ProviderInstanceId.make("opencode"), |
| 190 | model: "openai/gpt-5", |
| 191 | }; |
| 192 | const DEFAULT_COMMIT_MESSAGE_INPUT = { |
| 193 | cwd: process.cwd(), |
| 194 | branch: "feature/opencode-reuse", |
| 195 | stagedSummary: "M README.md", |
| 196 | stagedPatch: "diff --git a/README.md b/README.md", |
| 197 | modelSelection: DEFAULT_TEST_MODEL_SELECTION, |
| 198 | }; |
| 199 | |
| 200 | const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000; |
| 201 | |
| 202 | const layerOpenCodeTextGenerationTest = Layer.succeed( |
| 203 | OpenCodeRuntime.OpenCodeRuntime, |
| 204 | OpenCodeRuntimeTestDouble, |
| 205 | ).pipe( |
| 206 | Layer.provideMerge(TestProviderHost.layer()), |
| 207 | Layer.provideMerge(NetService.layer), |
| 208 | Layer.provideMerge(NodeServices.layer), |
| 209 | ); |
| 210 | |
| 211 | const layerOpenCodeTextGenerationExistingServerTest = Layer.succeed( |
| 212 | OpenCodeRuntime.OpenCodeRuntime, |
| 213 | OpenCodeRuntimeTestDouble, |
| 214 | ).pipe( |
| 215 | Layer.provideMerge(TestProviderHost.layer()), |
| 216 | Layer.provideMerge(NetService.layer), |
| 217 | Layer.provideMerge(NodeServices.layer), |
| 218 | ); |
| 219 | |
| 220 | const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({ |
| 221 | binaryPath: "fake-opencode", |
| 222 | }); |
| 223 | const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({ |
| 224 | binaryPath: "fake-opencode", |
| 225 | serverUrl: "http://127.0.0.1:9999", |
| 226 | serverPassword: "secret-password", |
| 227 | }); |
| 228 | const EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({ |
| 229 | binaryPath: "fake-opencode", |
| 230 | serverUrl: "http://127.0.0.1:9999", |
| 231 | }); |
| 232 | |
| 233 | function withOpenCodeTextGeneration<A, E, R>( |
| 234 | settings: OpenCodeSettings, |
| 235 | effectFn: (textGeneration: ProviderTextGeneration) => Effect.Effect<A, E, R>, |
| 236 | environment?: NodeJS.ProcessEnv, |
| 237 | ) { |
| 238 | return Effect.gen(function* () { |
| 239 | const serverOwner = yield* OpenCodeServerOwner.make({ |
| 240 | binaryPath: settings.binaryPath, |
| 241 | directory: process.cwd(), |
| 242 | ...(settingsSecretLiteral(settings.serverPassword) |
| 243 | ? { serverPassword: settingsSecretLiteral(settings.serverPassword) } |
| 244 | : {}), |
| 245 | ...(environment ? { environment } : {}), |
| 246 | }); |
| 247 | const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings).pipe( |
| 248 | Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner), |
| 249 | ); |
| 250 | return yield* effectFn(textGeneration); |
| 251 | }).pipe(Effect.scoped); |
| 252 | } |
| 253 | |
| 254 | beforeEach(() => { |
| 255 | runtimeMock.reset(); |
| 256 | }); |
| 257 | |
| 258 | const advanceIdleClock = Effect.gen(function* () { |
| 259 | yield* Effect.yieldNow; |
| 260 | yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1)); |
| 261 | yield* Effect.yieldNow; |
| 262 | }); |
| 263 | |
| 264 | it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => { |
| 265 | it.effect("omits stale reasoning variants when generating commit messages", () => |
| 266 | withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => |
| 267 | Effect.gen(function* () { |
| 268 | yield* textGeneration.generateCommitMessage({ |
| 269 | ...DEFAULT_COMMIT_MESSAGE_INPUT, |
| 270 | modelSelection: { |
| 271 | ...DEFAULT_TEST_MODEL_SELECTION, |
| 272 | options: [ |
| 273 | { id: "variant", value: "medium" }, |
| 274 | { id: "agent", value: "plan" }, |
| 275 | ], |
| 276 | }, |
| 277 | }); |
| 278 | |
| 279 | expect(runtimeMock.state.promptInputs).toHaveLength(1); |
| 280 | expect(runtimeMock.state.promptInputs[0]).toMatchObject({ |
| 281 | model: { providerID: "openai", modelID: "gpt-5" }, |
| 282 | agent: "plan", |
| 283 | }); |
| 284 | expect(runtimeMock.state.promptInputs[0]).not.toHaveProperty("variant"); |
| 285 | }), |
| 286 | ), |
| 287 | ); |
| 288 | |
| 289 | it.effect("cancels or times out an in-flight session creation before prompting", () => |
| 290 | withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) => |
| 291 | Effect.gen(function* () { |
| 292 | const timedOut = yield* Deferred.make<AbortSignal | undefined>(); |
| 293 | runtimeMock.state.onSessionCreate = (signal) => { |
| 294 | Deferred.doneUnsafe(timedOut, Effect.succeed(signal)); |
| 295 | return new Promise<never>(() => {}); |
| 296 | }; |
| 297 | const timedOutFiber = yield* textGeneration |
| 298 | .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) |
| 299 | .pipe(Effect.forkChild); |
| 300 | const timedOutSignal = yield* Deferred.await(timedOut); |
| 301 | yield* TestClock.adjust(Duration.minutes(3)); |
| 302 | const timeoutError = yield* Fiber.join(timedOutFiber).pipe(Effect.flip); |
| 303 | expect(timeoutError).toBeInstanceOf(TextGenerationError); |
| 304 | expect(timeoutError.detail).toBe("OpenCode did not finish generating in time."); |
| 305 | expect(timedOutSignal?.aborted).toBe(true); |
| 306 | |
| 307 | const started = yield* Deferred.make<AbortSignal | undefined>(); |
| 308 | runtimeMock.state.onSessionCreate = (signal) => { |
| 309 | Deferred.doneUnsafe(started, Effect.succeed(signal)); |
| 310 | return new Promise<never>(() => {}); |
| 311 | }; |
| 312 | const fiber = yield* textGeneration |
| 313 | .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) |
| 314 | .pipe(Effect.forkChild); |
| 315 | const signal = yield* Deferred.await(started); |
| 316 | yield* Fiber.interrupt(fiber); |
| 317 | |
| 318 | const exit = yield* Fiber.await(fiber); |
| 319 | expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true); |
| 320 | expect(signal?.aborted).toBe(true); |
| 321 | expect(runtimeMock.state.promptUrls).toEqual([]); |
| 322 | expect(runtimeMock.state.sessionCalls).toEqual([]); |
| 323 | }), |
| 324 | ), |
| 325 | ); |
| 326 | |
| 327 | it.effect("cancels only its prompt session while another generation uses the shared server", () => |
| 328 | withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => |
| 329 | Effect.gen(function* () { |
| 330 | const started = yield* Deferred.make<AbortSignal | undefined>(); |
| 331 | runtimeMock.state.sessionResult = { data: { id: "cancelled-session" } }; |
| 332 | runtimeMock.state.onPrompt = (signal) => { |
| 333 | Deferred.doneUnsafe(started, Effect.succeed(signal)); |
| 334 | return new Promise<never>(() => {}); |
| 335 | }; |
| 336 | const fiber = yield* textGeneration |
| 337 | .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) |
| 338 | .pipe(Effect.forkChild); |
| 339 | const signal = yield* Deferred.await(started); |
| 340 | |
| 341 | const otherStarted = yield* Deferred.make<AbortSignal | undefined>(); |
| 342 | const otherReply = Promise.withResolvers<{ data: { parts: ReadonlyArray<unknown> } }>(); |
| 343 | runtimeMock.state.sessionResult = { data: { id: "other-session" } }; |
| 344 | runtimeMock.state.onPrompt = (otherSignal) => { |
| 345 | Deferred.doneUnsafe(otherStarted, Effect.succeed(otherSignal)); |
| 346 | return otherReply.promise; |
| 347 | }; |
| 348 | const otherFiber = yield* textGeneration |
| 349 | .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) |
| 350 | .pipe(Effect.forkChild); |
| 351 | const otherSignal = yield* Deferred.await(otherStarted); |
| 352 | yield* Fiber.interrupt(fiber); |
| 353 | |
| 354 | const exit = yield* Fiber.await(fiber); |
| 355 | expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true); |
| 356 | expect(signal?.aborted).toBe(true); |
| 357 | expect(otherSignal?.aborted).toBe(false); |
| 358 | expect(runtimeMock.state.sessionCalls).toEqual([ |
| 359 | "abort cancelled-session", |
| 360 | "delete cancelled-session", |
| 361 | ]); |
| 362 | expect(runtimeMock.state.closeCalls).toEqual([]); |
| 363 | |
| 364 | otherReply.resolve({ |
| 365 | data: { |
| 366 | parts: [{ type: "text", text: '{"subject":"Other generation completed","body":""}' }], |
| 367 | }, |
| 368 | }); |
| 369 | expect((yield* Fiber.join(otherFiber)).subject).toBe("Other generation completed"); |
| 370 | expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]); |
| 371 | expect(runtimeMock.state.promptUrls).toEqual([ |
| 372 | "http://127.0.0.1:4301", |
| 373 | "http://127.0.0.1:4301", |
| 374 | ]); |
| 375 | expect(runtimeMock.state.sessionCalls).toEqual([ |
| 376 | "abort cancelled-session", |
| 377 | "delete cancelled-session", |
| 378 | "delete other-session", |
| 379 | ]); |
| 380 | expect(runtimeMock.state.closeCalls).toEqual([]); |
| 381 | }), |
| 382 | ), |
| 383 | ); |
| 384 | |
| 385 | it.effect("excludes generic files from thread title generation", () => |
| 386 | withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => |
| 387 | Effect.gen(function* () { |
| 388 | runtimeMock.state.promptResult = { |
| 389 | data: { |
| 390 | parts: [{ type: "text", text: '{"title":"Review uploaded report"}' }], |
| 391 | }, |
| 392 | }; |
| 393 | |
| 394 | yield* textGeneration.generateThreadTitle({ |
| 395 | cwd: process.cwd(), |
| 396 | message: "Review these attachments.", |
| 397 | modelSelection: DEFAULT_TEST_MODEL_SELECTION, |
| 398 | attachments: [ |
| 399 | { |
| 400 | type: "image", |
| 401 | id: "thread-image-attachment", |
| 402 | name: "screenshot.png", |
| 403 | mimeType: "image/png", |
| 404 | sizeBytes: 3, |
| 405 | }, |
| 406 | { |
| 407 | type: "file", |
| 408 | id: "thread-report-attachment-pdf", |
| 409 | name: "report.pdf", |
| 410 | mimeType: "application/pdf", |
| 411 | sizeBytes: 42, |
| 412 | }, |
| 413 | ], |
| 414 | }); |
| 415 | |
| 416 | expect(runtimeMock.state.promptParts[0]).toEqual([ |
| 417 | expect.objectContaining({ type: "text" }), |
| 418 | expect.objectContaining({ type: "file", filename: "screenshot.png" }), |
| 419 | ]); |
| 420 | }), |
| 421 | ), |
| 422 | ); |
| 423 | |
| 424 | it.effect("gives up and aborts the session when a prompt never settles", () => |
| 425 | withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => |
| 426 | Effect.gen(function* () { |
| 427 | const started = yield* Deferred.make<AbortSignal | undefined>(); |
| 428 | let sessionAborts = 0; |
| 429 | runtimeMock.state.onPrompt = (signal) => { |
| 430 | Deferred.doneUnsafe(started, Effect.succeed(signal)); |
| 431 | return new Promise<never>(() => {}); |
| 432 | }; |
| 433 | runtimeMock.state.onAbort = () => { |
| 434 | sessionAborts += 1; |
| 435 | return Promise.reject(new Error("abort observed")); |
| 436 | }; |
| 437 | const fiber = yield* textGeneration |
| 438 | .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) |
| 439 | .pipe(Effect.forkChild); |
| 440 | const signal = yield* Deferred.await(started); |
| 441 | yield* TestClock.adjust(Duration.minutes(3)); |
| 442 | |
| 443 | const error = yield* Fiber.join(fiber).pipe(Effect.flip); |
| 444 | expect(error).toBeInstanceOf(TextGenerationError); |
| 445 | expect(error.detail).toBe("OpenCode did not finish generating in time."); |
| 446 | expect(signal?.aborted).toBe(true); |
| 447 | expect(sessionAborts).toBe(1); |
| 448 | }), |
| 449 | ), |
| 450 | ); |
| 451 | |
| 452 | it.effect("uses an environment-only password for a locally spawned server", () => |
| 453 | withOpenCodeTextGeneration( |
| 454 | DEFAULT_OPENCODE_SETTINGS, |
| 455 | (textGeneration) => |
| 456 | Effect.gen(function* () { |
| 457 | yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT); |
| 458 | |
| 459 | expect(runtimeMock.state.authHeaders).toEqual([ |
| 460 | `Basic ${btoa("opencode:environment-password")}`, |
| 461 | ]); |
| 462 | }), |
| 463 | { OPENCODE_SERVER_PASSWORD: "environment-password" }, |
| 464 | ), |
| 465 | ); |
| 466 | |
| 467 | it.effect("returns a typed empty-output error for malformed and blank response parts", () => |
| 468 | withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => |
| 469 | Effect.gen(function* () { |
| 470 | runtimeMock.state.promptResult = { |
| 471 | data: { |
| 472 | parts: [null, { type: "tool" }, { type: "text", text: " " }], |
| 473 | }, |
| 474 | }; |
| 475 | |
| 476 | const error = yield* textGeneration |
| 477 | .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) |
| 478 | .pipe(Effect.flip); |
| 479 | |
| 480 | expect(error.message).toContain("OpenCode returned empty output."); |
| 481 | expect(error.cause).toMatchObject({ |
| 482 | _tag: "OpenCodeTextGenerationEmptyOutputError", |
| 483 | operation: "generateCommitMessage", |
| 484 | cwd: process.cwd(), |
| 485 | sessionId: "http://127.0.0.1:4301/session", |
| 486 | providerId: "openai", |
| 487 | modelId: "gpt-5", |
| 488 | responsePartCount: 3, |
| 489 | textPartCount: 1, |
| 490 | }); |
| 491 | expect(error.cause).not.toHaveProperty("cause"); |
| 492 | expect(runtimeMock.state.sessionCalls).toEqual(["delete http://127.0.0.1:4301/session"]); |
| 493 | }), |
| 494 | ), |
| 495 | ); |
| 496 | |
| 497 | it.effect( |
| 498 | "maps OpenCode prompt errors to fixed details and keeps provider text in the cause", |
| 499 | () => |
| 500 | Effect.forEach( |
| 501 | [ |
| 502 | { |
| 503 | error: { |
| 504 | name: "APIError", |
| 505 | data: { |
| 506 | message: "Org quota secret-org exceeded", |
| 507 | statusCode: 429, |
| 508 | isRetryable: true, |
| 509 | }, |
| 510 | }, |
| 511 | rawText: "secret-org", |
| 512 | detail: "The model provider's usage or rate limit was reached. Try again later.", |
| 513 | }, |
| 514 | { |
| 515 | error: { |
| 516 | name: "APIError", |
| 517 | data: { |
| 518 | message: "<none>", |
| 519 | statusCode: 503, |
| 520 | isRetryable: true, |
| 521 | responseBody: "<title>Upstream gateway secret-host</title>", |
| 522 | }, |
| 523 | }, |
| 524 | rawText: "secret-host", |
| 525 | detail: "The model provider failed the request (HTTP 503).", |
| 526 | }, |
| 527 | { |
| 528 | error: { name: "UnknownError", data: { message: "Provider stack trace secret-token" } }, |
| 529 | rawText: "secret-token", |
| 530 | detail: "OpenCode could not generate the text.", |
| 531 | }, |
| 532 | ], |
| 533 | (testCase) => |
| 534 | withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => |
| 535 | Effect.gen(function* () { |
| 536 | runtimeMock.state.promptResult = { |
| 537 | data: { info: { error: testCase.error }, parts: [] }, |
| 538 | }; |
| 539 | |
| 540 | const error = yield* textGeneration |
| 541 | .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) |
| 542 | .pipe(Effect.flip); |
| 543 | |
| 544 | expect(error.detail).toBe(testCase.detail); |
| 545 | expect(error.message).not.toContain(testCase.rawText); |
| 546 | expect(error.cause).toMatchObject({ |
| 547 | _tag: "OpenCodeTextGenerationPromptResponseError", |
| 548 | providerErrorName: testCase.error.name, |
| 549 | cause: testCase.error, |
| 550 | }); |
| 551 | expect((error.cause as Error).message).not.toContain(testCase.rawText); |
| 552 | }), |
| 553 | ), |
| 554 | { discard: true }, |
| 555 | ), |
| 556 | ); |
| 557 | |
| 558 | it.effect("deletes the session when the prompt request rejects", () => |
| 559 | withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => |
| 560 | Effect.gen(function* () { |
| 561 | runtimeMock.state.promptRequestError = new Error("prompt transport failed"); |
| 562 | |
| 563 | const error = yield* textGeneration |
| 564 | .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) |
| 565 | .pipe(Effect.flip); |
| 566 | |
| 567 | expect(error.detail).toBe("OpenCode session.prompt request failed."); |
| 568 | expect(runtimeMock.state.sessionCalls).toEqual(["delete http://127.0.0.1:4301/session"]); |
| 569 | }), |
| 570 | ), |
| 571 | ); |
| 572 | |
| 573 | it.effect("parses JSON returned as plain text output", () => |
| 574 | withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => |
| 575 | Effect.gen(function* () { |
| 576 | runtimeMock.state.promptResult = { |
| 577 | data: { |
| 578 | parts: [ |
| 579 | { |
| 580 | type: "text", |
| 581 | text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}', |
| 582 | }, |
| 583 | ], |
| 584 | }, |
| 585 | }; |
| 586 | |
| 587 | const result = yield* textGeneration.generateCommitMessage({ |
| 588 | cwd: process.cwd(), |
| 589 | branch: "feature/opencode-reuse", |
| 590 | stagedSummary: "M README.md", |
| 591 | stagedPatch: "diff --git a/README.md b/README.md", |
| 592 | modelSelection: DEFAULT_TEST_MODEL_SELECTION, |
| 593 | }); |
| 594 | |
| 595 | expect(result).toEqual({ |
| 596 | subject: "Tighten OpenCode parsing", |
| 597 | body: "Handle JSON text output locally.", |
| 598 | }); |
| 599 | }), |
| 600 | ), |
| 601 | ); |
| 602 | }); |
| 603 | |
| 604 | it.layer(layerOpenCodeTextGenerationExistingServerTest)( |
| 605 | "OpenCodeTextGeneration with configured server URL", |
| 606 | (it) => { |
| 607 | it.effect("does not send a local environment password to a configured server", () => |
| 608 | withOpenCodeTextGeneration( |
| 609 | EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS, |
| 610 | (textGeneration) => |
| 611 | Effect.gen(function* () { |
| 612 | yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT); |
| 613 | expect(runtimeMock.state.authHeaders).toEqual([null]); |
| 614 | }), |
| 615 | { OPENCODE_SERVER_PASSWORD: "local-secret" }, |
| 616 | ), |
| 617 | ); |
| 618 | |
| 619 | it.effect("does not create a session on a server version the policy rates broken", () => |
| 620 | withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) => |
| 621 | Effect.gen(function* () { |
| 622 | const error = yield* textGeneration |
| 623 | .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) |
| 624 | .pipe(Effect.flip); |
| 625 | |
| 626 | expect(error).toBeInstanceOf(TextGenerationError); |
| 627 | expect(error.message).toContain("OpenCode 1.14.19 does not work"); |
| 628 | expect(runtimeMock.state.sessionCreateCalls).toBe(0); |
| 629 | }), |
| 630 | ).pipe( |
| 631 | Effect.updateService(ProviderHost.ProviderHost, (host) => ({ |
| 632 | ...host, |
| 633 | compatibility: () => |
| 634 | Effect.succeed({ |
| 635 | status: "broken" as const, |
| 636 | message: null, |
| 637 | recommendedVersion: null, |
| 638 | recommendedRange: ">=2.0.18", |
| 639 | }), |
| 640 | })), |
| 641 | ), |
| 642 | ); |
| 643 | |
| 644 | it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () => |
| 645 | withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) => |
| 646 | Effect.gen(function* () { |
| 647 | yield* textGeneration.generateCommitMessage({ |
| 648 | cwd: process.cwd(), |
| 649 | branch: "feature/opencode-reuse", |
| 650 | stagedSummary: "M README.md", |
| 651 | stagedPatch: "diff --git a/README.md b/README.md", |
| 652 | modelSelection: DEFAULT_TEST_MODEL_SELECTION, |
| 653 | }); |
| 654 | yield* textGeneration.generateCommitMessage({ |
| 655 | cwd: process.cwd(), |
| 656 | branch: "feature/opencode-reuse", |
| 657 | stagedSummary: "M README.md", |
| 658 | stagedPatch: "diff --git a/README.md b/README.md", |
| 659 | modelSelection: DEFAULT_TEST_MODEL_SELECTION, |
| 660 | }); |
| 661 | |
| 662 | expect(runtimeMock.state.startCalls).toEqual([]); |
| 663 | expect(runtimeMock.state.sessionCalls).toEqual([ |
| 664 | "delete http://127.0.0.1:9999/session", |
| 665 | "delete http://127.0.0.1:9999/session", |
| 666 | ]); |
| 667 | expect(runtimeMock.state.promptUrls).toEqual([ |
| 668 | "http://127.0.0.1:9999", |
| 669 | "http://127.0.0.1:9999", |
| 670 | ]); |
| 671 | expect(runtimeMock.state.authHeaders).toEqual([ |
| 672 | `Basic ${btoa("opencode:secret-password")}`, |
| 673 | `Basic ${btoa("opencode:secret-password")}`, |
| 674 | ]); |
| 675 | |
| 676 | yield* advanceIdleClock; |
| 677 | |
| 678 | expect(runtimeMock.state.closeCalls).toEqual([]); |
| 679 | }), |
| 680 | ).pipe(Effect.provide(TestClock.layer())), |
| 681 | ); |
| 682 | }, |
| 683 | ); |