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