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

CodexTextGeneration.test.ts

855 lines32.8 KB

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