Open History to see the last commit
1import {
2 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
3 ProviderDriverKind,
4 type ModelSelection,
5 type ServerProvider,
6} from "@t3tools/contracts";
7import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
8import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
9import * as ServerSettings from "../serverSettings.ts";
10import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
11import * as NodeServices from "@effect/platform-node/NodeServices";
12import { it } from "@effect/vitest";
13import * as Cause from "effect/Cause";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Path from "effect/Path";
20import * as Schema from "effect/Schema";
21import * as Scope from "effect/Scope";
22import { createModelSelection } from "@t3tools/shared/model";
23import { expect } from "vite-plus/test";
24
25import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts";
26
27import * as ServerConfig from "../config.ts";
28import { makeProcessProbe, processProbeSource } from "../testUtils/processProbe.ts";
29import * as TextGeneration from "./TextGeneration.ts";
30import * as TextGenerators from "./TextGenerators.ts";
31import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
32import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
33const decodeCodexSettings = Schema.decodeSync(CodexSettings);
34
35const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
36 ProviderInstanceId.make("codex"),
37 "gpt-5.4-mini",
38);
39
40const layerCodexTextGenerationTest = ServerConfig.ServerConfig.layerTest(process.cwd(), {
41 prefix: "t3code-codex-text-generation-test-",
42}).pipe(Layer.provideMerge(NodeServices.layer));
43
44interface FakeCodexInput {
45 output: string;
46 lifecycle?: { port: number; command: "exec" | "mcp list" };
47 exitCode?: number;
48 stderr?: string;
49 requireImage?: boolean;
50 requireServiceTier?: string;
51 requireReasoningEffort?: string;
52 forbidReasoningEffort?: boolean;
53 requireArg?: string;
54 forbidArg?: string;
55 stdinMustContain?: string;
56 stdinMustNotContain?: string;
57 mcpServers?: ReadonlyArray<{ name: string; enabled: boolean }> | number;
58 requiredCwd?: string;
59 requireInstructions?: string;
60}
61
62function makeFakeCodexBinary(dir: string, input: FakeCodexInput) {
63 const check = JSON.stringify({
64 requireImage: input.requireImage ?? false,
65 requireServiceTier: input.requireServiceTier ?? null,
66 requireReasoningEffort: input.requireReasoningEffort ?? null,
67 forbidReasoningEffort: input.forbidReasoningEffort ?? false,
68 requireArg: input.requireArg ?? null,
69 forbidArg: input.forbidArg ?? null,
70 stdinMustContain: input.stdinMustContain ?? null,
71 stdinMustNotContain: input.stdinMustNotContain ?? null,
72 mcpServers: input.mcpServers ?? [],
73 requiredCwd: input.requiredCwd ?? null,
74 requireInstructions: input.requireInstructions ?? null,
75 stderr: input.stderr ?? null,
76 output: input.output,
77 exitCode: input.exitCode ?? 0,
78 });
79 return Effect.gen(function* () {
80 const path = yield* Path.Path;
81 return writeFakeCli({
82 directory: path.join(dir, "bin"),
83 name: "codex",
84 source: [
85 'import * as NodeFS from "node:fs";',
86 `const check = ${check};`,
87 "const args = process.argv.slice(2);",
88 'const isMcpList = args.includes("mcp") && args.includes("list");',
89 ...(input.lifecycle === undefined
90 ? []
91 : [
92 `if (isMcpList === ${input.lifecycle.command === "mcp list"}) {`,
93 'process.on("SIGTERM", () => {});',
94 processProbeSource(input.lifecycle.port),
95 "await new Promise(() => {});",
96 "}",
97 ]),
98 "if (isMcpList) {",
99 ' if (typeof check.mcpServers === "number") process.exit(check.mcpServers);',
100 " process.stdout.write(JSON.stringify(check.mcpServers));",
101 " process.exit(0);",
102 "}",
103 'const originalArgs = ` ${args.join(" ")} `;',
104 "let outputPath = null;",
105 "let seenImage = false;",
106 'let seenServiceTier = "";',
107 'let seenReasoningEffort = "";',
108 'let instructions = "";',
109 "for (let index = 0; index < args.length; index += 1) {",
110 ' if (args[index] === "--image") {',
111 " index += 1;",
112 " if (args[index]) seenImage = true;",
113 ' } else if (args[index] === "--config") {',
114 " index += 1;",
115 ' const value = args[index] ?? "";',
116 ' if (value.startsWith("developer_instructions=")) instructions = JSON.parse(value.slice("developer_instructions=".length));',
117 ' if (value.startsWith("service_tier=")) seenServiceTier = value;',
118 ' if (value.startsWith("model_reasoning_effort=")) seenReasoningEffort = value;',
119 ' } else if (args[index] === "--output-last-message") {',
120 " index += 1;",
121 " outputPath = args[index] ?? null;",
122 " }",
123 "}",
124 "const chunks = [];",
125 "for await (const chunk of process.stdin) chunks.push(chunk);",
126 'const stdinContent = Buffer.concat(chunks).toString("utf8");',
127 "function fail(message, code) {",
128 ' process.stderr.write(message + "\\n");',
129 " process.exit(code);",
130 "}",
131 'if (check.requiredCwd !== null && process.cwd() !== check.requiredCwd) fail("cannot inspect checkout", 10);',
132 'if (check.requireInstructions !== null && !instructions.includes(check.requireInstructions)) fail("missing writer task", 11);',
133 "if (check.requireArg !== null && !originalArgs.includes(` ${check.requireArg} `)) {",
134 ' fail("missing arg: " + check.requireArg, 8);',
135 "}",
136 "if (check.forbidArg !== null && originalArgs.includes(` ${check.forbidArg} `)) {",
137 ' fail("forbidden arg: " + check.forbidArg, 9);',
138 "}",
139 'if (check.requireImage && !seenImage) fail("missing --image input", 2);',
140 "if (",
141 " check.requireServiceTier !== null &&",
142 ' seenServiceTier !== `service_tier="${check.requireServiceTier}"`',
143 ") {",
144 ' fail("unexpected service tier config: " + seenServiceTier, 5);',
145 "}",
146 "if (",
147 " check.requireReasoningEffort !== null &&",
148 ' seenReasoningEffort !== `model_reasoning_effort="${check.requireReasoningEffort}"`',
149 ") {",
150 ' fail("unexpected reasoning effort config: " + seenReasoningEffort, 6);',
151 "}",
152 "if (check.forbidReasoningEffort && seenReasoningEffort.length > 0) {",
153 ' fail("reasoning effort config should be omitted: " + seenReasoningEffort, 7);',
154 "}",
155 "if (check.stdinMustContain !== null && !stdinContent.includes(check.stdinMustContain)) {",
156 ' fail("stdin missing expected content", 3);',
157 "}",
158 "if (check.stdinMustNotContain !== null && stdinContent.includes(check.stdinMustNotContain)) {",
159 ' fail("stdin contained forbidden content", 4);',
160 "}",
161 'if (check.stderr !== null) process.stderr.write(check.stderr + "\\n");',
162 'if (outputPath !== null) NodeFS.writeFileSync(outputPath, check.output + "\\n");',
163 "process.exitCode = check.exitCode;",
164 "",
165 ].join("\n"),
166 });
167 });
168}
169
170function withFakeCodexEnv<A, E, R>(
171 input: FakeCodexInput & {
172 launchArgs?: string;
173 environment?: NodeJS.ProcessEnv;
174 models?: ReadonlyArray<string>;
175 defaultModel?: string;
176 customModels?: ReadonlyArray<string>;
177 managedRuntime?: boolean;
178 },
179 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
180) {
181 return Effect.gen(function* () {
182 const fs = yield* FileSystem.FileSystem;
183 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
184 const codexPath = yield* makeFakeCodexBinary(tempDir, input);
185 const config = decodeCodexSettings({
186 binaryPath: codexPath,
187 launchArgs: input.launchArgs,
188 customModels: input.customModels,
189 });
190 const textGeneration = yield* makeCodexTextGeneration(
191 config,
192 input.environment === undefined ? undefined : { ...process.env, ...input.environment },
193 Effect.succeed(
194 (input.models ?? []).map((slug) => ({
195 slug,
196 name: slug,
197 isCustom: false,
198 ...(slug === input.defaultModel ? { isDefault: true } : {}),
199 capabilities: null,
200 })),
201 ),
202 input.managedRuntime
203 ? Effect.succeed({
204 config,
205 environment: input.environment ?? process.env,
206 revision: "test",
207 })
208 : undefined,
209 );
210 return yield* effectFn(textGeneration);
211 }).pipe(Effect.scoped);
212}
213
214it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => {
215 it.effect.each(["exec", "mcp list"] as const)(
216 "kills a stalled %s CLI when its request is interrupted",
217 (command) =>
218 Effect.gen(function* () {
219 const probe = yield* makeProcessProbe;
220 yield* withFakeCodexEnv(
221 { output: "", lifecycle: { port: probe.port, command } },
222 (textGeneration) =>
223 Effect.gen(function* () {
224 const fiber = yield* textGeneration
225 .generateThreadTitle({
226 cwd: process.cwd(),
227 message: "Name this thread",
228 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
229 })
230 .pipe(Effect.forkScoped);
231 yield* probe.started;
232
233 const interrupted = yield* Fiber.interrupt(fiber).pipe(Effect.forkScoped);
234 yield* probe.exited;
235 yield* Fiber.join(interrupted);
236 const exit = yield* Fiber.await(fiber);
237 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
238 }),
239 );
240 }),
241 );
242
243 it.effect.each([
244 {
245 selectedModel: "gpt-5.6-luna",
246 models: ["openai.gpt-5.6-luna"],
247 expected: "openai.gpt-5.6-luna",
248 },
249 {
250 selectedModel: "openai.gpt-5.6-luna",
251 models: ["openai.gpt-5.6-luna"],
252 expected: "openai.gpt-5.6-luna",
253 },
254 {
255 selectedModel: "openai.gpt-5.6-luna",
256 models: ["gpt-6-astra", "gpt-5.6-luna"],
257 defaultModel: "gpt-6-astra",
258 expected: "gpt-5.6-luna",
259 },
260 {
261 selectedModel: "gpt-6-luna",
262 models: ["gpt-5.6-luna", "gpt-6-astra"],
263 defaultModel: "gpt-6-astra",
264 expected: "gpt-6-astra",
265 },
266 { selectedModel: "gpt-6-luna", models: ["gpt-5.6-luna"], expected: "gpt-5.6-luna" },
267 { selectedModel: "gpt-6-luna", models: [], expected: "gpt-6-luna" },
268 ])(
269 "dispatches $expected for $selectedModel from $models",
270 ({ selectedModel, models, defaultModel, expected }) =>
271 withFakeCodexEnv(
272 {
273 output: JSON.stringify({ title: "Live title" }),
274 models,
275 ...(defaultModel ? { defaultModel } : {}),
276 requireArg: `--model ${expected}`,
277 },
278 (textGeneration) =>
279 Effect.gen(function* () {
280 const result = yield* textGeneration.generateThreadTitle({
281 cwd: process.cwd(),
282 message: "Describe this change",
283 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), selectedModel),
284 });
285 expect(result.title).toBe("Live title");
286 }),
287 ),
288 );
289
290 it.effect("drops the requested model's options when falling back to another model", () =>
291 withFakeCodexEnv(
292 {
293 output: JSON.stringify({ title: "Live title" }),
294 models: ["gpt-6-astra"],
295 requireArg: '--model gpt-6-astra --config model_reasoning_effort="low"',
296 forbidArg: 'service_tier="priority"',
297 },
298 (textGeneration) =>
299 textGeneration.generateThreadTitle({
300 cwd: process.cwd(),
301 message: "Describe this change",
302 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-6-luna", [
303 { id: "reasoningEffort", value: "none" },
304 { id: "serviceTier", value: "priority" },
305 ]),
306 }),
307 ),
308 );
309
310 it.effect("sends a configured custom model the managed snapshot leaves out", () =>
311 withFakeCodexEnv(
312 {
313 output: JSON.stringify({ title: "Live title" }),
314 models: ["gpt-6-astra", "gpt-5.6-luna"],
315 defaultModel: "gpt-6-astra",
316 customModels: ["gpt-5.6-luna-preview"],
317 managedRuntime: true,
318 requireArg: '--model gpt-5.6-luna-preview --config model_reasoning_effort="high"',
319 },
320 (textGeneration) =>
321 textGeneration.generateThreadTitle({
322 cwd: process.cwd(),
323 message: "Describe this change",
324 modelSelection: createModelSelection(
325 ProviderInstanceId.make("codex"),
326 "gpt-5.6-luna-preview",
327 [{ id: "reasoningEffort", value: "high" }],
328 ),
329 }),
330 ),
331 );
332
333 it.effect("omits a persisted service tier for managed ChatGPT text generation", () =>
334 withFakeCodexEnv(
335 {
336 output: JSON.stringify({ subject: "Update project", body: "" }),
337 managedRuntime: true,
338 forbidArg: 'service_tier="priority"',
339 },
340 (textGeneration) =>
341 textGeneration.generateCommitMessage({
342 cwd: process.cwd(),
343 branch: "feature/chatgpt",
344 stagedSummary: "M README.md",
345 stagedPatch: "diff --git a/README.md b/README.md",
346 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
347 { id: "serviceTier", value: "priority" },
348 ]),
349 }),
350 ),
351 );
352
353 it.effect("preserves custom PR instructions while allowing checkout inspection", () =>
354 withFakeCodexEnv(
355 {
356 output: JSON.stringify({ title: "Remove default shapes", body: "Removes default shapes." }),
357 launchArgs: "--config 'developer_instructions=\"Use TEAM: as the PR title prefix\"'",
358 requiredCwd: process.cwd(),
359 requireInstructions: "Use TEAM: as the PR title prefix",
360 forbidArg: "--config features.shell_tool=false",
361 mcpServers: [
362 { name: "augmenter", enabled: true },
363 { name: "my.server", enabled: true },
364 { name: "already-off", enabled: false },
365 ],
366 requireArg:
367 '--config features.plugins=false --config features.apps=false --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}}',
368 },
369 (textGeneration) =>
370 Effect.gen(function* () {
371 const result = yield* textGeneration.generatePrContent({
372 cwd: process.cwd(),
373 baseBranch: "main",
374 headBranch: "remove-default-shapes",
375 commitSummary: "Remove default shapes",
376 diffSummary: "shapes.ts | 2 --",
377 diffPatch: "-addDefaultShapes();",
378 threadContext: "user: in a few minutes PR will be up then $babysit-pr",
379 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
380 });
381 expect(result.title).toBe("Remove default shapes");
382 }),
383 ),
384 );
385
386 it.effect("still generates when Codex cannot list its MCP servers", () =>
387 withFakeCodexEnv(
388 {
389 output: JSON.stringify({ branch: "remove-default-shapes" }),
390 mcpServers: 2,
391 requireArg: "--config features.plugins=false --config features.apps=false --ephemeral",
392 forbidArg: "mcp_servers=",
393 },
394 (textGeneration) =>
395 Effect.gen(function* () {
396 const result = yield* textGeneration.generateBranchName({
397 cwd: process.cwd(),
398 message: "Remove default shapes from characters",
399 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
400 });
401 expect(result.branch).toBe("remove-default-shapes");
402 }),
403 ),
404 );
405
406 it.effect("keeps plugins and apps off over launch args that turn them on", () =>
407 withFakeCodexEnv(
408 {
409 output: JSON.stringify({ title: "Remove default shapes" }),
410 launchArgs: "--config features.plugins=true --config features.apps=true",
411 requireArg:
412 "--config features.plugins=true --config features.apps=true --config features.plugins=false --config features.apps=false --ephemeral",
413 },
414 (textGeneration) =>
415 Effect.gen(function* () {
416 const result = yield* textGeneration.generateThreadTitle({
417 cwd: process.cwd(),
418 message: "Remove default shapes from characters",
419 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
420 });
421 expect(result.title).toBe("Remove default shapes");
422 }),
423 ),
424 );
425
426 it.effect("passes exec-safe launch args into codex exec", () =>
427 withFakeCodexEnv(
428 {
429 output: JSON.stringify({
430 subject: "Add important change",
431 body: "",
432 }),
433 launchArgs: "--strict-config --listen off",
434 requireArg: "--strict-config",
435 forbidArg: "--listen",
436 },
437 (textGeneration) =>
438 textGeneration.generateCommitMessage({
439 cwd: process.cwd(),
440 branch: "feature/codex-effect",
441 stagedSummary: "M README.md",
442 stagedPatch: "diff --git a/README.md b/README.md",
443 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
444 }),
445 ),
446 );
447
448 it.effect("generates branch names even when the ambient scope is already closed", () =>
449 withFakeCodexEnv(
450 {
451 output: JSON.stringify({
452 branch: "feat/background-generation",
453 }),
454 },
455 (textGeneration) =>
456 Effect.gen(function* () {
457 // Background fibers can outlive request scopes; temp files scoped there would be reaped on creation.
458 const closedScope = yield* Scope.make();
459 yield* Scope.close(closedScope, Exit.void);
460
461 const generated = yield* textGeneration
462 .generateBranchName({
463 cwd: process.cwd(),
464 message: "Please update session handling.",
465 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
466 })
467 .pipe(Effect.provideService(Scope.Scope, closedScope));
468
469 expect(generated.branch).toBe("feat/background-generation");
470 }),
471 ),
472 );
473
474 it.effect("returns the refinement signal for an unresolved subject", () =>
475 withFakeCodexEnv(
476 { output: JSON.stringify({ title: "Investigate issue", needsRefinement: true }) },
477 (textGeneration) =>
478 Effect.gen(function* () {
479 expect(
480 yield* textGeneration.generateThreadTitle({
481 cwd: process.cwd(),
482 message: "Fix this",
483 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
484 }),
485 ).toEqual({ title: "Investigate issue", needsRefinement: true });
486 }),
487 ),
488 );
489
490 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
491 withFakeCodexEnv(
492 {
493 output: JSON.stringify({
494 branch: "fix/ui-regression",
495 }),
496 requireImage: true,
497 },
498 (textGeneration) =>
499 Effect.gen(function* () {
500 const fs = yield* FileSystem.FileSystem;
501 const path = yield* Path.Path;
502 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
503 const attachmentId = "thread-1-attachment";
504 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
505 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
506 yield* fs.writeFile(imagePath, Buffer.from("hello"));
507
508 const generated = yield* textGeneration
509 .generateBranchName({
510 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
511 cwd: process.cwd(),
512 message: "Fix layout bug from screenshot.",
513 attachments: [
514 {
515 type: "image",
516 id: attachmentId,
517 name: "bug.png",
518 mimeType: "image/png",
519 sizeBytes: 5,
520 },
521 ],
522 })
523 .pipe(
524 Effect.tap(() =>
525 fs.stat(imagePath).pipe(
526 Effect.map((fileInfo) => {
527 expect(fileInfo.type).toBe("File");
528 }),
529 ),
530 ),
531 Effect.ensuring(fs.remove(imagePath).pipe(Effect.ignore)),
532 );
533
534 expect(generated.branch).toBe("fix/ui-regression");
535 }),
536 ),
537 );
538});
539
540const PREFLIGHT_PRIMARY_STATES = [
541 "ready",
542 "pending",
543 "exhausted",
544 "not installed",
545 "signed out",
546 "signed out, fallback failed",
547] as const;
548
549it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (primaryState) =>
550 Effect.gen(function* () {
551 const primary = ProviderInstanceId.make("codex");
552 const fallback = ProviderInstanceId.make("claude_work");
553 const selection = {
554 instanceId: primary,
555 model: "chat-model",
556 options: [{ id: "effort", value: "high" }],
557 };
558 const calls: ModelSelection[] = [];
559 const instances: ProviderInstance[] = [primary, fallback].map((instanceId) => {
560 const driver = ProviderDriverKind.make(instanceId === primary ? "codex" : "claudeAgent");
561 const snapshot: ServerProvider = {
562 instanceId,
563 driver,
564 enabled: true,
565 installed: true,
566 status: "ready",
567 auth: { status: "authenticated" },
568 version: null,
569 checkedAt: "1970-01-01T00:00:00Z",
570 models: [],
571 slashCommands: [],
572 skills: [],
573 ...(primaryState === "pending" && instanceId === primary
574 ? { installed: false, status: "warning", auth: { status: "unknown" } }
575 : {}),
576 ...(primaryState === "not installed" && instanceId === primary
577 ? { installed: false, status: "error", auth: { status: "unknown" } }
578 : {}),
579 ...(primaryState.startsWith("signed out") && instanceId === primary
580 ? { status: "error", auth: { status: "unauthenticated" } }
581 : {}),
582 ...(primaryState === "signed out, fallback failed" && instanceId === fallback
583 ? { status: "error", auth: { status: "unknown" } }
584 : {}),
585 ...(primaryState === "exhausted" && instanceId === primary
586 ? {
587 usageLimits: {
588 checkedAt: "1970-01-01T00:00:00Z",
589 windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 100 }],
590 },
591 }
592 : {}),
593 };
594 return {
595 instanceId,
596 driverKind: driver,
597 continuationIdentity: { driverKind: driver, continuationKey: instanceId },
598 displayName: undefined,
599 enabled: true,
600 snapshot: { getSnapshot: Effect.succeed(snapshot) } as ProviderInstance["snapshot"],
601 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
602 textGeneration: TextGeneration.TextGeneration.of({
603 generateCommitMessage: () => Effect.die("unused"),
604 generatePrContent: () => Effect.die("unused"),
605 generateBranchName: () => Effect.die("unused"),
606 generateReviewGuide: () => Effect.die("unused"),
607 generateTranscriptionPostProcessing: () => Effect.die("unused"),
608 generateThreadTitle: (input) =>
609 Effect.sync(() => {
610 calls.push(input.modelSelection);
611 return { title: "Generated title" };
612 }),
613 }),
614 };
615 });
616 const service = yield* TextGeneration.make.pipe(
617 Effect.provide(
618 Layer.mergeAll(
619 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
620 listInstances: Effect.succeed(instances),
621 getInstance: (id) =>
622 Effect.succeed(instances.find((instance) => instance.instanceId === id)),
623 }),
624 ServerSettings.layerTest({
625 providerInstances: {
626 [fallback]: { driver: ProviderDriverKind.make("claudeAgent"), config: {} },
627 },
628 }),
629 Layer.mock(TextGenerators.TextGenerators)({ runner: () => Effect.undefined }),
630 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
631 resolveLink: () => Effect.die("unused"),
632 }),
633 ),
634 ),
635 );
636 expect(
637 yield* service.generateThreadTitle({
638 cwd: "/tmp",
639 message: "hello",
640 linkedContext: "",
641 modelSelection: selection,
642 }),
643 ).toEqual({ title: "Generated title" });
644 expect(calls).toEqual([
645 primaryState === "ready" ||
646 primaryState === "pending" ||
647 primaryState === "signed out, fallback failed"
648 ? selection
649 : {
650 instanceId: fallback,
651 model:
652 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[ProviderDriverKind.make("claudeAgent")],
653 },
654 ]);
655 }),
656);
657
658it.effect(
659 "a review guide aimed at a text generator falls back to an agent that can read the checkout",
660 () =>
661 Effect.gen(function* () {
662 const claude = ProviderInstanceId.make("claudeAgent");
663 const driver = ProviderDriverKind.make("claudeAgent");
664 const calls: ModelSelection[] = [];
665 const instance = {
666 instanceId: claude,
667 driverKind: driver,
668 continuationIdentity: { driverKind: driver, continuationKey: claude },
669 displayName: undefined,
670 enabled: true,
671 snapshot: {
672 getSnapshot: Effect.succeed<ServerProvider>({
673 instanceId: claude,
674 driver,
675 enabled: true,
676 installed: true,
677 status: "ready",
678 auth: { status: "authenticated" },
679 version: null,
680 checkedAt: "1970-01-01T00:00:00Z",
681 models: [],
682 slashCommands: [],
683 skills: [],
684 }),
685 } as ProviderInstance["snapshot"],
686 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
687 textGeneration: TextGeneration.TextGeneration.of({
688 generateCommitMessage: () => Effect.die("unused"),
689 generatePrContent: () => Effect.die("unused"),
690 generateBranchName: () => Effect.die("unused"),
691 generateThreadTitle: () => Effect.die("unused"),
692 generateTranscriptionPostProcessing: () => Effect.die("unused"),
693 generateReviewGuide: (input) =>
694 Effect.sync(() => {
695 calls.push(input.modelSelection);
696 return {} as TextGeneration.ReviewGuideGenerationResult;
697 }),
698 }),
699 } satisfies ProviderInstance;
700 const serviceWith = (instances: ReadonlyArray<ProviderInstance>) =>
701 TextGeneration.make.pipe(
702 Effect.provide(
703 Layer.mergeAll(
704 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
705 listInstances: Effect.succeed(instances),
706 getInstance: (id) =>
707 Effect.succeed(instances.find((candidate) => candidate.instanceId === id)),
708 }),
709 ServerSettings.layerTest({}),
710 Layer.mock(TextGenerators.TextGenerators)({
711 runner: (id) =>
712 Effect.succeed(
713 id === "openrouter"
714 ? () => Effect.die("a text generator cannot investigate")
715 : undefined,
716 ),
717 }),
718 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
719 resolveLink: () => Effect.die("unused"),
720 }),
721 ),
722 ),
723 );
724 const input = {
725 cwd: "/tmp",
726 number: 1,
727 title: "Change",
728 description: "",
729 baseBranch: "main",
730 baseCommit: "abc",
731 settledReview: "",
732 modelSelection: { instanceId: ProviderInstanceId.make("openrouter"), model: "some/model" },
733 };
734 yield* (yield* serviceWith([instance])).generateReviewGuide(input);
735 expect(calls.map((selection) => selection.instanceId)).toEqual([claude]);
736
737 // With no agent ready, it says what is missing instead of looking up a provider by that id.
738 const failure = yield* Effect.flip((yield* serviceWith([])).generateReviewGuide(input));
739 expect(failure.detail).toMatch(
740 /^Review guides need a coding agent that can read the checkout/,
741 );
742 }),
743);