Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCodeTextGeneration.test.ts

340 lines11.0 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it } from "@effect/vitest";
3import { Duration, Effect, Layer } from "effect";
4import { TestClock } from "effect/testing";
5import { NetService } from "@t3tools/shared/Net";
6import { beforeEach, expect } from "vitest";
7​
8import { ServerConfig } from "../../config.ts";
9import { ServerSettingsService } from "../../serverSettings.ts";
10import {
11 OpenCodeRuntime,
12 OpenCodeRuntimeError,
13 type OpenCodeRuntimeShape,
14} from "../../provider/opencodeRuntime.ts";
15import { TextGeneration } from "../Services/TextGeneration.ts";
16import { OpenCodeTextGenerationLive } 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 provider: "opencode" as const,
101 model: "openai/gpt-5",
102};
103​
104const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
105​
106const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
107 Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
108 Layer.provideMerge(
109 ServerSettingsService.layerTest({
110 providers: {
111 opencode: {
112 binaryPath: "fake-opencode",
113 },
114 },
115 }),
116 ),
117 Layer.provideMerge(
118 ServerConfig.layerTest(process.cwd(), {
119 prefix: "t3code-opencode-text-generation-test-",
120 }),
121 ),
122 Layer.provideMerge(NetService.layer),
123 Layer.provideMerge(NodeServices.layer),
124);
125​
126const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
127 Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
128 Layer.provideMerge(
129 ServerSettingsService.layerTest({
130 providers: {
131 opencode: {
132 binaryPath: "fake-opencode",
133 serverUrl: "http://127.0.0.1:9999",
134 serverPassword: "secret-password",
135 },
136 },
137 }),
138 ),
139 Layer.provideMerge(
140 ServerConfig.layerTest(process.cwd(), {
141 prefix: "t3code-opencode-text-generation-existing-server-test-",
142 }),
143 ),
144 Layer.provideMerge(NetService.layer),
145 Layer.provideMerge(NodeServices.layer),
146);
147​
148beforeEach(() => {
149 runtimeMock.reset();
150});
151​
152const advanceIdleClock = Effect.gen(function* () {
153 yield* Effect.yieldNow;
154 yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
155 yield* Effect.yieldNow;
156});
157​
158it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
159 it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
160 Effect.gen(function* () {
161 const textGeneration = yield* TextGeneration;
162​
163 yield* textGeneration.generateCommitMessage({
164 cwd: process.cwd(),
165 branch: "feature/opencode-reuse",
166 stagedSummary: "M README.md",
167 stagedPatch: "diff --git a/README.md b/README.md",
168 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
169 });
170 yield* textGeneration.generateCommitMessage({
171 cwd: process.cwd(),
172 branch: "feature/opencode-reuse",
173 stagedSummary: "M README.md",
174 stagedPatch: "diff --git a/README.md b/README.md",
175 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
176 });
177​
178 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
179 expect(runtimeMock.state.promptUrls).toEqual([
180 "http://127.0.0.1:4301",
181 "http://127.0.0.1:4301",
182 ]);
183 expect(runtimeMock.state.closeCalls).toEqual([]);
184​
185 yield* advanceIdleClock;
186​
187 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
188 }).pipe(Effect.provide(TestClock.layer())),
189 );
190​
191 it.effect("starts a new server after the warm server idles out", () =>
192 Effect.gen(function* () {
193 const textGeneration = yield* TextGeneration;
194​
195 yield* textGeneration.generateCommitMessage({
196 cwd: process.cwd(),
197 branch: "feature/opencode-reuse",
198 stagedSummary: "M README.md",
199 stagedPatch: "diff --git a/README.md b/README.md",
200 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
201 });
202​
203 yield* advanceIdleClock;
204​
205 yield* textGeneration.generateCommitMessage({
206 cwd: process.cwd(),
207 branch: "feature/opencode-reuse",
208 stagedSummary: "M README.md",
209 stagedPatch: "diff --git a/README.md b/README.md",
210 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
211 });
212​
213 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
214 expect(runtimeMock.state.promptUrls).toEqual([
215 "http://127.0.0.1:4301",
216 "http://127.0.0.1:4302",
217 ]);
218 expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
219 }).pipe(Effect.provide(TestClock.layer())),
220 );
221​
222 it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
223 Effect.gen(function* () {
224 runtimeMock.state.promptResult = { data: {} };
225 const textGeneration = yield* TextGeneration;
226​
227 const error = yield* textGeneration
228 .generateCommitMessage({
229 cwd: process.cwd(),
230 branch: "feature/opencode-reuse",
231 stagedSummary: "M README.md",
232 stagedPatch: "diff --git a/README.md b/README.md",
233 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
234 })
235 .pipe(Effect.flip);
236​
237 expect(error.message).toContain("OpenCode returned empty output.");
238 }),
239 );
240​
241 it.effect("parses JSON returned as plain text output", () =>
242 Effect.gen(function* () {
243 runtimeMock.state.promptResult = {
244 data: {
245 parts: [
246 {
247 type: "text",
248 text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
249 },
250 ],
251 },
252 };
253 const textGeneration = yield* TextGeneration;
254​
255 const result = yield* textGeneration.generateCommitMessage({
256 cwd: process.cwd(),
257 branch: "feature/opencode-reuse",
258 stagedSummary: "M README.md",
259 stagedPatch: "diff --git a/README.md b/README.md",
260 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
261 });
262​
263 expect(result).toEqual({
264 subject: "Tighten OpenCode parsing",
265 body: "Handle JSON text output locally.",
266 });
267 }),
268 );
269​
270 it.effect("surfaces the upstream OpenCode structured-output error message", () =>
271 Effect.gen(function* () {
272 runtimeMock.state.promptResult = {
273 data: {
274 info: {
275 error: {
276 name: "StructuredOutputError",
277 data: {
278 message: "Model did not produce structured output",
279 retries: 2,
280 },
281 },
282 },
283 },
284 };
285 const textGeneration = yield* TextGeneration;
286​
287 const error = yield* textGeneration
288 .generateCommitMessage({
289 cwd: process.cwd(),
290 branch: "feature/opencode-reuse",
291 stagedSummary: "M README.md",
292 stagedPatch: "diff --git a/README.md b/README.md",
293 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
294 })
295 .pipe(Effect.flip);
296​
297 expect(error.message).toContain("Model did not produce structured output");
298 }),
299 );
300});
301​
302it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
303 "OpenCodeTextGenerationLive with configured server URL",
304 (it) => {
305 it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
306 Effect.gen(function* () {
307 const textGeneration = yield* TextGeneration;
308​
309 yield* textGeneration.generateCommitMessage({
310 cwd: process.cwd(),
311 branch: "feature/opencode-reuse",
312 stagedSummary: "M README.md",
313 stagedPatch: "diff --git a/README.md b/README.md",
314 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
315 });
316 yield* textGeneration.generateCommitMessage({
317 cwd: process.cwd(),
318 branch: "feature/opencode-reuse",
319 stagedSummary: "M README.md",
320 stagedPatch: "diff --git a/README.md b/README.md",
321 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
322 });
323​
324 expect(runtimeMock.state.startCalls).toEqual([]);
325 expect(runtimeMock.state.promptUrls).toEqual([
326 "http://127.0.0.1:9999",
327 "http://127.0.0.1:9999",
328 ]);
329 expect(runtimeMock.state.authHeaders).toEqual([
330 `Basic ${btoa("opencode:secret-password")}`,
331 `Basic ${btoa("opencode:secret-password")}`,
332 ]);
333​
334 yield* advanceIdleClock;
335​
336 expect(runtimeMock.state.closeCalls).toEqual([]);
337 }).pipe(Effect.provide(TestClock.layer())),
338 );
339 },
340);