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 OpenCodeTextGeneration from "./OpenCodeTextGeneration.ts";
15import * as TextGeneration from "./TextGeneration.ts";
16
17const runtimeMock = {
18 state: {
19 startCalls: [] as string[],
20 promptUrls: [] as string[],
21 authHeaders: [] as Array<string | null>,
22 closeCalls: [] as string[],
23 sessionCreateError: undefined as unknown,
24 sessionResult: undefined as { data?: { id: string } } | undefined,
25 promptRequestError: undefined as unknown,
26 promptResult: undefined as
27 | { data?: { info?: { error?: unknown }; parts?: Array<unknown> } }
28 | undefined,
29 },
30 reset() {
31 this.state.startCalls.length = 0;
32 this.state.promptUrls.length = 0;
33 this.state.authHeaders.length = 0;
34 this.state.closeCalls.length = 0;
35 this.state.sessionCreateError = undefined;
36 this.state.sessionResult = undefined;
37 this.state.promptRequestError = undefined;
38 this.state.promptResult = undefined;
39 },
40};
41
42const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
43 startOpenCodeServerProcess: ({ binaryPath }) =>
44 Effect.gen(function* () {
45 const index = runtimeMock.state.startCalls.length + 1;
46 const url = `http://127.0.0.1:${4_300 + index}`;
47 runtimeMock.state.startCalls.push(binaryPath);
48 // The production runtime binds server lifetime to the caller's scope.
49 // Mirror that here so the closeCalls probe observes scope close.
50 yield* Effect.addFinalizer(() =>
51 Effect.sync(() => {
52 runtimeMock.state.closeCalls.push(url);
53 }),
54 );
55 return {
56 url,
57 exitCode: Effect.never,
58 };
59 }),
60 connectToOpenCodeServer: ({ serverUrl }) =>
61 Effect.succeed({
62 url: serverUrl ?? "http://127.0.0.1:4301",
63 exitCode: null,
64 external: Boolean(serverUrl),
65 }),
66 runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
67 createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
68 ({
69 session: {
70 create: async () => {
71 if (runtimeMock.state.sessionCreateError !== undefined) {
72 throw runtimeMock.state.sessionCreateError;
73 }
74 return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } };
75 },
76 prompt: async () => {
77 runtimeMock.state.promptUrls.push(baseUrl);
78 runtimeMock.state.authHeaders.push(
79 serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
80 );
81 if (runtimeMock.state.promptRequestError !== undefined) {
82 throw runtimeMock.state.promptRequestError;
83 }
84 return (
85 runtimeMock.state.promptResult ?? {
86 data: {
87 parts: [
88 {
89 type: "text",
90 text: JSON.stringify({
91 subject: "Improve OpenCode reuse",
92 body: "Reuse one server for the full action.",
93 }),
94 },
95 ],
96 },
97 }
98 );
99 },
100 },
101 }) as unknown as ReturnType<OpenCodeRuntime.OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
102 loadOpenCodeInventory: () =>
103 Effect.fail(
104 new OpenCodeRuntime.OpenCodeRuntimeError({
105 operation: "loadOpenCodeInventory",
106 detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
107 cause: null,
108 }),
109 ),
110};
111
112const DEFAULT_TEST_MODEL_SELECTION = {
113 instanceId: ProviderInstanceId.make("opencode"),
114 model: "openai/gpt-5",
115};
116const DEFAULT_COMMIT_MESSAGE_INPUT = {
117 cwd: process.cwd(),
118 branch: "feature/opencode-reuse",
119 stagedSummary: "M README.md",
120 stagedPatch: "diff --git a/README.md b/README.md",
121 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
122};
123
124const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
125
126const OpenCodeTextGenerationTestLayer = Layer.succeed(
127 OpenCodeRuntime.OpenCodeRuntime,
128 OpenCodeRuntimeTestDouble,
129).pipe(
130 Layer.provideMerge(
131 ServerConfig.ServerConfig.layerTest(process.cwd(), {
132 prefix: "t3code-opencode-text-generation-test-",
133 }),
134 ),
135 Layer.provideMerge(NetService.layer),
136 Layer.provideMerge(NodeServices.layer),
137);
138
139const OpenCodeTextGenerationExistingServerTestLayer = Layer.succeed(
140 OpenCodeRuntime.OpenCodeRuntime,
141 OpenCodeRuntimeTestDouble,
142).pipe(
143 Layer.provideMerge(
144 ServerConfig.ServerConfig.layerTest(process.cwd(), {
145 prefix: "t3code-opencode-text-generation-existing-server-test-",
146 }),
147 ),
148 Layer.provideMerge(NetService.layer),
149 Layer.provideMerge(NodeServices.layer),
150);
151
152const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
153 binaryPath: "fake-opencode",
154});
155const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
156 binaryPath: "fake-opencode",
157 serverUrl: "http://127.0.0.1:9999",
158 serverPassword: "secret-password",
159});
160
161function withOpenCodeTextGeneration<A, E, R>(
162 settings: OpenCodeSettings,
163 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
164) {
165 return Effect.gen(function* () {
166 const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings);
167 return yield* effectFn(textGeneration);
168 }).pipe(Effect.scoped);
169}
170
171beforeEach(() => {
172 runtimeMock.reset();
173});
174
175const advanceIdleClock = Effect.gen(function* () {
176 yield* Effect.yieldNow;
177 yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
178 yield* Effect.yieldNow;
179});
180
181it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
182 it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
183 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
184 Effect.gen(function* () {
185 yield* textGeneration.generateCommitMessage({
186 cwd: process.cwd(),
187 branch: "feature/opencode-reuse",
188 stagedSummary: "M README.md",
189 stagedPatch: "diff --git a/README.md b/README.md",
190 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
191 });
192 yield* textGeneration.generateCommitMessage({
193 cwd: process.cwd(),
194 branch: "feature/opencode-reuse",
195 stagedSummary: "M README.md",
196 stagedPatch: "diff --git a/README.md b/README.md",
197 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
198 });
199
200 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
201 expect(runtimeMock.state.promptUrls).toEqual([
202 "http://127.0.0.1:4301",
203 "http://127.0.0.1:4301",
204 ]);
205 expect(runtimeMock.state.closeCalls).toEqual([]);
206
207 yield* advanceIdleClock;
208
209 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
210 }),
211 ).pipe(Effect.provide(TestClock.layer())),
212 );
213
214 it.effect("starts a new server after the warm server idles out", () =>
215 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
216 Effect.gen(function* () {
217 yield* textGeneration.generateCommitMessage({
218 cwd: process.cwd(),
219 branch: "feature/opencode-reuse",
220 stagedSummary: "M README.md",
221 stagedPatch: "diff --git a/README.md b/README.md",
222 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
223 });
224
225 yield* advanceIdleClock;
226
227 yield* textGeneration.generateCommitMessage({
228 cwd: process.cwd(),
229 branch: "feature/opencode-reuse",
230 stagedSummary: "M README.md",
231 stagedPatch: "diff --git a/README.md b/README.md",
232 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
233 });
234
235 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
236 expect(runtimeMock.state.promptUrls).toEqual([
237 "http://127.0.0.1:4301",
238 "http://127.0.0.1:4302",
239 ]);
240 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
241 }),
242 ).pipe(Effect.provide(TestClock.layer())),
243 );
244
245 it.effect("preserves the SDK cause when session creation fails", () =>
246 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
247 Effect.gen(function* () {
248 const sdkCause = new Error("session endpoint unavailable");
249 runtimeMock.state.sessionCreateError = sdkCause;
250
251 const error = yield* textGeneration
252 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
253 .pipe(Effect.flip);
254
255 expect(error).toBeInstanceOf(TextGenerationError);
256 expect(error.message).toContain("OpenCode session.create request failed.");
257 expect(error.cause).toMatchObject({
258 _tag: "OpenCodeTextGenerationSessionRequestError",
259 operation: "generateCommitMessage",
260 cwd: process.cwd(),
261 cause: sdkCause,
262 });
263 expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
264 }),
265 ),
266 );
267
268 it.effect("reports a missing session payload without manufacturing a cause", () =>
269 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
270 Effect.gen(function* () {
271 runtimeMock.state.sessionResult = {};
272
273 const error = yield* textGeneration
274 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
275 .pipe(Effect.flip);
276
277 expect(error.message).toContain("OpenCode session.create returned no session payload.");
278 expect(error.cause).toMatchObject({
279 _tag: "OpenCodeTextGenerationSessionPayloadError",
280 operation: "generateCommitMessage",
281 cwd: process.cwd(),
282 });
283 expect(error.cause).not.toHaveProperty("cause");
284 }),
285 ),
286 );
287
288 it.effect("preserves the SDK cause and request context when prompting fails", () =>
289 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
290 Effect.gen(function* () {
291 const sdkCause = new Error("prompt endpoint unavailable");
292 runtimeMock.state.promptRequestError = sdkCause;
293
294 const error = yield* textGeneration
295 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
296 .pipe(Effect.flip);
297
298 expect(error.message).toContain("OpenCode session.prompt request failed.");
299 expect(error.cause).toMatchObject({
300 _tag: "OpenCodeTextGenerationPromptRequestError",
301 operation: "generateCommitMessage",
302 cwd: process.cwd(),
303 sessionId: "http://127.0.0.1:4301/session",
304 providerId: "openai",
305 modelId: "gpt-5",
306 cause: sdkCause,
307 });
308 expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
309 }),
310 ),
311 );
312
313 it.effect("returns a typed empty-output error for malformed and blank response parts", () =>
314 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
315 Effect.gen(function* () {
316 runtimeMock.state.promptResult = {
317 data: {
318 parts: [null, { type: "tool" }, { type: "text", text: " " }],
319 },
320 };
321
322 const error = yield* textGeneration
323 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
324 .pipe(Effect.flip);
325
326 expect(error.message).toContain("OpenCode returned empty output.");
327 expect(error.cause).toMatchObject({
328 _tag: "OpenCodeTextGenerationEmptyOutputError",
329 operation: "generateCommitMessage",
330 cwd: process.cwd(),
331 sessionId: "http://127.0.0.1:4301/session",
332 providerId: "openai",
333 modelId: "gpt-5",
334 responsePartCount: 3,
335 textPartCount: 1,
336 });
337 expect(error.cause).not.toHaveProperty("cause");
338 }),
339 ),
340 );
341
342 it.effect("parses JSON returned as plain text output", () =>
343 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
344 Effect.gen(function* () {
345 runtimeMock.state.promptResult = {
346 data: {
347 parts: [
348 {
349 type: "text",
350 text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
351 },
352 ],
353 },
354 };
355
356 const result = 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(result).toEqual({
365 subject: "Tighten OpenCode parsing",
366 body: "Handle JSON text output locally.",
367 });
368 }),
369 ),
370 );
371
372 it.effect("surfaces the upstream OpenCode structured-output error message", () =>
373 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
374 Effect.gen(function* () {
375 runtimeMock.state.promptResult = {
376 data: {
377 info: {
378 error: {
379 name: "StructuredOutputError",
380 data: {
381 message: "Model did not produce structured output",
382 retries: 2,
383 },
384 },
385 },
386 },
387 };
388
389 const error = yield* textGeneration
390 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
391 .pipe(Effect.flip);
392
393 expect(error.message).toContain("Model did not produce structured output");
394 expect(error.cause).toMatchObject({
395 _tag: "OpenCodeTextGenerationPromptResponseError",
396 operation: "generateCommitMessage",
397 cwd: process.cwd(),
398 sessionId: "http://127.0.0.1:4301/session",
399 providerId: "openai",
400 modelId: "gpt-5",
401 providerErrorName: "StructuredOutputError",
402 providerMessage: "Model did not produce structured output",
403 });
404 expect(error.cause).not.toHaveProperty("cause");
405 }),
406 ),
407 );
408});
409
410it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
411 "OpenCodeTextGeneration with configured server URL",
412 (it) => {
413 it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
414 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
415 Effect.gen(function* () {
416 yield* textGeneration.generateCommitMessage({
417 cwd: process.cwd(),
418 branch: "feature/opencode-reuse",
419 stagedSummary: "M README.md",
420 stagedPatch: "diff --git a/README.md b/README.md",
421 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
422 });
423 yield* textGeneration.generateCommitMessage({
424 cwd: process.cwd(),
425 branch: "feature/opencode-reuse",
426 stagedSummary: "M README.md",
427 stagedPatch: "diff --git a/README.md b/README.md",
428 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
429 });
430
431 expect(runtimeMock.state.startCalls).toEqual([]);
432 expect(runtimeMock.state.promptUrls).toEqual([
433 "http://127.0.0.1:9999",
434 "http://127.0.0.1:9999",
435 ]);
436 expect(runtimeMock.state.authHeaders).toEqual([
437 `Basic ${btoa("opencode:secret-password")}`,
438 `Basic ${btoa("opencode:secret-password")}`,
439 ]);
440
441 yield* advanceIdleClock;
442
443 expect(runtimeMock.state.closeCalls).toEqual([]);
444 }),
445 ).pipe(Effect.provide(TestClock.layer())),
446 );
447 },
448);