Open History to see the last commit
1import { OpenCodeSettings, ProviderInstanceId } from "@t3tools/contracts";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { it } from "@effect/vitest";
4import { Duration, Effect, Layer, Schema } from "effect";
5import { TestClock } from "effect/testing";
6import { NetService } from "@t3tools/shared/Net";
7import { beforeEach, expect } from "vitest";
8
9import { ServerConfig } from "../../config.ts";
10import {
11 OpenCodeRuntime,
12 OpenCodeRuntimeError,
13 type OpenCodeRuntimeShape,
14} from "../../provider/opencodeRuntime.ts";
15import { type TextGenerationShape } from "../Services/TextGeneration.ts";
16import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts";
17
18const runtimeMock = {
19 state: {
20 startCalls: [] as string[],
21 promptUrls: [] as string[],
22 authHeaders: [] as Array<string | null>,
23 closeCalls: [] as string[],
24 promptResult: undefined as
25 | { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
26 | undefined,
27 },
28 reset() {
29 this.state.startCalls.length = 0;
30 this.state.promptUrls.length = 0;
31 this.state.authHeaders.length = 0;
32 this.state.closeCalls.length = 0;
33 this.state.promptResult = undefined;
34 },
35};
36
37const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
38 startOpenCodeServerProcess: ({ binaryPath }) =>
39 Effect.gen(function* () {
40 const index = runtimeMock.state.startCalls.length + 1;
41 const url = `http://127.0.0.1:${4_300 + index}`;
42 runtimeMock.state.startCalls.push(binaryPath);
43 // The production runtime binds server lifetime to the caller's scope.
44 // Mirror that here so the closeCalls probe observes scope close.
45 yield* Effect.addFinalizer(() =>
46 Effect.sync(() => {
47 runtimeMock.state.closeCalls.push(url);
48 }),
49 );
50 return {
51 url,
52 exitCode: Effect.never,
53 };
54 }),
55 connectToOpenCodeServer: ({ serverUrl }) =>
56 Effect.succeed({
57 url: serverUrl ?? "http://127.0.0.1:4301",
58 exitCode: null,
59 external: Boolean(serverUrl),
60 }),
61 runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
62 createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
63 ({
64 session: {
65 create: async () => ({ data: { id: `${baseUrl}/session` } }),
66 prompt: async () => {
67 runtimeMock.state.promptUrls.push(baseUrl);
68 runtimeMock.state.authHeaders.push(
69 serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
70 );
71 return (
72 runtimeMock.state.promptResult ?? {
73 data: {
74 parts: [
75 {
76 type: "text",
77 text: JSON.stringify({
78 subject: "Improve OpenCode reuse",
79 body: "Reuse one server for the full action.",
80 }),
81 },
82 ],
83 },
84 }
85 );
86 },
87 },
88 }) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
89 loadOpenCodeInventory: () =>
90 Effect.fail(
91 new OpenCodeRuntimeError({
92 operation: "loadOpenCodeInventory",
93 detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
94 cause: null,
95 }),
96 ),
97};
98
99const DEFAULT_TEST_MODEL_SELECTION = {
100 instanceId: ProviderInstanceId.make("opencode"),
101 model: "openai/gpt-5",
102};
103
104const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
105
106const OpenCodeTextGenerationTestLayer = Layer.succeed(
107 OpenCodeRuntime,
108 OpenCodeRuntimeTestDouble,
109).pipe(
110 Layer.provideMerge(
111 ServerConfig.layerTest(process.cwd(), {
112 prefix: "t3code-opencode-text-generation-test-",
113 }),
114 ),
115 Layer.provideMerge(NetService.layer),
116 Layer.provideMerge(NodeServices.layer),
117);
118
119const OpenCodeTextGenerationExistingServerTestLayer = Layer.succeed(
120 OpenCodeRuntime,
121 OpenCodeRuntimeTestDouble,
122).pipe(
123 Layer.provideMerge(
124 ServerConfig.layerTest(process.cwd(), {
125 prefix: "t3code-opencode-text-generation-existing-server-test-",
126 }),
127 ),
128 Layer.provideMerge(NetService.layer),
129 Layer.provideMerge(NodeServices.layer),
130);
131
132const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
133 binaryPath: "fake-opencode",
134});
135const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
136 binaryPath: "fake-opencode",
137 serverUrl: "http://127.0.0.1:9999",
138 serverPassword: "secret-password",
139});
140
141function withOpenCodeTextGeneration<A, E, R>(
142 settings: OpenCodeSettings,
143 effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
144) {
145 return Effect.gen(function* () {
146 const textGeneration = yield* makeOpenCodeTextGeneration(settings);
147 return yield* effectFn(textGeneration);
148 }).pipe(Effect.scoped);
149}
150
151beforeEach(() => {
152 runtimeMock.reset();
153});
154
155const advanceIdleClock = Effect.gen(function* () {
156 yield* Effect.yieldNow;
157 yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
158 yield* Effect.yieldNow;
159});
160
161it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
162 it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
163 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
164 Effect.gen(function* () {
165 yield* textGeneration.generateCommitMessage({
166 cwd: process.cwd(),
167 branch: "feature/opencode-reuse",
168 stagedSummary: "M README.md",
169 stagedPatch: "diff --git a/README.md b/README.md",
170 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
171 });
172 yield* textGeneration.generateCommitMessage({
173 cwd: process.cwd(),
174 branch: "feature/opencode-reuse",
175 stagedSummary: "M README.md",
176 stagedPatch: "diff --git a/README.md b/README.md",
177 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
178 });
179
180 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
181 expect(runtimeMock.state.promptUrls).toEqual([
182 "http://127.0.0.1:4301",
183 "http://127.0.0.1:4301",
184 ]);
185 expect(runtimeMock.state.closeCalls).toEqual([]);
186
187 yield* advanceIdleClock;
188
189 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
190 }),
191 ).pipe(Effect.provide(TestClock.layer())),
192 );
193
194 it.effect("starts a new server after the warm server idles out", () =>
195 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
196 Effect.gen(function* () {
197 yield* textGeneration.generateCommitMessage({
198 cwd: process.cwd(),
199 branch: "feature/opencode-reuse",
200 stagedSummary: "M README.md",
201 stagedPatch: "diff --git a/README.md b/README.md",
202 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
203 });
204
205 yield* advanceIdleClock;
206
207 yield* textGeneration.generateCommitMessage({
208 cwd: process.cwd(),
209 branch: "feature/opencode-reuse",
210 stagedSummary: "M README.md",
211 stagedPatch: "diff --git a/README.md b/README.md",
212 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
213 });
214
215 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
216 expect(runtimeMock.state.promptUrls).toEqual([
217 "http://127.0.0.1:4301",
218 "http://127.0.0.1:4302",
219 ]);
220 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
221 }),
222 ).pipe(Effect.provide(TestClock.layer())),
223 );
224
225 it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
226 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
227 Effect.gen(function* () {
228 runtimeMock.state.promptResult = { data: {} };
229
230 const error = yield* textGeneration
231 .generateCommitMessage({
232 cwd: process.cwd(),
233 branch: "feature/opencode-reuse",
234 stagedSummary: "M README.md",
235 stagedPatch: "diff --git a/README.md b/README.md",
236 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
237 })
238 .pipe(Effect.flip);
239
240 expect(error.message).toContain("OpenCode returned empty output.");
241 }),
242 ),
243 );
244
245 it.effect("parses JSON returned as plain text output", () =>
246 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
247 Effect.gen(function* () {
248 runtimeMock.state.promptResult = {
249 data: {
250 parts: [
251 {
252 type: "text",
253 text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
254 },
255 ],
256 },
257 };
258
259 const result = yield* textGeneration.generateCommitMessage({
260 cwd: process.cwd(),
261 branch: "feature/opencode-reuse",
262 stagedSummary: "M README.md",
263 stagedPatch: "diff --git a/README.md b/README.md",
264 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
265 });
266
267 expect(result).toEqual({
268 subject: "Tighten OpenCode parsing",
269 body: "Handle JSON text output locally.",
270 });
271 }),
272 ),
273 );
274
275 it.effect("surfaces the upstream OpenCode structured-output error message", () =>
276 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
277 Effect.gen(function* () {
278 runtimeMock.state.promptResult = {
279 data: {
280 info: {
281 error: {
282 name: "StructuredOutputError",
283 data: {
284 message: "Model did not produce structured output",
285 retries: 2,
286 },
287 },
288 },
289 },
290 };
291
292 const error = yield* textGeneration
293 .generateCommitMessage({
294 cwd: process.cwd(),
295 branch: "feature/opencode-reuse",
296 stagedSummary: "M README.md",
297 stagedPatch: "diff --git a/README.md b/README.md",
298 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
299 })
300 .pipe(Effect.flip);
301
302 expect(error.message).toContain("Model did not produce structured output");
303 }),
304 ),
305 );
306});
307
308it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
309 "OpenCodeTextGenerationLive with configured server URL",
310 (it) => {
311 it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
312 withOpenCodeTextGeneration(EXISTING_SERVER_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([]);
330 expect(runtimeMock.state.promptUrls).toEqual([
331 "http://127.0.0.1:9999",
332 "http://127.0.0.1:9999",
333 ]);
334 expect(runtimeMock.state.authHeaders).toEqual([
335 `Basic ${btoa("opencode:secret-password")}`,
336 `Basic ${btoa("opencode:secret-password")}`,
337 ]);
338
339 yield* advanceIdleClock;
340
341 expect(runtimeMock.state.closeCalls).toEqual([]);
342 }),
343 ).pipe(Effect.provide(TestClock.layer())),
344 );
345 },
346);