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

CodexTextGeneration.test.ts

875 lines33.5 KB

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