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