Open History to see the last commit
1import { ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
2import { OpenCodeSettings } from "../settings.ts";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { it } from "@effect/vitest";
5import * as Cause from "effect/Cause";
6import * as Deferred from "effect/Deferred";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
11import * as Layer from "effect/Layer";
12import * as Logger from "effect/Logger";
13import * as Schema from "effect/Schema";
14import * as TestClock from "effect/testing/TestClock";
15import * as NetService from "@t3tools/shared/Net";
16import { beforeEach, expect } from "vite-plus/test";
17
18import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
19import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
20import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
21import * as OpenCodeTextGeneration from "./textGeneration.ts";
22import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
23
24const runtimeMock = {
25 state: {
26 startCalls: [] as string[],
27 promptUrls: [] as string[],
28 promptParts: [] as ReadonlyArray<unknown>[],
29 authHeaders: [] as Array<string | null>,
30 closeCalls: [] as string[],
31 sessionCreateCalls: 0,
32 abortCalls: [] as string[],
33 onSessionCreate: undefined as ((signal?: AbortSignal) => Promise<never>) | undefined,
34 onPrompt: undefined as
35 | ((signal?: AbortSignal) => Promise<{ data: { parts: ReadonlyArray<unknown> } }>)
36 | undefined,
37 onAbort: undefined as ((signal?: AbortSignal) => Promise<never>) | undefined,
38 connectionError: undefined as Error | undefined,
39 sessionCreateError: undefined as unknown,
40 sessionResult: undefined as { data?: { id: string } } | undefined,
41 promptRequestError: undefined as unknown,
42 promptResult: undefined as
43 | { data?: { info?: { error?: unknown }; parts?: Array<unknown> } }
44 | undefined,
45 },
46 reset() {
47 this.state.startCalls.length = 0;
48 this.state.promptUrls.length = 0;
49 this.state.promptParts.length = 0;
50 this.state.authHeaders.length = 0;
51 this.state.closeCalls.length = 0;
52 this.state.sessionCreateCalls = 0;
53 this.state.abortCalls.length = 0;
54 this.state.onSessionCreate = undefined;
55 this.state.onPrompt = undefined;
56 this.state.onAbort = undefined;
57 this.state.connectionError = undefined;
58 this.state.sessionCreateError = undefined;
59 this.state.sessionResult = undefined;
60 this.state.promptRequestError = undefined;
61 this.state.promptResult = undefined;
62 },
63};
64
65const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
66 startOpenCodeServerProcess: ({ binaryPath, serverPassword, environment }) =>
67 Effect.gen(function* () {
68 const index = runtimeMock.state.startCalls.length + 1;
69 const url = `http://127.0.0.1:${4_300 + index}`;
70 runtimeMock.state.startCalls.push(binaryPath);
71 yield* Effect.addFinalizer(() =>
72 Effect.sync(() => {
73 runtimeMock.state.closeCalls.push(url);
74 }),
75 );
76 const effectiveServerPassword = OpenCodeRuntime.resolveOpenCodeServerPassword({
77 external: false,
78 ...(serverPassword !== undefined ? { serverPassword } : {}),
79 ...(environment !== undefined ? { environment } : {}),
80 });
81 return {
82 url,
83 ...(effectiveServerPassword !== undefined
84 ? { serverPassword: effectiveServerPassword }
85 : {}),
86 version: "1.14.19",
87 isRunning: Effect.succeed(true),
88 exitCode: Effect.never,
89 };
90 }),
91 connectToOpenCodeServer: ({ serverUrl, serverPassword }) =>
92 runtimeMock.state.connectionError
93 ? Effect.fail(
94 new OpenCodeRuntime.OpenCodeRuntimeError({
95 operation: "global.health",
96 detail: runtimeMock.state.connectionError.message,
97 cause: runtimeMock.state.connectionError,
98 }),
99 )
100 : Effect.succeed({
101 url: serverUrl ?? "http://127.0.0.1:4301",
102 ...(serverPassword ? { serverPassword } : {}),
103 version: "1.14.19",
104 exitCode: null,
105 external: Boolean(serverUrl),
106 }),
107 runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
108 createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
109 ({
110 session: {
111 create: async (_input: unknown, options?: { readonly signal?: AbortSignal }) => {
112 runtimeMock.state.sessionCreateCalls += 1;
113 if (runtimeMock.state.onSessionCreate) {
114 return runtimeMock.state.onSessionCreate(options?.signal);
115 }
116 if (runtimeMock.state.sessionCreateError !== undefined) {
117 throw runtimeMock.state.sessionCreateError;
118 }
119 return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } };
120 },
121 abort: async (
122 input: { readonly sessionID: string },
123 options?: { readonly signal?: AbortSignal },
124 ) => {
125 runtimeMock.state.abortCalls.push(input.sessionID);
126 if (runtimeMock.state.onAbort) return runtimeMock.state.onAbort(options?.signal);
127 return { data: true };
128 },
129 prompt: async (
130 input: { readonly parts: ReadonlyArray<unknown> },
131 options?: { readonly signal?: AbortSignal },
132 ) => {
133 runtimeMock.state.promptUrls.push(baseUrl);
134 runtimeMock.state.promptParts.push(input.parts);
135 runtimeMock.state.authHeaders.push(
136 serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
137 );
138 if (runtimeMock.state.onPrompt) return runtimeMock.state.onPrompt(options?.signal);
139 if (runtimeMock.state.promptRequestError !== undefined) {
140 throw runtimeMock.state.promptRequestError;
141 }
142 return (
143 runtimeMock.state.promptResult ?? {
144 data: {
145 parts: [
146 {
147 type: "text",
148 text: JSON.stringify({
149 subject: "Improve OpenCode reuse",
150 body: "Reuse one server for the full action.",
151 }),
152 },
153 ],
154 },
155 }
156 );
157 },
158 },
159 }) as unknown as ReturnType<
160 OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
161 >,
162 loadOpenCodeInventory: () =>
163 Effect.fail(
164 new OpenCodeRuntime.OpenCodeRuntimeError({
165 operation: "loadOpenCodeInventory",
166 detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
167 cause: null,
168 }),
169 ),
170 loadOpenCodeSkills: () => Effect.succeed([]),
171 loadInventoryFromCli: () =>
172 Effect.fail(
173 new OpenCodeRuntime.OpenCodeRuntimeError({
174 operation: "loadInventoryFromCli",
175 detail: "OpenCodeRuntimeTestDouble.loadInventoryFromCli not used in this test",
176 cause: null,
177 }),
178 ),
179 loadSkillsFromCli: () => Effect.succeed([]),
180};
181
182const DEFAULT_TEST_MODEL_SELECTION = {
183 instanceId: ProviderInstanceId.make("opencode"),
184 model: "openai/gpt-5",
185};
186const DEFAULT_COMMIT_MESSAGE_INPUT = {
187 cwd: process.cwd(),
188 branch: "feature/opencode-reuse",
189 stagedSummary: "M README.md",
190 stagedPatch: "diff --git a/README.md b/README.md",
191 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
192};
193
194const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
195
196const layerOpenCodeTextGenerationTest = Layer.succeed(
197 OpenCodeRuntime.OpenCodeRuntime,
198 OpenCodeRuntimeTestDouble,
199).pipe(
200 Layer.provideMerge(TestProviderHost.layer()),
201 Layer.provideMerge(NetService.layer),
202 Layer.provideMerge(NodeServices.layer),
203);
204
205const layerOpenCodeTextGenerationExistingServerTest = Layer.succeed(
206 OpenCodeRuntime.OpenCodeRuntime,
207 OpenCodeRuntimeTestDouble,
208).pipe(
209 Layer.provideMerge(TestProviderHost.layer()),
210 Layer.provideMerge(NetService.layer),
211 Layer.provideMerge(NodeServices.layer),
212);
213
214const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
215 binaryPath: "fake-opencode",
216});
217const LOCAL_AUTH_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
218 binaryPath: "fake-opencode",
219 serverPassword: "secret-password",
220});
221const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
222 binaryPath: "fake-opencode",
223 serverUrl: "http://127.0.0.1:9999",
224 serverPassword: "secret-password",
225});
226const EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
227 binaryPath: "fake-opencode",
228 serverUrl: "http://127.0.0.1:9999",
229});
230
231function withOpenCodeTextGeneration<A, E, R>(
232 settings: OpenCodeSettings,
233 effectFn: (textGeneration: ProviderTextGeneration) => Effect.Effect<A, E, R>,
234 environment?: NodeJS.ProcessEnv,
235) {
236 return Effect.gen(function* () {
237 const serverOwner = yield* OpenCodeServerOwner.make({
238 binaryPath: settings.binaryPath,
239 directory: process.cwd(),
240 ...(settings.serverPassword ? { serverPassword: settings.serverPassword } : {}),
241 ...(environment ? { environment } : {}),
242 });
243 const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings).pipe(
244 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
245 );
246 return yield* effectFn(textGeneration);
247 }).pipe(Effect.scoped);
248}
249
250beforeEach(() => {
251 runtimeMock.reset();
252});
253
254const advanceIdleClock = Effect.gen(function* () {
255 yield* Effect.yieldNow;
256 yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
257 yield* Effect.yieldNow;
258});
259
260it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => {
261 it.effect("cancels an in-flight session creation before prompting", () =>
262 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
263 Effect.gen(function* () {
264 const started = yield* Deferred.make<AbortSignal | undefined>();
265 runtimeMock.state.onSessionCreate = (signal) => {
266 Deferred.doneUnsafe(started, Effect.succeed(signal));
267 return new Promise<never>(() => {});
268 };
269 const fiber = yield* textGeneration
270 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
271 .pipe(Effect.forkChild);
272 const signal = yield* Deferred.await(started);
273 yield* Fiber.interrupt(fiber);
274
275 const exit = yield* Fiber.await(fiber);
276 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
277 expect(signal?.aborted).toBe(true);
278 expect(runtimeMock.state.promptUrls).toEqual([]);
279 expect(runtimeMock.state.abortCalls).toEqual([]);
280 }),
281 ),
282 );
283
284 it.effect("cancels only its prompt session while another generation uses the shared server", () =>
285 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
286 Effect.gen(function* () {
287 const started = yield* Deferred.make<AbortSignal | undefined>();
288 runtimeMock.state.sessionResult = { data: { id: "cancelled-session" } };
289 runtimeMock.state.onPrompt = (signal) => {
290 Deferred.doneUnsafe(started, Effect.succeed(signal));
291 return new Promise<never>(() => {});
292 };
293 const fiber = yield* textGeneration
294 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
295 .pipe(Effect.forkChild);
296 const signal = yield* Deferred.await(started);
297
298 const otherStarted = yield* Deferred.make<AbortSignal | undefined>();
299 const otherReply = Promise.withResolvers<{ data: { parts: ReadonlyArray<unknown> } }>();
300 runtimeMock.state.sessionResult = { data: { id: "other-session" } };
301 runtimeMock.state.onPrompt = (otherSignal) => {
302 Deferred.doneUnsafe(otherStarted, Effect.succeed(otherSignal));
303 return otherReply.promise;
304 };
305 const otherFiber = yield* textGeneration
306 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
307 .pipe(Effect.forkChild);
308 const otherSignal = yield* Deferred.await(otherStarted);
309 yield* Fiber.interrupt(fiber);
310
311 const exit = yield* Fiber.await(fiber);
312 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
313 expect(signal?.aborted).toBe(true);
314 expect(otherSignal?.aborted).toBe(false);
315 expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]);
316 expect(runtimeMock.state.closeCalls).toEqual([]);
317
318 otherReply.resolve({
319 data: {
320 parts: [{ type: "text", text: '{"subject":"Other generation completed","body":""}' }],
321 },
322 });
323 expect((yield* Fiber.join(otherFiber)).subject).toBe("Other generation completed");
324 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
325 expect(runtimeMock.state.promptUrls).toEqual([
326 "http://127.0.0.1:4301",
327 "http://127.0.0.1:4301",
328 ]);
329 expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]);
330 expect(runtimeMock.state.closeCalls).toEqual([]);
331 }),
332 ),
333 );
334
335 it.effect.each(["failure", "timeout"] as const)(
336 "preserves cancellation when the session abort ends in %s",
337 (outcome) => {
338 const messages: unknown[] = [];
339 const logger = Logger.make<unknown, void>(({ message }) => {
340 messages.push(message);
341 });
342 return withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
343 Effect.gen(function* () {
344 const promptStarted = yield* Deferred.make<AbortSignal | undefined>();
345 const abortStarted = yield* Deferred.make<AbortSignal | undefined>();
346 runtimeMock.state.onPrompt = (signal) => {
347 Deferred.doneUnsafe(promptStarted, Effect.succeed(signal));
348 return new Promise<never>(() => {});
349 };
350 runtimeMock.state.onAbort = (signal) => {
351 Deferred.doneUnsafe(abortStarted, Effect.succeed(signal));
352 return outcome === "failure"
353 ? Promise.reject(new Error("Synthetic SDK response: confidential-value"))
354 : new Promise<never>(() => {});
355 };
356 const fiber = yield* textGeneration
357 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
358 .pipe(Effect.forkChild);
359 const promptSignal = yield* Deferred.await(promptStarted);
360 const cancellation = yield* Fiber.interrupt(fiber).pipe(Effect.forkChild);
361 const abortSignal = yield* Deferred.await(abortStarted);
362 if (outcome === "timeout") {
363 yield* TestClock.adjust("10 seconds");
364 }
365 yield* Fiber.join(cancellation);
366
367 const exit = yield* Fiber.await(fiber);
368 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
369 expect(promptSignal?.aborted).toBe(true);
370 expect(runtimeMock.state.abortCalls).toEqual(["http://127.0.0.1:9999/session"]);
371 expect(runtimeMock.state.startCalls).toEqual([]);
372 expect(runtimeMock.state.closeCalls).toEqual([]);
373 if (outcome === "timeout") expect(abortSignal?.aborted).toBe(true);
374 expect(messages).toEqual([
375 [
376 "Failed to stop cancelled OpenCode text generation.",
377 {
378 operation: "generateCommitMessage",
379 cwd: DEFAULT_COMMIT_MESSAGE_INPUT.cwd,
380 sessionId: "http://127.0.0.1:9999/session",
381 providerId: "openai",
382 modelId: "gpt-5",
383 },
384 ],
385 ]);
386 }),
387 ).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
388 },
389 );
390
391 it.effect("excludes generic files from thread title generation", () =>
392 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
393 Effect.gen(function* () {
394 runtimeMock.state.promptResult = {
395 data: {
396 parts: [{ type: "text", text: '{"title":"Review uploaded report"}' }],
397 },
398 };
399
400 yield* textGeneration.generateThreadTitle({
401 cwd: process.cwd(),
402 message: "Review these attachments.",
403 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
404 attachments: [
405 {
406 type: "image",
407 id: "thread-image-attachment",
408 name: "screenshot.png",
409 mimeType: "image/png",
410 sizeBytes: 3,
411 },
412 {
413 type: "file",
414 id: "thread-report-attachment-pdf",
415 name: "report.pdf",
416 mimeType: "application/pdf",
417 sizeBytes: 42,
418 },
419 ],
420 });
421
422 expect(runtimeMock.state.promptParts[0]).toEqual([
423 expect.objectContaining({ type: "text" }),
424 expect.objectContaining({ type: "file", filename: "screenshot.png" }),
425 ]);
426 }),
427 ),
428 );
429
430 it.effect("passes configured authentication to a locally spawned server", () =>
431 withOpenCodeTextGeneration(LOCAL_AUTH_OPENCODE_SETTINGS, (textGeneration) =>
432 Effect.gen(function* () {
433 yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
434
435 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
436 expect(runtimeMock.state.authHeaders).toEqual([
437 `Basic ${btoa("opencode:secret-password")}`,
438 ]);
439 }),
440 ),
441 );
442
443 it.effect("uses an environment-only password for a locally spawned server", () =>
444 withOpenCodeTextGeneration(
445 DEFAULT_OPENCODE_SETTINGS,
446 (textGeneration) =>
447 Effect.gen(function* () {
448 yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
449
450 expect(runtimeMock.state.authHeaders).toEqual([
451 `Basic ${btoa("opencode:environment-password")}`,
452 ]);
453 }),
454 { OPENCODE_SERVER_PASSWORD: "environment-password" },
455 ),
456 );
457
458 it.effect("uses settings auth when the local environment password differs", () =>
459 withOpenCodeTextGeneration(
460 LOCAL_AUTH_OPENCODE_SETTINGS,
461 (textGeneration) =>
462 Effect.gen(function* () {
463 yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
464
465 expect(runtimeMock.state.authHeaders).toEqual([
466 `Basic ${btoa("opencode:secret-password")}`,
467 ]);
468 }),
469 { OPENCODE_SERVER_PASSWORD: "environment-password" },
470 ),
471 );
472
473 it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
474 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
475 Effect.gen(function* () {
476 yield* textGeneration.generateCommitMessage({
477 cwd: process.cwd(),
478 branch: "feature/opencode-reuse",
479 stagedSummary: "M README.md",
480 stagedPatch: "diff --git a/README.md b/README.md",
481 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
482 });
483 yield* textGeneration.generateCommitMessage({
484 cwd: process.cwd(),
485 branch: "feature/opencode-reuse",
486 stagedSummary: "M README.md",
487 stagedPatch: "diff --git a/README.md b/README.md",
488 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
489 });
490
491 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
492 expect(runtimeMock.state.promptUrls).toEqual([
493 "http://127.0.0.1:4301",
494 "http://127.0.0.1:4301",
495 ]);
496 expect(runtimeMock.state.closeCalls).toEqual([]);
497
498 yield* advanceIdleClock;
499
500 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
501 }),
502 ).pipe(Effect.provide(TestClock.layer())),
503 );
504
505 it.effect("starts a new server after the warm server idles out", () =>
506 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
507 Effect.gen(function* () {
508 yield* textGeneration.generateCommitMessage({
509 cwd: process.cwd(),
510 branch: "feature/opencode-reuse",
511 stagedSummary: "M README.md",
512 stagedPatch: "diff --git a/README.md b/README.md",
513 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
514 });
515
516 yield* advanceIdleClock;
517
518 yield* textGeneration.generateCommitMessage({
519 cwd: process.cwd(),
520 branch: "feature/opencode-reuse",
521 stagedSummary: "M README.md",
522 stagedPatch: "diff --git a/README.md b/README.md",
523 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
524 });
525
526 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
527 expect(runtimeMock.state.promptUrls).toEqual([
528 "http://127.0.0.1:4301",
529 "http://127.0.0.1:4302",
530 ]);
531 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
532 }),
533 ).pipe(Effect.provide(TestClock.layer())),
534 );
535
536 it.effect("preserves the SDK cause when session creation fails", () =>
537 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
538 Effect.gen(function* () {
539 const sdkCause = new Error("session endpoint unavailable");
540 runtimeMock.state.sessionCreateError = sdkCause;
541
542 const error = yield* textGeneration
543 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
544 .pipe(Effect.flip);
545
546 expect(error).toBeInstanceOf(TextGenerationError);
547 expect(error.message).toContain("OpenCode session.create request failed.");
548 expect(error.cause).toMatchObject({
549 _tag: "OpenCodeTextGenerationSessionRequestError",
550 operation: "generateCommitMessage",
551 cwd: process.cwd(),
552 cause: sdkCause,
553 });
554 expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
555 }),
556 ),
557 );
558
559 it.effect("reports a missing session payload without manufacturing a cause", () =>
560 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
561 Effect.gen(function* () {
562 runtimeMock.state.sessionResult = {};
563
564 const error = yield* textGeneration
565 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
566 .pipe(Effect.flip);
567
568 expect(error.message).toContain("OpenCode session.create returned no session payload.");
569 expect(error.cause).toMatchObject({
570 _tag: "OpenCodeTextGenerationSessionPayloadError",
571 operation: "generateCommitMessage",
572 cwd: process.cwd(),
573 });
574 expect(error.cause).not.toHaveProperty("cause");
575 }),
576 ),
577 );
578
579 it.effect("preserves the SDK cause and request context when prompting fails", () =>
580 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
581 Effect.gen(function* () {
582 const sdkCause = new Error("prompt endpoint unavailable");
583 runtimeMock.state.promptRequestError = sdkCause;
584
585 const error = yield* textGeneration
586 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
587 .pipe(Effect.flip);
588
589 expect(error.message).toContain("OpenCode session.prompt request failed.");
590 expect(error.cause).toMatchObject({
591 _tag: "OpenCodeTextGenerationPromptRequestError",
592 operation: "generateCommitMessage",
593 cwd: process.cwd(),
594 sessionId: "http://127.0.0.1:4301/session",
595 providerId: "openai",
596 modelId: "gpt-5",
597 cause: sdkCause,
598 });
599 expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
600 }),
601 ),
602 );
603
604 it.effect("returns a typed empty-output error for malformed and blank response parts", () =>
605 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
606 Effect.gen(function* () {
607 runtimeMock.state.promptResult = {
608 data: {
609 parts: [null, { type: "tool" }, { type: "text", text: " " }],
610 },
611 };
612
613 const error = yield* textGeneration
614 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
615 .pipe(Effect.flip);
616
617 expect(error.message).toContain("OpenCode returned empty output.");
618 expect(error.cause).toMatchObject({
619 _tag: "OpenCodeTextGenerationEmptyOutputError",
620 operation: "generateCommitMessage",
621 cwd: process.cwd(),
622 sessionId: "http://127.0.0.1:4301/session",
623 providerId: "openai",
624 modelId: "gpt-5",
625 responsePartCount: 3,
626 textPartCount: 1,
627 });
628 expect(error.cause).not.toHaveProperty("cause");
629 }),
630 ),
631 );
632
633 it.effect("parses JSON returned as plain text output", () =>
634 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
635 Effect.gen(function* () {
636 runtimeMock.state.promptResult = {
637 data: {
638 parts: [
639 {
640 type: "text",
641 text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
642 },
643 ],
644 },
645 };
646
647 const result = 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
655 expect(result).toEqual({
656 subject: "Tighten OpenCode parsing",
657 body: "Handle JSON text output locally.",
658 });
659 }),
660 ),
661 );
662
663 it.effect("surfaces the upstream OpenCode structured-output error message", () =>
664 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
665 Effect.gen(function* () {
666 runtimeMock.state.promptResult = {
667 data: {
668 info: {
669 error: {
670 name: "StructuredOutputError",
671 data: {
672 message: "Model did not produce structured output",
673 retries: 2,
674 },
675 },
676 },
677 },
678 };
679
680 const error = yield* textGeneration
681 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
682 .pipe(Effect.flip);
683
684 expect(error.message).toContain("Model did not produce structured output");
685 expect(error.cause).toMatchObject({
686 _tag: "OpenCodeTextGenerationPromptResponseError",
687 operation: "generateCommitMessage",
688 cwd: process.cwd(),
689 sessionId: "http://127.0.0.1:4301/session",
690 providerId: "openai",
691 modelId: "gpt-5",
692 providerErrorName: "StructuredOutputError",
693 providerMessage: "Model did not produce structured output",
694 });
695 expect(error.cause).not.toHaveProperty("cause");
696 }),
697 ),
698 );
699});
700
701it.layer(layerOpenCodeTextGenerationExistingServerTest)(
702 "OpenCodeTextGeneration with configured server URL",
703 (it) => {
704 it.effect("does not send a local environment password to a configured server", () =>
705 withOpenCodeTextGeneration(
706 EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS,
707 (textGeneration) =>
708 Effect.gen(function* () {
709 yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
710 expect(runtimeMock.state.authHeaders).toEqual([null]);
711 }),
712 { OPENCODE_SERVER_PASSWORD: "local-secret" },
713 ),
714 );
715
716 it.effect("does not create a session when the server version is unsupported", () =>
717 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
718 Effect.gen(function* () {
719 runtimeMock.state.connectionError = new Error(
720 "OpenCode v1.14.18 is too old. Upgrade to v1.14.19 or newer.",
721 );
722
723 const error = yield* textGeneration
724 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
725 .pipe(Effect.flip);
726
727 expect(error).toBeInstanceOf(TextGenerationError);
728 expect(error.message).toContain("v1.14.18 is too old");
729 expect(runtimeMock.state.sessionCreateCalls).toBe(0);
730 }),
731 ),
732 );
733
734 it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
735 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
736 Effect.gen(function* () {
737 yield* textGeneration.generateCommitMessage({
738 cwd: process.cwd(),
739 branch: "feature/opencode-reuse",
740 stagedSummary: "M README.md",
741 stagedPatch: "diff --git a/README.md b/README.md",
742 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
743 });
744 yield* textGeneration.generateCommitMessage({
745 cwd: process.cwd(),
746 branch: "feature/opencode-reuse",
747 stagedSummary: "M README.md",
748 stagedPatch: "diff --git a/README.md b/README.md",
749 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
750 });
751
752 expect(runtimeMock.state.startCalls).toEqual([]);
753 expect(runtimeMock.state.promptUrls).toEqual([
754 "http://127.0.0.1:9999",
755 "http://127.0.0.1:9999",
756 ]);
757 expect(runtimeMock.state.authHeaders).toEqual([
758 `Basic ${btoa("opencode:secret-password")}`,
759 `Basic ${btoa("opencode:secret-password")}`,
760 ]);
761
762 yield* advanceIdleClock;
763
764 expect(runtimeMock.state.closeCalls).toEqual([]);
765 }),
766 ).pipe(Effect.provide(TestClock.layer())),
767 );
768 },
769);