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