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