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

CodexTextGeneration.test.ts

936 lines36.1 KB

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;
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 });
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 },
215 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
216) {
217 return Effect.gen(function* () {
218 const fs = yield* FileSystem.FileSystem;
219 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
220 const codexPath = yield* makeFakeCodexBinary(tempDir, input);
221 const config = decodeCodexSettings({
222 binaryPath: codexPath,
223 launchArgs: input.launchArgs,
224 customModels: input.customModels,
225 });
226 const textGeneration = yield* makeCodexTextGeneration(
227 config,
228 input.environment === undefined ? undefined : { ...process.env, ...input.environment },
229 Effect.succeed(
230 (input.models ?? []).map((slug) => ({
231 slug,
232 name: slug,
233 isCustom: false,
234 ...(slug === input.defaultModel ? { isDefault: true } : {}),
235 capabilities: null,
236 })),
237 ),
238 input.managedRuntime
239 ? Effect.succeed({
240 config,
241 environment: input.environment ?? process.env,
242 revision: "test",
243 })
244 : undefined,
245 );
246 return yield* effectFn(textGeneration);
247 }).pipe(Effect.scoped);
249​
250it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => {
251 it.effect.each(["exec", "mcp list"] as const)(
252 "kills a stalled %s CLI when its request is interrupted",
253 (command) =>
254 Effect.gen(function* () {
255 const probe = yield* makeProcessProbe;
256 yield* withFakeCodexEnv(
257 { output: "", lifecycle: { port: probe.port, command } },
258 (textGeneration) =>
259 Effect.gen(function* () {
260 const fiber = yield* textGeneration
261 .generateThreadTitle({
262 cwd: process.cwd(),
263 message: "Name this thread",
264 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
265 })
266 .pipe(Effect.forkScoped);
267 yield* probe.started;
268​
269 const interrupted = yield* Fiber.interrupt(fiber).pipe(Effect.forkScoped);
270 yield* probe.exited;
271 yield* Fiber.join(interrupted);
272 const exit = yield* Fiber.await(fiber);
273 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
274 }),
275 );
276 }),
277 );
278​
279 it.effect.each([
280 {
281 selectedModel: "gpt-5.6-luna",
282 models: ["openai.gpt-5.6-luna"],
283 expected: "openai.gpt-5.6-luna",
284 },
285 {
286 selectedModel: "openai.gpt-5.6-luna",
287 models: ["openai.gpt-5.6-luna"],
288 expected: "openai.gpt-5.6-luna",
289 },
290 {
291 selectedModel: "openai.gpt-5.6-luna",
292 models: ["gpt-6-astra", "gpt-5.6-luna"],
293 defaultModel: "gpt-6-astra",
294 expected: "gpt-5.6-luna",
295 },
296 {
297 selectedModel: "gpt-6-luna",
298 models: ["gpt-5.6-luna", "gpt-6-astra"],
299 defaultModel: "gpt-6-astra",
300 expected: "gpt-6-astra",
301 },
302 { selectedModel: "gpt-6-luna", models: ["gpt-5.6-luna"], expected: "gpt-5.6-luna" },
303 { selectedModel: "gpt-6-luna", models: [], expected: "gpt-6-luna" },
304 ])(
305 "dispatches $expected for $selectedModel from $models",
306 ({ selectedModel, models, defaultModel, expected }) =>
307 withFakeCodexEnv(
308 {
309 output: JSON.stringify({ title: "Live title" }),
310 models,
311 ...(defaultModel ? { defaultModel } : {}),
312 requireArg: `--model ${expected}`,
313 },
314 (textGeneration) =>
315 Effect.gen(function* () {
316 const result = yield* textGeneration.generateThreadTitle({
317 cwd: process.cwd(),
318 message: "Describe this change",
319 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), selectedModel),
320 });
321 expect(result.title).toBe("Live title");
322 }),
323 ),
324 );
325​
326 it.effect("drops the requested model's options when falling back to another model", () =>
327 withFakeCodexEnv(
328 {
329 output: JSON.stringify({ title: "Live title" }),
330 models: ["gpt-6-astra"],
331 requireArg: '--model gpt-6-astra --config model_reasoning_effort="low"',
332 forbidArg: 'service_tier="priority"',
333 },
334 (textGeneration) =>
335 textGeneration.generateThreadTitle({
336 cwd: process.cwd(),
337 message: "Describe this change",
338 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-6-luna", [
339 { id: "reasoningEffort", value: "none" },
340 { id: "serviceTier", value: "priority" },
341 ]),
342 }),
343 ),
344 );
345​
346 it.effect("sends a configured custom model the managed snapshot leaves out", () =>
347 withFakeCodexEnv(
348 {
349 output: JSON.stringify({ title: "Live title" }),
350 models: ["gpt-6-astra", "gpt-5.6-luna"],
351 defaultModel: "gpt-6-astra",
352 customModels: ["gpt-5.6-luna-preview"],
353 managedRuntime: true,
354 requireArg: '--model gpt-5.6-luna-preview --config model_reasoning_effort="high"',
355 },
356 (textGeneration) =>
357 textGeneration.generateThreadTitle({
358 cwd: process.cwd(),
359 message: "Describe this change",
360 modelSelection: createModelSelection(
361 ProviderInstanceId.make("codex"),
362 "gpt-5.6-luna-preview",
363 [{ id: "reasoningEffort", value: "high" }],
364 ),
365 }),
366 ),
367 );
368​
369 it.effect("omits a persisted service tier for managed ChatGPT text generation", () =>
370 withFakeCodexEnv(
371 {
372 output: JSON.stringify({ subject: "Update project", body: "" }),
373 managedRuntime: true,
374 forbidArg: 'service_tier="priority"',
375 },
376 (textGeneration) =>
377 textGeneration.generateCommitMessage({
378 cwd: process.cwd(),
379 branch: "feature/chatgpt",
380 stagedSummary: "M README.md",
381 stagedPatch: "diff --git a/README.md b/README.md",
382 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
383 { id: "serviceTier", value: "priority" },
384 ]),
385 }),
386 ),
387 );
388​
389 it.effect("preserves custom PR instructions while allowing checkout inspection", () =>
390 withFakeCodexEnv(
391 {
392 output: JSON.stringify({ title: "Remove default shapes", body: "Removes default shapes." }),
393 launchArgs: "--config 'developer_instructions=\"Use TEAM: as the PR title prefix\"'",
394 requiredCwd: process.cwd(),
395 requireInstructions: "Use TEAM: as the PR title prefix",
396 forbidArg: "--config features.shell_tool=false",
397 mcpServers: [
398 { name: "augmenter", enabled: true },
399 { name: "my.server", enabled: true },
400 { name: "already-off", enabled: false },
401 ],
402 requireArg:
403 'exec --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}} --config developer_instructions="Use',
404 },
405 (textGeneration) =>
406 Effect.gen(function* () {
407 const result = yield* textGeneration.generatePrContent({
408 cwd: process.cwd(),
409 baseBranch: "main",
410 headBranch: "remove-default-shapes",
411 commitSummary: "Remove default shapes",
412 diffSummary: "shapes.ts | 2 --",
413 diffPatch: "-addDefaultShapes();",
414 threadContext: "user: in a few minutes PR will be up then $babysit-pr",
415 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
416 });
417 expect(result.title).toBe("Remove default shapes");
418 }),
419 ),
420 );
421​
422 it.effect("turns off an MCP server that launch args define without dropping its transport", () =>
423 withFakeCodexEnv(
424 {
425 output: JSON.stringify({ title: "Remove default shapes" }),
426 launchArgs: `-c 'mcp_servers.t3-code.url="http://127.0.0.1:1/mcp"' -c 'mcp_servers.t3-code.enabled=true'`,
427 mcpServers: [{ name: "t3-code", enabled: true }],
428 requireMcpServersOff: ["t3-code"],
429 requireArg:
430 "--config features.apps=false --config mcp_servers.t3-code.enabled=false --ephemeral",
431 },
432 (textGeneration) =>
433 Effect.gen(function* () {
434 const result = yield* textGeneration.generateThreadTitle({
435 cwd: process.cwd(),
436 message: "Remove default shapes from characters",
437 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
438 });
439 expect(result.title).toBe("Remove default shapes");
440 }),
441 ),
442 );
443​
444 it.effect("keeps MCP servers off when launch args set their own mcp_servers table", () =>
445 withFakeCodexEnv(
446 {
447 output: JSON.stringify({ title: "Remove default shapes" }),
448 launchArgs: `-c 'mcp_servers={"my.server"={command="echo",enabled=true}}'`,
449 mcpServers: [
450 { name: "my.server", enabled: true },
451 { name: "my server", enabled: true },
452 ],
453 requireArg:
454 '--config features.apps=false --config mcp_servers={"my.server"={enabled=false},"my server"={enabled=false}} --config mcp_servers.my server.enabled=false --ephemeral',
455 },
456 (textGeneration) =>
457 Effect.gen(function* () {
458 const result = yield* textGeneration.generateThreadTitle({
459 cwd: process.cwd(),
460 message: "Remove default shapes from characters",
461 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
462 });
463 expect(result.title).toBe("Remove default shapes");
464 }),
465 ),
466 );
467​
468 it.effect("still generates when Codex cannot list its MCP servers", () =>
469 withFakeCodexEnv(
470 {
471 output: JSON.stringify({ branch: "remove-default-shapes" }),
472 mcpServers: 2,
473 requireArg: "--config features.plugins=false --config features.apps=false --ephemeral",
474 forbidArg: "mcp_servers=",
475 },
476 (textGeneration) =>
477 Effect.gen(function* () {
478 const result = yield* textGeneration.generateBranchName({
479 cwd: process.cwd(),
480 message: "Remove default shapes from characters",
481 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
482 });
483 expect(result.branch).toBe("remove-default-shapes");
484 }),
485 ),
486 );
487​
488 it.effect("keeps plugins and apps off over launch args that turn them on", () =>
489 withFakeCodexEnv(
490 {
491 output: JSON.stringify({ title: "Remove default shapes" }),
492 launchArgs:
493 "--config features.plugins=true --config features.apps=true --config features.connectors=true",
494 requireArg:
495 "--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",
496 },
497 (textGeneration) =>
498 Effect.gen(function* () {
499 const result = yield* textGeneration.generateThreadTitle({
500 cwd: process.cwd(),
501 message: "Remove default shapes from characters",
502 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
503 });
504 expect(result.title).toBe("Remove default shapes");
505 }),
506 ),
507 );
508​
509 it.effect("keeps user hooks off over launch args that turn them on", () =>
510 withFakeCodexEnv(
511 {
512 output: JSON.stringify({ title: "Hookless title" }),
513 launchArgs: "--config features.hooks=true --enable hooks",
514 requireArg: "--config features.codex_hooks=false --config features.hooks=false",
515 forbidArg: "--enable",
516 },
517 (textGeneration) =>
518 Effect.gen(function* () {
519 const result = yield* textGeneration.generateThreadTitle({
520 cwd: process.cwd(),
521 message: "Describe this change",
522 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
523 });
524 expect(result.title).toBe("Hookless title");
525 }),
526 ),
527 );
528​
529 it.effect("identifies codex exec as T3 Code", () =>
530 withFakeCodexEnv(
531 { output: JSON.stringify({ title: "Live title" }), requireOriginator: "T3 Code" },
532 (textGeneration) =>
533 Effect.gen(function* () {
534 const result = yield* textGeneration.generateThreadTitle({
535 cwd: process.cwd(),
536 message: "Name this thread",
537 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
538 });
539 expect(result.title).toBe("Live title");
540 }),
541 ),
542 );
543​
544 it.effect("passes exec-safe launch args into codex exec", () =>
545 withFakeCodexEnv(
546 {
547 output: JSON.stringify({
548 subject: "Add important change",
549 body: "",
550 }),
551 launchArgs: "--strict-config --oss --local-provider ollama --listen off",
552 requireArg: "--strict-config --oss --local-provider ollama",
553 forbidArg: "--listen",
554 },
555 (textGeneration) =>
556 textGeneration.generateCommitMessage({
557 cwd: process.cwd(),
558 branch: "feature/codex-effect",
559 stagedSummary: "M README.md",
560 stagedPatch: "diff --git a/README.md b/README.md",
561 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
562 }),
563 ),
564 );
565​
566 it.effect("generates branch names even when the ambient scope is already closed", () =>
567 withFakeCodexEnv(
568 {
569 output: JSON.stringify({
570 branch: "feat/background-generation",
571 }),
572 },
573 (textGeneration) =>
574 Effect.gen(function* () {
575 // Background fibers can outlive request scopes; temp files scoped there would be reaped on creation.
576 const closedScope = yield* Scope.make();
577 yield* Scope.close(closedScope, Exit.void);
578​
579 const generated = yield* textGeneration
580 .generateBranchName({
581 cwd: process.cwd(),
582 message: "Please update session handling.",
583 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
584 })
585 .pipe(Effect.provideService(Scope.Scope, closedScope));
586​
587 expect(generated.branch).toBe("feat/background-generation");
588 }),
589 ),
590 );
591​
592 it.effect("returns the refinement signal for an unresolved subject", () =>
593 withFakeCodexEnv(
594 { output: JSON.stringify({ title: "Investigate issue", needsRefinement: true }) },
595 (textGeneration) =>
596 Effect.gen(function* () {
597 expect(
598 yield* textGeneration.generateThreadTitle({
599 cwd: process.cwd(),
600 message: "Fix this",
601 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
602 }),
603 ).toEqual({ title: "Investigate issue", needsRefinement: true });
604 }),
605 ),
606 );
607​
608 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
609 withFakeCodexEnv(
610 {
611 output: JSON.stringify({
612 branch: "fix/ui-regression",
613 }),
614 requireImage: true,
615 },
616 (textGeneration) =>
617 Effect.gen(function* () {
618 const fs = yield* FileSystem.FileSystem;
619 const path = yield* Path.Path;
620 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
621 const attachmentId = "thread-1-attachment";
622 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
623 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
624 yield* fs.writeFile(imagePath, Buffer.from("hello"));
625​
626 const generated = yield* textGeneration
627 .generateBranchName({
628 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
629 cwd: process.cwd(),
630 message: "Fix layout bug from screenshot.",
631 attachments: [
632 {
633 type: "image",
634 id: attachmentId,
635 name: "bug.png",
636 mimeType: "image/png",
637 sizeBytes: 5,
638 },
639 ],
640 })
641 .pipe(
642 Effect.tap(() =>
643 fs.stat(imagePath).pipe(
644 Effect.map((fileInfo) => {
645 expect(fileInfo.type).toBe("File");
646 }),
647 ),
648 ),
649 Effect.ensuring(fs.remove(imagePath).pipe(Effect.ignore)),
650 );
651​
652 expect(generated.branch).toBe("fix/ui-regression");
653 }),
654 ),
655 );
656});
657​
658const PREFLIGHT_PRIMARY_STATES = [
659 "ready",
660 "pending",
661 "exhausted",
662 "not installed",
663 "not installed, fallback disabled for project",
664 "not installed, fallback model cannot generate text",
665 "signed out",
666 "signed out, fallback failed",
667 "cannot generate text",
668 "model cannot generate text",
669 "disabled",
670 "disabled, thread default model cannot generate text",
671 "disabled, fallback disabled for project",
672] as const;
673​
674it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (primaryState) =>
675 Effect.gen(function* () {
676 const primary = ProviderInstanceId.make("codex");
677 const fallback = ProviderInstanceId.make("claude_work");
678 const projectId = ProjectId.make("project-a");
679 const selection = {
680 instanceId: primary,
681 model: "chat-model",
682 options: [{ id: "effort", value: "high" }],
683 };
684 const threadDefault = {
685 instanceId: fallback,
686 model: "z-ai/glm-5.3-flash",
687 options: [{ id: "thinking", value: false }],
688 };
689 const calls: ModelSelection[] = [];
690 const instances: ProviderInstance[] = [primary, fallback].map((instanceId) => {
691 const driver = ProviderDriverKind.make(instanceId === primary ? "codex" : "claudeAgent");
692 const snapshot: ServerProvider = {
693 instanceId,
694 driver,
695 enabled: true,
696 installed: true,
697 status: "ready",
698 auth: { status: "authenticated" },
699 version: null,
700 checkedAt: "1970-01-01T00:00:00Z",
701 models: [],
702 slashCommands: [],
703 skills: [],
704 ...(primaryState === "pending" && instanceId === primary
705 ? { installed: false, status: "warning", auth: { status: "unknown" } }
706 : {}),
707 ...(primaryState.startsWith("not installed") && instanceId === primary
708 ? { installed: false, status: "error", auth: { status: "unknown" } }
709 : {}),
710 ...(primaryState.startsWith("signed out") && instanceId === primary
711 ? { status: "error", auth: { status: "unauthenticated" } }
712 : {}),
713 ...(primaryState === "signed out, fallback failed" && instanceId === fallback
714 ? { status: "error", auth: { status: "unknown" } }
715 : {}),
716 ...(primaryState === "cannot generate text" && instanceId === primary
717 ? { supportsTextGeneration: false }
718 : {}),
719 ...(primaryState === "model cannot generate text" && instanceId === primary
720 ? {
721 models: [
722 {
723 slug: selection.model,
724 name: selection.model,
725 isCustom: false,
726 supportsTextGeneration: false,
727 capabilities: null,
728 },
729 ],
730 }
731 : {}),
732 ...((primaryState === "not installed, fallback model cannot generate text" ||
733 primaryState === "disabled, thread default model cannot generate text") &&
734 instanceId === fallback
735 ? {
736 models: [
737 {
738 slug: threadDefault.model,
739 name: threadDefault.model,
740 isCustom: true,
741 supportsTextGeneration: false,
742 capabilities: null,
743 },
744 ],
745 }
746 : {}),
747 ...(primaryState.startsWith("disabled") && instanceId === primary
748 ? { enabled: false, status: "disabled" }
749 : {}),
750 ...(primaryState === "exhausted" && instanceId === primary
751 ? {
752 usageLimits: {
753 checkedAt: "1970-01-01T00:00:00Z",
754 windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 100 }],
755 },
756 }
757 : {}),
758 };
759 return {
760 instanceId,
761 driverKind: driver,
762 continuationIdentity: { driverKind: driver, continuationKey: instanceId },
763 displayName: undefined,
764 enabled: true,
765 snapshot: { getSnapshot: Effect.succeed(snapshot) } as ProviderInstance["snapshot"],
766 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
767 textGeneration: TextGeneration.TextGeneration.of({
768 generateCommitMessage: () => Effect.die("unused"),
769 generatePrContent: () => Effect.die("unused"),
770 generateBranchName: () => Effect.die("unused"),
771 generateReviewGuide: () => Effect.die("unused"),
772 generateTranscriptionPostProcessing: () => Effect.die("unused"),
773 generateThreadTitle: (input) =>
774 Effect.sync(() => {
775 calls.push(input.modelSelection);
776 return { title: "Generated title" };
777 }),
778 }),
779 };
780 });
781 const service = yield* TextGeneration.make.pipe(
782 Effect.provide(
783 Layer.mergeAll(
784 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
785 listInstances: Effect.succeed(instances),
786 getInstance: (id) =>
787 Effect.succeed(instances.find((instance) => instance.instanceId === id)),
788 }),
789 ServerSettings.layerTest({
790 providerInstances: {
791 [fallback]: {
792 driver: ProviderDriverKind.make("claudeAgent"),
793 config: { customModels: [threadDefault.model] },
794 },
795 },
796 defaultModelSelection: threadDefault,
797 ...(primaryState.endsWith("fallback disabled for project")
798 ? {
799 projectSettingsOverrides: {
800 [projectId]: { providerInstances: { [fallback]: { enabled: false } } },
801 },
802 }
803 : {}),
804 }),
805 Layer.mock(TextGenerators.TextGenerators)({ runner: () => Effect.undefined }),
806 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
807 resolveLink: () => Effect.die("unused"),
808 }),
809 ProviderInstallationGate.layer,
810 ),
811 ),
812 );
813 const generated = yield* service
814 .generateThreadTitle({
815 cwd: "/tmp",
816 message: "hello",
817 linkedContext: "",
818 modelSelection:
819 primaryState === "disabled, thread default model cannot generate text"
820 ? threadDefault
821 : selection,
822 projectId,
823 })
824 .pipe(Effect.exit);
825 if (primaryState === "disabled, fallback disabled for project") {
826 expect(Exit.isFailure(generated)).toBe(true);
827 expect(calls).toEqual([]);
828 return;
829 }
830 expect(generated).toEqual(Exit.succeed({ title: "Generated title" }));
831 expect(calls).toEqual([
832 primaryState === "ready" ||
833 primaryState === "pending" ||
834 primaryState === "not installed, fallback disabled for project" ||
835 primaryState === "signed out, fallback failed"
836 ? selection
837 : primaryState === "not installed, fallback model cannot generate text" ||
838 primaryState === "disabled, thread default model cannot generate text"
839 ? {
840 instanceId: fallback,
841 model:
842 DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[ProviderDriverKind.make("claudeAgent")],
843 }
844 : threadDefault,
845 ]);
846 }),
847);
848​
849it.effect(
850 "a review guide aimed at a text generator falls back to an agent that can read the checkout",
851 () =>
852 Effect.gen(function* () {
853 const claude = ProviderInstanceId.make("claudeAgent");
854 const driver = ProviderDriverKind.make("claudeAgent");
855 const calls: ModelSelection[] = [];
856 const instance = {
857 instanceId: claude,
858 driverKind: driver,
859 continuationIdentity: { driverKind: driver, continuationKey: claude },
860 displayName: undefined,
861 enabled: true,
862 snapshot: {
863 getSnapshot: Effect.succeed<ServerProvider>({
864 instanceId: claude,
865 driver,
866 enabled: true,
867 installed: true,
868 status: "ready",
869 auth: { status: "authenticated" },
870 version: null,
871 checkedAt: "1970-01-01T00:00:00Z",
872 models: [],
873 slashCommands: [],
874 skills: [],
875 }),
876 } as ProviderInstance["snapshot"],
877 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
878 textGeneration: TextGeneration.TextGeneration.of({
879 generateCommitMessage: () => Effect.die("unused"),
880 generatePrContent: () => Effect.die("unused"),
881 generateBranchName: () => Effect.die("unused"),
882 generateThreadTitle: () => Effect.die("unused"),
883 generateTranscriptionPostProcessing: () => Effect.die("unused"),
884 generateReviewGuide: (input) =>
885 Effect.sync(() => {
886 calls.push(input.modelSelection);
887 return {} as TextGeneration.ReviewGuideGenerationResult;
888 }),
889 }),
890 } satisfies ProviderInstance;
891 const serviceWith = (instances: ReadonlyArray<ProviderInstance>) =>
892 TextGeneration.make.pipe(
893 Effect.provide(
894 Layer.mergeAll(
895 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
896 listInstances: Effect.succeed(instances),
897 getInstance: (id) =>
898 Effect.succeed(instances.find((candidate) => candidate.instanceId === id)),
899 }),
900 ServerSettings.layerTest({}),
901 Layer.mock(TextGenerators.TextGenerators)({
902 runner: (id) =>
903 Effect.succeed(
904 id === "openrouter"
905 ? () => Effect.die("a text generator cannot investigate")
906 : undefined,
907 ),
908 }),
909 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
910 resolveLink: () => Effect.die("unused"),
911 }),
912 ProviderInstallationGate.layer,
913 ),
914 ),
915 );
916 const input = {
917 cwd: "/tmp",
918 projectCwd: "/tmp",
919 number: 1,
920 title: "Change",
921 description: "",
922 baseBranch: "main",
923 baseCommit: "abc",
924 settledReview: "",
925 modelSelection: { instanceId: ProviderInstanceId.make("openrouter"), model: "some/model" },
926 };
927 yield* (yield* serviceWith([instance])).generateReviewGuide(input);
928 expect(calls.map((selection) => selection.instanceId)).toEqual([claude]);
929​
930 // With no agent ready, it says what is missing instead of looking up a provider by that id.
931 const failure = yield* Effect.flip((yield* serviceWith([])).generateReviewGuide(input));
932 expect(failure.detail).toMatch(
933 /^Review guides need a coding agent that can read the checkout/,
934 );
935 }),
936);