Open History to see the last commit
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 loadInventoryFromCli: () =>
171 Effect.fail(
172 new OpenCodeRuntime.OpenCodeRuntimeError({
173 operation: "loadInventoryFromCli",
174 detail: "OpenCodeRuntimeTestDouble.loadInventoryFromCli not used in this test",
175 cause: null,
176 }),
177 ),
178 loadSkillsFromCli: () => Effect.succeed([]),
179};
180
181const DEFAULT_TEST_MODEL_SELECTION = {
182 instanceId: ProviderInstanceId.make("opencode"),
183 model: "openai/gpt-5",
184};
185const DEFAULT_COMMIT_MESSAGE_INPUT = {
186 cwd: process.cwd(),
187 branch: "feature/opencode-reuse",
188 stagedSummary: "M README.md",
189 stagedPatch: "diff --git a/README.md b/README.md",
190 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
191};
192
193const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
194
195const layerOpenCodeTextGenerationTest = 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 layerOpenCodeTextGenerationExistingServerTest = Layer.succeed(
205 OpenCodeRuntime.OpenCodeRuntime,
206 OpenCodeRuntimeTestDouble,
207).pipe(
208 Layer.provideMerge(TestProviderHost.layer()),
209 Layer.provideMerge(NetService.layer),
210 Layer.provideMerge(NodeServices.layer),
211);
212
213const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
214 binaryPath: "fake-opencode",
215});
216const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
217 binaryPath: "fake-opencode",
218 serverUrl: "http://127.0.0.1:9999",
219 serverPassword: "secret-password",
220});
221const EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
222 binaryPath: "fake-opencode",
223 serverUrl: "http://127.0.0.1:9999",
224});
225
226function withOpenCodeTextGeneration<A, E, R>(
227 settings: OpenCodeSettings,
228 effectFn: (textGeneration: ProviderTextGeneration) => Effect.Effect<A, E, R>,
229 environment?: NodeJS.ProcessEnv,
230) {
231 return Effect.gen(function* () {
232 const serverOwner = yield* OpenCodeServerOwner.make({
233 binaryPath: settings.binaryPath,
234 directory: process.cwd(),
235 ...(settings.serverPassword ? { serverPassword: settings.serverPassword } : {}),
236 ...(environment ? { environment } : {}),
237 });
238 const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings).pipe(
239 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
240 );
241 return yield* effectFn(textGeneration);
242 }).pipe(Effect.scoped);
243}
244
245beforeEach(() => {
246 runtimeMock.reset();
247});
248
249const advanceIdleClock = Effect.gen(function* () {
250 yield* Effect.yieldNow;
251 yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
252 yield* Effect.yieldNow;
253});
254
255it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => {
256 it.effect("cancels an in-flight session creation before prompting", () =>
257 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
258 Effect.gen(function* () {
259 const started = yield* Deferred.make<AbortSignal | undefined>();
260 runtimeMock.state.onSessionCreate = (signal) => {
261 Deferred.doneUnsafe(started, Effect.succeed(signal));
262 return new Promise<never>(() => {});
263 };
264 const fiber = yield* textGeneration
265 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
266 .pipe(Effect.forkChild);
267 const signal = yield* Deferred.await(started);
268 yield* Fiber.interrupt(fiber);
269
270 const exit = yield* Fiber.await(fiber);
271 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
272 expect(signal?.aborted).toBe(true);
273 expect(runtimeMock.state.promptUrls).toEqual([]);
274 expect(runtimeMock.state.abortCalls).toEqual([]);
275 }),
276 ),
277 );
278
279 it.effect("cancels only its prompt session while another generation uses the shared server", () =>
280 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
281 Effect.gen(function* () {
282 const started = yield* Deferred.make<AbortSignal | undefined>();
283 runtimeMock.state.sessionResult = { data: { id: "cancelled-session" } };
284 runtimeMock.state.onPrompt = (signal) => {
285 Deferred.doneUnsafe(started, Effect.succeed(signal));
286 return new Promise<never>(() => {});
287 };
288 const fiber = yield* textGeneration
289 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
290 .pipe(Effect.forkChild);
291 const signal = yield* Deferred.await(started);
292
293 const otherStarted = yield* Deferred.make<AbortSignal | undefined>();
294 const otherReply = Promise.withResolvers<{ data: { parts: ReadonlyArray<unknown> } }>();
295 runtimeMock.state.sessionResult = { data: { id: "other-session" } };
296 runtimeMock.state.onPrompt = (otherSignal) => {
297 Deferred.doneUnsafe(otherStarted, Effect.succeed(otherSignal));
298 return otherReply.promise;
299 };
300 const otherFiber = yield* textGeneration
301 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
302 .pipe(Effect.forkChild);
303 const otherSignal = yield* Deferred.await(otherStarted);
304 yield* Fiber.interrupt(fiber);
305
306 const exit = yield* Fiber.await(fiber);
307 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
308 expect(signal?.aborted).toBe(true);
309 expect(otherSignal?.aborted).toBe(false);
310 expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]);
311 expect(runtimeMock.state.closeCalls).toEqual([]);
312
313 otherReply.resolve({
314 data: {
315 parts: [{ type: "text", text: '{"subject":"Other generation completed","body":""}' }],
316 },
317 });
318 expect((yield* Fiber.join(otherFiber)).subject).toBe("Other generation completed");
319 expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
320 expect(runtimeMock.state.promptUrls).toEqual([
321 "http://127.0.0.1:4301",
322 "http://127.0.0.1:4301",
323 ]);
324 expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]);
325 expect(runtimeMock.state.closeCalls).toEqual([]);
326 }),
327 ),
328 );
329
330 it.effect("excludes generic files from thread title generation", () =>
331 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
332 Effect.gen(function* () {
333 runtimeMock.state.promptResult = {
334 data: {
335 parts: [{ type: "text", text: '{"title":"Review uploaded report"}' }],
336 },
337 };
338
339 yield* textGeneration.generateThreadTitle({
340 cwd: process.cwd(),
341 message: "Review these attachments.",
342 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
343 attachments: [
344 {
345 type: "image",
346 id: "thread-image-attachment",
347 name: "screenshot.png",
348 mimeType: "image/png",
349 sizeBytes: 3,
350 },
351 {
352 type: "file",
353 id: "thread-report-attachment-pdf",
354 name: "report.pdf",
355 mimeType: "application/pdf",
356 sizeBytes: 42,
357 },
358 ],
359 });
360
361 expect(runtimeMock.state.promptParts[0]).toEqual([
362 expect.objectContaining({ type: "text" }),
363 expect.objectContaining({ type: "file", filename: "screenshot.png" }),
364 ]);
365 }),
366 ),
367 );
368
369 it.effect("uses an environment-only password for a locally spawned server", () =>
370 withOpenCodeTextGeneration(
371 DEFAULT_OPENCODE_SETTINGS,
372 (textGeneration) =>
373 Effect.gen(function* () {
374 yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
375
376 expect(runtimeMock.state.authHeaders).toEqual([
377 `Basic ${btoa("opencode:environment-password")}`,
378 ]);
379 }),
380 { OPENCODE_SERVER_PASSWORD: "environment-password" },
381 ),
382 );
383
384 it.effect("returns a typed empty-output error for malformed and blank response parts", () =>
385 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
386 Effect.gen(function* () {
387 runtimeMock.state.promptResult = {
388 data: {
389 parts: [null, { type: "tool" }, { type: "text", text: " " }],
390 },
391 };
392
393 const error = yield* textGeneration
394 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
395 .pipe(Effect.flip);
396
397 expect(error.message).toContain("OpenCode returned empty output.");
398 expect(error.cause).toMatchObject({
399 _tag: "OpenCodeTextGenerationEmptyOutputError",
400 operation: "generateCommitMessage",
401 cwd: process.cwd(),
402 sessionId: "http://127.0.0.1:4301/session",
403 providerId: "openai",
404 modelId: "gpt-5",
405 responsePartCount: 3,
406 textPartCount: 1,
407 });
408 expect(error.cause).not.toHaveProperty("cause");
409 }),
410 ),
411 );
412
413 it.effect("parses JSON returned as plain text output", () =>
414 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
415 Effect.gen(function* () {
416 runtimeMock.state.promptResult = {
417 data: {
418 parts: [
419 {
420 type: "text",
421 text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
422 },
423 ],
424 },
425 };
426
427 const result = yield* textGeneration.generateCommitMessage({
428 cwd: process.cwd(),
429 branch: "feature/opencode-reuse",
430 stagedSummary: "M README.md",
431 stagedPatch: "diff --git a/README.md b/README.md",
432 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
433 });
434
435 expect(result).toEqual({
436 subject: "Tighten OpenCode parsing",
437 body: "Handle JSON text output locally.",
438 });
439 }),
440 ),
441 );
442});
443
444it.layer(layerOpenCodeTextGenerationExistingServerTest)(
445 "OpenCodeTextGeneration with configured server URL",
446 (it) => {
447 it.effect("does not send a local environment password to a configured server", () =>
448 withOpenCodeTextGeneration(
449 EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS,
450 (textGeneration) =>
451 Effect.gen(function* () {
452 yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
453 expect(runtimeMock.state.authHeaders).toEqual([null]);
454 }),
455 { OPENCODE_SERVER_PASSWORD: "local-secret" },
456 ),
457 );
458
459 it.effect("does not create a session when the server version is unsupported", () =>
460 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
461 Effect.gen(function* () {
462 runtimeMock.state.connectionError = new Error(
463 "OpenCode v1.14.18 is too old. Upgrade to v1.14.19 or newer.",
464 );
465
466 const error = yield* textGeneration
467 .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
468 .pipe(Effect.flip);
469
470 expect(error).toBeInstanceOf(TextGenerationError);
471 expect(error.message).toContain("v1.14.18 is too old");
472 expect(runtimeMock.state.sessionCreateCalls).toBe(0);
473 }),
474 ),
475 );
476
477 it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
478 withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
479 Effect.gen(function* () {
480 yield* textGeneration.generateCommitMessage({
481 cwd: process.cwd(),
482 branch: "feature/opencode-reuse",
483 stagedSummary: "M README.md",
484 stagedPatch: "diff --git a/README.md b/README.md",
485 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
486 });
487 yield* textGeneration.generateCommitMessage({
488 cwd: process.cwd(),
489 branch: "feature/opencode-reuse",
490 stagedSummary: "M README.md",
491 stagedPatch: "diff --git a/README.md b/README.md",
492 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
493 });
494
495 expect(runtimeMock.state.startCalls).toEqual([]);
496 expect(runtimeMock.state.promptUrls).toEqual([
497 "http://127.0.0.1:9999",
498 "http://127.0.0.1:9999",
499 ]);
500 expect(runtimeMock.state.authHeaders).toEqual([
501 `Basic ${btoa("opencode:secret-password")}`,
502 `Basic ${btoa("opencode:secret-password")}`,
503 ]);
504
505 yield* advanceIdleClock;
506
507 expect(runtimeMock.state.closeCalls).toEqual([]);
508 }),
509 ).pipe(Effect.provide(TestClock.layer())),
510 );
511 },
512);