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