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 loadInventoryFromCli: () =>
111 Effect.fail(
112 new OpenCodeRuntime.OpenCodeRuntimeError({
113 operation: "loadInventoryFromCli",
114 detail: "OpenCodeRuntimeTestDouble.loadInventoryFromCli not used in this test",
115 cause: null,
116 }),
117 ),
118};
119
120const DEFAULT_TEST_MODEL_SELECTION = {
121 instanceId: ProviderInstanceId.make("opencode"),
122 model: "openai/gpt-5",
123};
124const DEFAULT_COMMIT_MESSAGE_INPUT = {
125 cwd: process.cwd(),
126 branch: "feature/opencode-reuse",
127 stagedSummary: "M README.md",
128 stagedPatch: "diff --git a/README.md b/README.md",
129 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
130};
131
132const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
133
134const OpenCodeTextGenerationTestLayer = Layer.succeed(
135 OpenCodeRuntime.OpenCodeRuntime,
136 OpenCodeRuntimeTestDouble,
137).pipe(
138 Layer.provideMerge(
139 ServerConfig.ServerConfig.layerTest(process.cwd(), {
140 prefix: "t3code-opencode-text-generation-test-",
141 }),
142 ),
143 Layer.provideMerge(NetService.layer),
144 Layer.provideMerge(NodeServices.layer),
145);
146
147const OpenCodeTextGenerationExistingServerTestLayer = Layer.succeed(
148 OpenCodeRuntime.OpenCodeRuntime,
149 OpenCodeRuntimeTestDouble,
150).pipe(
151 Layer.provideMerge(
152 ServerConfig.ServerConfig.layerTest(process.cwd(), {
153 prefix: "t3code-opencode-text-generation-existing-server-test-",
154 }),
155 ),
156 Layer.provideMerge(NetService.layer),
157 Layer.provideMerge(NodeServices.layer),
158);
159
160const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
161 binaryPath: "fake-opencode",
162});
163const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
164 binaryPath: "fake-opencode",
165 serverUrl: "http://127.0.0.1:9999",
166 serverPassword: "secret-password",
167});
168
169function withOpenCodeTextGeneration<A, E, R>(
170 settings: OpenCodeSettings,
171 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
172) {
173 return Effect.gen(function* () {
174 const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings);
175 return yield* effectFn(textGeneration);
176 }).pipe(Effect.scoped);
177}
178
179beforeEach(() => {
180 runtimeMock.reset();
181});
182
183const advanceIdleClock = Effect.gen(function* () {
184 yield* Effect.yieldNow;
185 yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
186 yield* Effect.yieldNow;
187});
188
189it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
190 it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
191 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
192 Effect.gen(function* () {
193 yield* textGeneration.generateCommitMessage({
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 yield* textGeneration.generateCommitMessage({
201 cwd: process.cwd(),
202 branch: "feature/opencode-reuse",
203 stagedSummary: "M README.md",
204 stagedPatch: "diff --git a/README.md b/README.md",
205 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
206 });
207
208 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
209 expect(runtimeMock.state.promptUrls).toEqual([
210 "http://127.0.0.1:4301",
211 "http://127.0.0.1:4301",
212 ]);
213 expect(runtimeMock.state.closeCalls).toEqual([]);
214
215 yield* advanceIdleClock;
216
217 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
218 }),
219 ).pipe(Effect.provide(TestClock.layer())),
220 );
221
222 it.effect("starts a new server after the warm server idles out", () =>
223 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
224 Effect.gen(function* () {
225 yield* textGeneration.generateCommitMessage({
226 cwd: process.cwd(),
227 branch: "feature/opencode-reuse",
228 stagedSummary: "M README.md",
229 stagedPatch: "diff --git a/README.md b/README.md",
230 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
231 });
232
233 yield* advanceIdleClock;
234
235 yield* textGeneration.generateCommitMessage({
236 cwd: process.cwd(),
237 branch: "feature/opencode-reuse",
238 stagedSummary: "M README.md",
239 stagedPatch: "diff --git a/README.md b/README.md",
240 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
241 });
242
243 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
244 expect(runtimeMock.state.promptUrls).toEqual([
245 "http://127.0.0.1:4301",
246 "http://127.0.0.1:4302",
247 ]);
248 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
249 }),
250 ).pipe(Effect.provide(TestClock.layer())),
251 );
252
253 it.effect("preserves the SDK cause when session creation fails", () =>
254 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
255 Effect.gen(function* () {
256 const sdkCause = new Error("session endpoint unavailable");
257 runtimeMock.state.sessionCreateError = sdkCause;
258
259 const error = yield* textGeneration
260 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
261 .pipe(Effect.flip);
262
263 expect(error).toBeInstanceOf(TextGenerationError);
264 expect(error.message).toContain("OpenCode session.create request failed.");
265 expect(error.cause).toMatchObject({
266 _tag: "OpenCodeTextGenerationSessionRequestError",
267 operation: "generateCommitMessage",
268 cwd: process.cwd(),
269 cause: sdkCause,
270 });
271 expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
272 }),
273 ),
274 );
275
276 it.effect("reports a missing session payload without manufacturing a cause", () =>
277 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
278 Effect.gen(function* () {
279 runtimeMock.state.sessionResult = {};
280
281 const error = yield* textGeneration
282 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
283 .pipe(Effect.flip);
284
285 expect(error.message).toContain("OpenCode session.create returned no session payload.");
286 expect(error.cause).toMatchObject({
287 _tag: "OpenCodeTextGenerationSessionPayloadError",
288 operation: "generateCommitMessage",
289 cwd: process.cwd(),
290 });
291 expect(error.cause).not.toHaveProperty("cause");
292 }),
293 ),
294 );
295
296 it.effect("preserves the SDK cause and request context when prompting fails", () =>
297 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
298 Effect.gen(function* () {
299 const sdkCause = new Error("prompt endpoint unavailable");
300 runtimeMock.state.promptRequestError = sdkCause;
301
302 const error = yield* textGeneration
303 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
304 .pipe(Effect.flip);
305
306 expect(error.message).toContain("OpenCode session.prompt request failed.");
307 expect(error.cause).toMatchObject({
308 _tag: "OpenCodeTextGenerationPromptRequestError",
309 operation: "generateCommitMessage",
310 cwd: process.cwd(),
311 sessionId: "http://127.0.0.1:4301/session",
312 providerId: "openai",
313 modelId: "gpt-5",
314 cause: sdkCause,
315 });
316 expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
317 }),
318 ),
319 );
320
321 it.effect("returns a typed empty-output error for malformed and blank response parts", () =>
322 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
323 Effect.gen(function* () {
324 runtimeMock.state.promptResult = {
325 data: {
326 parts: [null, { type: "tool" }, { type: "text", text: " " }],
327 },
328 };
329
330 const error = yield* textGeneration
331 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
332 .pipe(Effect.flip);
333
334 expect(error.message).toContain("OpenCode returned empty output.");
335 expect(error.cause).toMatchObject({
336 _tag: "OpenCodeTextGenerationEmptyOutputError",
337 operation: "generateCommitMessage",
338 cwd: process.cwd(),
339 sessionId: "http://127.0.0.1:4301/session",
340 providerId: "openai",
341 modelId: "gpt-5",
342 responsePartCount: 3,
343 textPartCount: 1,
344 });
345 expect(error.cause).not.toHaveProperty("cause");
346 }),
347 ),
348 );
349
350 it.effect("parses JSON returned as plain text output", () =>
351 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
352 Effect.gen(function* () {
353 runtimeMock.state.promptResult = {
354 data: {
355 parts: [
356 {
357 type: "text",
358 text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
359 },
360 ],
361 },
362 };
363
364 const result = yield* textGeneration.generateCommitMessage({
365 cwd: process.cwd(),
366 branch: "feature/opencode-reuse",
367 stagedSummary: "M README.md",
368 stagedPatch: "diff --git a/README.md b/README.md",
369 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
370 });
371
372 expect(result).toEqual({
373 subject: "Tighten OpenCode parsing",
374 body: "Handle JSON text output locally.",
375 });
376 }),
377 ),
378 );
379
380 it.effect("surfaces the upstream OpenCode structured-output error message", () =>
381 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
382 Effect.gen(function* () {
383 runtimeMock.state.promptResult = {
384 data: {
385 info: {
386 error: {
387 name: "StructuredOutputError",
388 data: {
389 message: "Model did not produce structured output",
390 retries: 2,
391 },
392 },
393 },
394 },
395 };
396
397 const error = yield* textGeneration
398 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
399 .pipe(Effect.flip);
400
401 expect(error.message).toContain("Model did not produce structured output");
402 expect(error.cause).toMatchObject({
403 _tag: "OpenCodeTextGenerationPromptResponseError",
404 operation: "generateCommitMessage",
405 cwd: process.cwd(),
406 sessionId: "http://127.0.0.1:4301/session",
407 providerId: "openai",
408 modelId: "gpt-5",
409 providerErrorName: "StructuredOutputError",
410 providerMessage: "Model did not produce structured output",
411 });
412 expect(error.cause).not.toHaveProperty("cause");
413 }),
414 ),
415 );
416});
417
418it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
419 "OpenCodeTextGeneration with configured server URL",
420 (it) => {
421 it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
422 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
423 Effect.gen(function* () {
424 yield* textGeneration.generateCommitMessage({
425 cwd: process.cwd(),
426 branch: "feature/opencode-reuse",
427 stagedSummary: "M README.md",
428 stagedPatch: "diff --git a/README.md b/README.md",
429 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
430 });
431 yield* textGeneration.generateCommitMessage({
432 cwd: process.cwd(),
433 branch: "feature/opencode-reuse",
434 stagedSummary: "M README.md",
435 stagedPatch: "diff --git a/README.md b/README.md",
436 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
437 });
438
439 expect(runtimeMock.state.startCalls).toEqual([]);
440 expect(runtimeMock.state.promptUrls).toEqual([
441 "http://127.0.0.1:9999",
442 "http://127.0.0.1:9999",
443 ]);
444 expect(runtimeMock.state.authHeaders).toEqual([
445 `Basic ${btoa("opencode:secret-password")}`,
446 `Basic ${btoa("opencode:secret-password")}`,
447 ]);
448
449 yield* advanceIdleClock;
450
451 expect(runtimeMock.state.closeCalls).toEqual([]);
452 }),
453 ).pipe(Effect.provide(TestClock.layer())),
454 );
455 },
456);