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