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