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

textGeneration.test.ts

503 lines18.8 KB

1import { ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
2import { OpenCodeSettings } from "../settings.ts";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { it } from "@effect/vitest";
5import * as Cause from "effect/Cause";
6import * as Deferred from "effect/Deferred";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
11import * as Layer from "effect/Layer";
12import * as Schema from "effect/Schema";
13import * as TestClock from "effect/testing/TestClock";
14import * as NetService from "@t3tools/shared/Net";
15import { beforeEach, expect } from "vite-plus/test";
16​
17import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
18import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
19import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
20import * as OpenCodeTextGeneration from "./textGeneration.ts";
21import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
22​
23const runtimeMock = {
24 state: {
25 startCalls: [] as string[],
26 promptUrls: [] as string[],
27 promptParts: [] as ReadonlyArray<unknown>[],
28 authHeaders: [] as Array<string | null>,
29 closeCalls: [] as string[],
30 sessionCreateCalls: 0,
31 abortCalls: [] as string[],
32 onSessionCreate: undefined as ((signal?: AbortSignal) => Promise<never>) | undefined,
33 onPrompt: undefined as
34 | ((signal?: AbortSignal) => Promise<{ data: { parts: ReadonlyArray<unknown> } }>)
35 | undefined,
36 onAbort: undefined as ((signal?: AbortSignal) => Promise<never>) | undefined,
37 connectionError: undefined as Error | undefined,
38 sessionCreateError: undefined as unknown,
39 sessionResult: undefined as { data?: { id: string } } | undefined,
40 promptRequestError: undefined as unknown,
41 promptResult: undefined as
42 | { data?: { info?: { error?: unknown }; parts?: Array<unknown> } }
43 | undefined,
44 },
45 reset() {
46 this.state.startCalls.length = 0;
47 this.state.promptUrls.length = 0;
48 this.state.promptParts.length = 0;
49 this.state.authHeaders.length = 0;
50 this.state.closeCalls.length = 0;
51 this.state.sessionCreateCalls = 0;
52 this.state.abortCalls.length = 0;
53 this.state.onSessionCreate = undefined;
54 this.state.onPrompt = undefined;
55 this.state.onAbort = undefined;
56 this.state.connectionError = undefined;
57 this.state.sessionCreateError = undefined;
58 this.state.sessionResult = undefined;
59 this.state.promptRequestError = undefined;
60 this.state.promptResult = undefined;
61 },
62};
63​
64const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
65 startOpenCodeServerProcess: ({ binaryPath, serverPassword, environment }) =>
66 Effect.gen(function* () {
67 const index = runtimeMock.state.startCalls.length + 1;
68 const url = `http://127.0.0.1:${4_300 + index}`;
69 runtimeMock.state.startCalls.push(binaryPath);
70 yield* Effect.addFinalizer(() =>
71 Effect.sync(() => {
72 runtimeMock.state.closeCalls.push(url);
73 }),
74 );
75 const effectiveServerPassword = OpenCodeRuntime.resolveOpenCodeServerPassword({
76 external: false,
77 ...(serverPassword !== undefined ? { serverPassword } : {}),
78 ...(environment !== undefined ? { environment } : {}),
79 });
80 return {
81 url,
82 ...(effectiveServerPassword !== undefined
83 ? { serverPassword: effectiveServerPassword }
84 : {}),
85 version: "1.14.19",
86 isRunning: Effect.succeed(true),
87 exitCode: Effect.never,
88 };
89 }),
90 connectToOpenCodeServer: ({ serverUrl, serverPassword }) =>
91 runtimeMock.state.connectionError
92 ? Effect.fail(
93 new OpenCodeRuntime.OpenCodeRuntimeError({
94 operation: "global.health",
95 detail: runtimeMock.state.connectionError.message,
96 cause: runtimeMock.state.connectionError,
97 }),
98 )
99 : Effect.succeed({
100 url: serverUrl ?? "http://127.0.0.1:4301",
101 ...(serverPassword ? { serverPassword } : {}),
102 version: "1.14.19",
103 exitCode: null,
104 external: Boolean(serverUrl),
105 }),
106 runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
107 createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
108 ({
109 session: {
110 create: async (_input: unknown, options?: { readonly signal?: AbortSignal }) => {
111 runtimeMock.state.sessionCreateCalls += 1;
112 if (runtimeMock.state.onSessionCreate) {
113 return runtimeMock.state.onSessionCreate(options?.signal);
114 }
115 if (runtimeMock.state.sessionCreateError !== undefined) {
116 throw runtimeMock.state.sessionCreateError;
117 }
118 return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } };
119 },
120 abort: async (
121 input: { readonly sessionID: string },
122 options?: { readonly signal?: AbortSignal },
123 ) => {
124 runtimeMock.state.abortCalls.push(input.sessionID);
125 if (runtimeMock.state.onAbort) return runtimeMock.state.onAbort(options?.signal);
126 return { data: true };
127 },
128 prompt: async (
129 input: { readonly parts: ReadonlyArray<unknown> },
130 options?: { readonly signal?: AbortSignal },
131 ) => {
132 runtimeMock.state.promptUrls.push(baseUrl);
133 runtimeMock.state.promptParts.push(input.parts);
134 runtimeMock.state.authHeaders.push(
135 serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
136 );
137 if (runtimeMock.state.onPrompt) return runtimeMock.state.onPrompt(options?.signal);
138 if (runtimeMock.state.promptRequestError !== undefined) {
139 throw runtimeMock.state.promptRequestError;
140 }
141 return (
142 runtimeMock.state.promptResult ?? {
143 data: {
144 parts: [
145 {
146 type: "text",
147 text: JSON.stringify({
148 subject: "Improve OpenCode reuse",
149 body: "Reuse one server for the full action.",
150 }),
151 },
152 ],
153 },
154 }
155 );
156 },
157 },
158 }) as unknown as ReturnType<
159 OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
160 >,
161 loadOpenCodeInventory: () =>
162 Effect.fail(
163 new OpenCodeRuntime.OpenCodeRuntimeError({
164 operation: "loadOpenCodeInventory",
165 detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
166 cause: null,
167 }),
168 ),
169 loadOpenCodeSkills: () => Effect.succeed([]),
170};
171​
172const DEFAULT_TEST_MODEL_SELECTION = {
173 instanceId: ProviderInstanceId.make("opencode"),
174 model: "openai/gpt-5",
175};
176const DEFAULT_COMMIT_MESSAGE_INPUT = {
177 cwd: process.cwd(),
178 branch: "feature/opencode-reuse",
179 stagedSummary: "M README.md",
180 stagedPatch: "diff --git a/README.md b/README.md",
181 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
182};
183​
184const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
185​
186const layerOpenCodeTextGenerationTest = Layer.succeed(
187 OpenCodeRuntime.OpenCodeRuntime,
188 OpenCodeRuntimeTestDouble,
189).pipe(
190 Layer.provideMerge(TestProviderHost.layer()),
191 Layer.provideMerge(NetService.layer),
192 Layer.provideMerge(NodeServices.layer),
193);
194​
195const layerOpenCodeTextGenerationExistingServerTest = Layer.succeed(
196 OpenCodeRuntime.OpenCodeRuntime,
197 OpenCodeRuntimeTestDouble,
198).pipe(
199 Layer.provideMerge(TestProviderHost.layer()),
200 Layer.provideMerge(NetService.layer),
201 Layer.provideMerge(NodeServices.layer),
202);
203​
204const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
205 binaryPath: "fake-opencode",
206});
207const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
208 binaryPath: "fake-opencode",
209 serverUrl: "http://127.0.0.1:9999",
210 serverPassword: "secret-password",
211});
212const EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
213 binaryPath: "fake-opencode",
214 serverUrl: "http://127.0.0.1:9999",
215});
216​
217function withOpenCodeTextGeneration<A, E, R>(
218 settings: OpenCodeSettings,
219 effectFn: (textGeneration: ProviderTextGeneration) => Effect.Effect<A, E, R>,
220 environment?: NodeJS.ProcessEnv,
221) {
222 return Effect.gen(function* () {
223 const serverOwner = yield* OpenCodeServerOwner.make({
224 binaryPath: settings.binaryPath,
225 directory: process.cwd(),
226 ...(settings.serverPassword ? { serverPassword: settings.serverPassword } : {}),
227 ...(environment ? { environment } : {}),
228 });
229 const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings).pipe(
230 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
231 );
232 return yield* effectFn(textGeneration);
233 }).pipe(Effect.scoped);
235​
236beforeEach(() => {
237 runtimeMock.reset();
238});
239​
240const advanceIdleClock = Effect.gen(function* () {
241 yield* Effect.yieldNow;
242 yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
243 yield* Effect.yieldNow;
244});
245​
246it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => {
247 it.effect("cancels an in-flight session creation before prompting", () =>
248 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
249 Effect.gen(function* () {
250 const started = yield* Deferred.make<AbortSignal | undefined>();
251 runtimeMock.state.onSessionCreate = (signal) => {
252 Deferred.doneUnsafe(started, Effect.succeed(signal));
253 return new Promise<never>(() => {});
254 };
255 const fiber = yield* textGeneration
256 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
257 .pipe(Effect.forkChild);
258 const signal = yield* Deferred.await(started);
259 yield* Fiber.interrupt(fiber);
260​
261 const exit = yield* Fiber.await(fiber);
262 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
263 expect(signal?.aborted).toBe(true);
264 expect(runtimeMock.state.promptUrls).toEqual([]);
265 expect(runtimeMock.state.abortCalls).toEqual([]);
266 }),
267 ),
268 );
269​
270 it.effect("cancels only its prompt session while another generation uses the shared server", () =>
271 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
272 Effect.gen(function* () {
273 const started = yield* Deferred.make<AbortSignal | undefined>();
274 runtimeMock.state.sessionResult = { data: { id: "cancelled-session" } };
275 runtimeMock.state.onPrompt = (signal) => {
276 Deferred.doneUnsafe(started, Effect.succeed(signal));
277 return new Promise<never>(() => {});
278 };
279 const fiber = yield* textGeneration
280 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
281 .pipe(Effect.forkChild);
282 const signal = yield* Deferred.await(started);
283​
284 const otherStarted = yield* Deferred.make<AbortSignal | undefined>();
285 const otherReply = Promise.withResolvers<{ data: { parts: ReadonlyArray<unknown> } }>();
286 runtimeMock.state.sessionResult = { data: { id: "other-session" } };
287 runtimeMock.state.onPrompt = (otherSignal) => {
288 Deferred.doneUnsafe(otherStarted, Effect.succeed(otherSignal));
289 return otherReply.promise;
290 };
291 const otherFiber = yield* textGeneration
292 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
293 .pipe(Effect.forkChild);
294 const otherSignal = yield* Deferred.await(otherStarted);
295 yield* Fiber.interrupt(fiber);
296​
297 const exit = yield* Fiber.await(fiber);
298 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
299 expect(signal?.aborted).toBe(true);
300 expect(otherSignal?.aborted).toBe(false);
301 expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]);
302 expect(runtimeMock.state.closeCalls).toEqual([]);
303​
304 otherReply.resolve({
305 data: {
306 parts: [{ type: "text", text: '{"subject":"Other generation completed","body":""}' }],
307 },
308 });
309 expect((yield* Fiber.join(otherFiber)).subject).toBe("Other generation completed");
310 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
311 expect(runtimeMock.state.promptUrls).toEqual([
312 "http://127.0.0.1:4301",
313 "http://127.0.0.1:4301",
314 ]);
315 expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]);
316 expect(runtimeMock.state.closeCalls).toEqual([]);
317 }),
318 ),
319 );
320​
321 it.effect("excludes generic files from thread title generation", () =>
322 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
323 Effect.gen(function* () {
324 runtimeMock.state.promptResult = {
325 data: {
326 parts: [{ type: "text", text: '{"title":"Review uploaded report"}' }],
327 },
328 };
329​
330 yield* textGeneration.generateThreadTitle({
331 cwd: process.cwd(),
332 message: "Review these attachments.",
333 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
334 attachments: [
335 {
336 type: "image",
337 id: "thread-image-attachment",
338 name: "screenshot.png",
339 mimeType: "image/png",
340 sizeBytes: 3,
341 },
342 {
343 type: "file",
344 id: "thread-report-attachment-pdf",
345 name: "report.pdf",
346 mimeType: "application/pdf",
347 sizeBytes: 42,
348 },
349 ],
350 });
351​
352 expect(runtimeMock.state.promptParts[0]).toEqual([
353 expect.objectContaining({ type: "text" }),
354 expect.objectContaining({ type: "file", filename: "screenshot.png" }),
355 ]);
356 }),
357 ),
358 );
359​
360 it.effect("uses an environment-only password for a locally spawned server", () =>
361 withOpenCodeTextGeneration(
362 DEFAULT_OPENCODE_SETTINGS,
363 (textGeneration) =>
364 Effect.gen(function* () {
365 yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
366​
367 expect(runtimeMock.state.authHeaders).toEqual([
368 `Basic ${btoa("opencode:environment-password")}`,
369 ]);
370 }),
371 { OPENCODE_SERVER_PASSWORD: "environment-password" },
372 ),
373 );
374​
375 it.effect("returns a typed empty-output error for malformed and blank response parts", () =>
376 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
377 Effect.gen(function* () {
378 runtimeMock.state.promptResult = {
379 data: {
380 parts: [null, { type: "tool" }, { type: "text", text: " " }],
381 },
382 };
383​
384 const error = yield* textGeneration
385 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
386 .pipe(Effect.flip);
387​
388 expect(error.message).toContain("OpenCode returned empty output.");
389 expect(error.cause).toMatchObject({
390 _tag: "OpenCodeTextGenerationEmptyOutputError",
391 operation: "generateCommitMessage",
392 cwd: process.cwd(),
393 sessionId: "http://127.0.0.1:4301/session",
394 providerId: "openai",
395 modelId: "gpt-5",
396 responsePartCount: 3,
397 textPartCount: 1,
398 });
399 expect(error.cause).not.toHaveProperty("cause");
400 }),
401 ),
402 );
403​
404 it.effect("parses JSON returned as plain text output", () =>
405 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
406 Effect.gen(function* () {
407 runtimeMock.state.promptResult = {
408 data: {
409 parts: [
410 {
411 type: "text",
412 text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
413 },
414 ],
415 },
416 };
417​
418 const result = yield* textGeneration.generateCommitMessage({
419 cwd: process.cwd(),
420 branch: "feature/opencode-reuse",
421 stagedSummary: "M README.md",
422 stagedPatch: "diff --git a/README.md b/README.md",
423 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
424 });
425​
426 expect(result).toEqual({
427 subject: "Tighten OpenCode parsing",
428 body: "Handle JSON text output locally.",
429 });
430 }),
431 ),
432 );
433});
434​
435it.layer(layerOpenCodeTextGenerationExistingServerTest)(
436 "OpenCodeTextGeneration with configured server URL",
437 (it) => {
438 it.effect("does not send a local environment password to a configured server", () =>
439 withOpenCodeTextGeneration(
440 EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS,
441 (textGeneration) =>
442 Effect.gen(function* () {
443 yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
444 expect(runtimeMock.state.authHeaders).toEqual([null]);
445 }),
446 { OPENCODE_SERVER_PASSWORD: "local-secret" },
447 ),
448 );
449​
450 it.effect("does not create a session when the server version is unsupported", () =>
451 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
452 Effect.gen(function* () {
453 runtimeMock.state.connectionError = new Error(
454 "OpenCode v1.14.18 is too old. Upgrade to v1.14.19 or newer.",
455 );
456​
457 const error = yield* textGeneration
458 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
459 .pipe(Effect.flip);
460​
461 expect(error).toBeInstanceOf(TextGenerationError);
462 expect(error.message).toContain("v1.14.18 is too old");
463 expect(runtimeMock.state.sessionCreateCalls).toBe(0);
464 }),
465 ),
466 );
467​
468 it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
469 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
470 Effect.gen(function* () {
471 yield* textGeneration.generateCommitMessage({
472 cwd: process.cwd(),
473 branch: "feature/opencode-reuse",
474 stagedSummary: "M README.md",
475 stagedPatch: "diff --git a/README.md b/README.md",
476 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
477 });
478 yield* textGeneration.generateCommitMessage({
479 cwd: process.cwd(),
480 branch: "feature/opencode-reuse",
481 stagedSummary: "M README.md",
482 stagedPatch: "diff --git a/README.md b/README.md",
483 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
484 });
485​
486 expect(runtimeMock.state.startCalls).toEqual([]);
487 expect(runtimeMock.state.promptUrls).toEqual([
488 "http://127.0.0.1:9999",
489 "http://127.0.0.1:9999",
490 ]);
491 expect(runtimeMock.state.authHeaders).toEqual([
492 `Basic ${btoa("opencode:secret-password")}`,
493 `Basic ${btoa("opencode:secret-password")}`,
494 ]);
495​
496 yield* advanceIdleClock;
497​
498 expect(runtimeMock.state.closeCalls).toEqual([]);
499 }),
500 ).pipe(Effect.provide(TestClock.layer())),
501 );
502 },
503);