Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it } from "@effect/vitest";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as Result from "effect/Result";
11import * as Schema from "effect/Schema";
12import * as Scope from "effect/Scope";
13import { createModelSelection } from "@t3tools/shared/model";
14import { expect } from "vite-plus/test";
15
16import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
17
18import * as ServerConfig from "../config.ts";
19import { makeProcessProbe, processProbeSource } from "../testUtils/processProbe.ts";
20import * as TextGeneration from "./TextGeneration.ts";
21import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
22import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
23const decodeCodexSettings = Schema.decodeSync(CodexSettings);
24
25const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
26 ProviderInstanceId.make("codex"),
27 "gpt-5.4-mini",
28);
29
30const layerCodexTextGenerationTest = ServerConfig.ServerConfig.layerTest(process.cwd(), {
31 prefix: "t3code-codex-text-generation-test-",
32}).pipe(Layer.provideMerge(NodeServices.layer));
33
34interface FakeCodexInput {
35 output: string;
36 lifecycle?: { port: number; command: "exec" | "mcp list" };
37 exitCode?: number;
38 stderr?: string;
39 requireImage?: boolean;
40 requireServiceTier?: string;
41 requireReasoningEffort?: string;
42 forbidReasoningEffort?: boolean;
43 requireArg?: string;
44 forbidArg?: string;
45 stdinMustContain?: string;
46 stdinMustNotContain?: string;
47 mcpServers?: ReadonlyArray<{ name: string; enabled: boolean }> | number;
48}
49
50function makeFakeCodexBinary(dir: string, input: FakeCodexInput) {
51 const check = JSON.stringify({
52 requireImage: input.requireImage ?? false,
53 requireServiceTier: input.requireServiceTier ?? null,
54 requireReasoningEffort: input.requireReasoningEffort ?? null,
55 forbidReasoningEffort: input.forbidReasoningEffort ?? false,
56 requireArg: input.requireArg ?? null,
57 forbidArg: input.forbidArg ?? null,
58 stdinMustContain: input.stdinMustContain ?? null,
59 stdinMustNotContain: input.stdinMustNotContain ?? null,
60 mcpServers: input.mcpServers ?? [],
61 stderr: input.stderr ?? null,
62 output: input.output,
63 exitCode: input.exitCode ?? 0,
64 });
65 return Effect.gen(function* () {
66 const path = yield* Path.Path;
67 return writeFakeCli({
68 directory: path.join(dir, "bin"),
69 name: "codex",
70 source: [
71 'import * as NodeFS from "node:fs";',
72 `const check = ${check};`,
73 "const args = process.argv.slice(2);",
74 'const isMcpList = args.includes("mcp") && args.includes("list");',
75 ...(input.lifecycle === undefined
76 ? []
77 : [
78 `if (isMcpList === ${input.lifecycle.command === "mcp list"}) {`,
79 'process.on("SIGTERM", () => {});',
80 processProbeSource(input.lifecycle.port),
81 "await new Promise(() => {});",
82 "}",
83 ]),
84 "if (isMcpList) {",
85 ' if (typeof check.mcpServers === "number") process.exit(check.mcpServers);',
86 " process.stdout.write(JSON.stringify(check.mcpServers));",
87 " process.exit(0);",
88 "}",
89 'const originalArgs = ` ${args.join(" ")} `;',
90 "let outputPath = null;",
91 "let seenImage = false;",
92 'let seenServiceTier = "";',
93 'let seenReasoningEffort = "";',
94 "for (let index = 0; index < args.length; index += 1) {",
95 ' if (args[index] === "--image") {',
96 " index += 1;",
97 " if (args[index]) seenImage = true;",
98 ' } else if (args[index] === "--config") {',
99 " index += 1;",
100 ' const value = args[index] ?? "";',
101 ' if (value.startsWith("service_tier=")) seenServiceTier = value;',
102 ' if (value.startsWith("model_reasoning_effort=")) seenReasoningEffort = value;',
103 ' } else if (args[index] === "--output-last-message") {',
104 " index += 1;",
105 " outputPath = args[index] ?? null;",
106 " }",
107 "}",
108 "const chunks = [];",
109 "for await (const chunk of process.stdin) chunks.push(chunk);",
110 'const stdinContent = Buffer.concat(chunks).toString("utf8");',
111 "function fail(message, code) {",
112 ' process.stderr.write(message + "\\n");',
113 " process.exit(code);",
114 "}",
115 "if (check.requireArg !== null && !originalArgs.includes(` ${check.requireArg} `)) {",
116 ' fail("missing arg: " + check.requireArg, 8);',
117 "}",
118 "if (check.forbidArg !== null && originalArgs.includes(` ${check.forbidArg} `)) {",
119 ' fail("forbidden arg: " + check.forbidArg, 9);',
120 "}",
121 'if (check.requireImage && !seenImage) fail("missing --image input", 2);',
122 "if (",
123 " check.requireServiceTier !== null &&",
124 ' seenServiceTier !== `service_tier="${check.requireServiceTier}"`',
125 ") {",
126 ' fail("unexpected service tier config: " + seenServiceTier, 5);',
127 "}",
128 "if (",
129 " check.requireReasoningEffort !== null &&",
130 ' seenReasoningEffort !== `model_reasoning_effort="${check.requireReasoningEffort}"`',
131 ") {",
132 ' fail("unexpected reasoning effort config: " + seenReasoningEffort, 6);',
133 "}",
134 "if (check.forbidReasoningEffort && seenReasoningEffort.length > 0) {",
135 ' fail("reasoning effort config should be omitted: " + seenReasoningEffort, 7);',
136 "}",
137 "if (check.stdinMustContain !== null && !stdinContent.includes(check.stdinMustContain)) {",
138 ' fail("stdin missing expected content", 3);',
139 "}",
140 "if (check.stdinMustNotContain !== null && stdinContent.includes(check.stdinMustNotContain)) {",
141 ' fail("stdin contained forbidden content", 4);',
142 "}",
143 'if (check.stderr !== null) process.stderr.write(check.stderr + "\\n");',
144 'if (outputPath !== null) NodeFS.writeFileSync(outputPath, check.output + "\\n");',
145 "process.exitCode = check.exitCode;",
146 "",
147 ].join("\n"),
148 });
149 });
150}
151
152function withFakeCodexEnv<A, E, R>(
153 input: FakeCodexInput & {
154 launchArgs?: string;
155 environment?: NodeJS.ProcessEnv;
156 models?: ReadonlyArray<string>;
157 managedRuntime?: boolean;
158 },
159 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
160) {
161 return Effect.gen(function* () {
162 const fs = yield* FileSystem.FileSystem;
163 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
164 const codexPath = yield* makeFakeCodexBinary(tempDir, input);
165 const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs });
166 const textGeneration = yield* makeCodexTextGeneration(
167 config,
168 input.environment === undefined ? undefined : { ...process.env, ...input.environment },
169 Effect.succeed(
170 (input.models ?? []).map((slug) => ({
171 slug,
172 name: slug,
173 isCustom: false,
174 capabilities: null,
175 })),
176 ),
177 input.managedRuntime
178 ? Effect.succeed({
179 config,
180 environment: input.environment ?? process.env,
181 revision: "test",
182 })
183 : undefined,
184 );
185 return yield* effectFn(textGeneration);
186 }).pipe(Effect.scoped);
187}
188
189it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => {
190 it.effect.each(["exec", "mcp list"] as const)(
191 "kills a stalled %s CLI when its request is interrupted",
192 (command) =>
193 Effect.gen(function* () {
194 const probe = yield* makeProcessProbe;
195 yield* withFakeCodexEnv(
196 { output: "", lifecycle: { port: probe.port, command } },
197 (textGeneration) =>
198 Effect.gen(function* () {
199 const fiber = yield* textGeneration
200 .generateThreadTitle({
201 cwd: process.cwd(),
202 message: "Name this thread",
203 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
204 })
205 .pipe(Effect.forkScoped);
206 yield* probe.started;
207
208 const interrupted = yield* Fiber.interrupt(fiber).pipe(Effect.forkScoped);
209 yield* probe.exited;
210 yield* Fiber.join(interrupted);
211 const exit = yield* Fiber.await(fiber);
212 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
213 }),
214 );
215 }),
216 );
217
218 it.effect.each(["gpt-5.6-luna", "openai.gpt-5.6-luna"])(
219 "dispatches the qualified live model for %s",
220 (selectedModel) =>
221 withFakeCodexEnv(
222 {
223 output: JSON.stringify({ title: "Bedrock title" }),
224 models: ["openai.gpt-5.6-luna"],
225 requireArg: "--model openai.gpt-5.6-luna",
226 forbidArg: "--model gpt-5.6-luna",
227 },
228 (textGeneration) =>
229 Effect.gen(function* () {
230 const result = yield* textGeneration.generateThreadTitle({
231 cwd: process.cwd(),
232 message: "Describe this change",
233 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), selectedModel),
234 });
235 expect(result.title).toBe("Bedrock title");
236 }),
237 ),
238 );
239 it.effect("generates and sanitizes commit messages without branch by default", () =>
240 withFakeCodexEnv(
241 {
242 output: JSON.stringify({
243 subject:
244 " Add important change to the system with too much detail and a trailing period.\nsecondary line",
245 body: "\n- added migration\n- updated tests\n",
246 }),
247 stdinMustNotContain: "branch must be a short semantic git branch fragment",
248 },
249 (textGeneration) =>
250 Effect.gen(function* () {
251 const generated = yield* textGeneration.generateCommitMessage({
252 cwd: process.cwd(),
253 branch: "feature/codex-effect",
254 stagedSummary: "M README.md",
255 stagedPatch: "diff --git a/README.md b/README.md",
256 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
257 });
258
259 expect(generated.subject.length).toBeLessThanOrEqual(72);
260 expect(generated.subject.endsWith(".")).toBe(false);
261 expect(generated.body).toBe("- added migration\n- updated tests");
262 expect(generated.branch).toBeUndefined();
263 }),
264 ),
265 );
266
267 it.effect(
268 "forwards codex service tier and non-default reasoning effort into codex exec config",
269 () =>
270 withFakeCodexEnv(
271 {
272 output: JSON.stringify({
273 subject: "Add important change",
274 body: "",
275 }),
276 requireServiceTier: "priority",
277 requireReasoningEffort: "xhigh",
278 stdinMustNotContain: "branch must be a short semantic git branch fragment",
279 },
280 (textGeneration) =>
281 textGeneration.generateCommitMessage({
282 cwd: process.cwd(),
283 branch: "feature/codex-effect",
284 stagedSummary: "M README.md",
285 stagedPatch: "diff --git a/README.md b/README.md",
286 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
287 { id: "reasoningEffort", value: "xhigh" },
288 { id: "serviceTier", value: "priority" },
289 ]),
290 }),
291 ),
292 );
293
294 it.effect("omits a persisted service tier for managed ChatGPT text generation", () =>
295 withFakeCodexEnv(
296 {
297 output: JSON.stringify({ subject: "Update project", body: "" }),
298 managedRuntime: true,
299 forbidArg: 'service_tier="priority"',
300 },
301 (textGeneration) =>
302 textGeneration.generateCommitMessage({
303 cwd: process.cwd(),
304 branch: "feature/chatgpt",
305 stagedSummary: "M README.md",
306 stagedPatch: "diff --git a/README.md b/README.md",
307 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
308 { id: "serviceTier", value: "priority" },
309 ]),
310 }),
311 ),
312 );
313
314 it.effect("generates titles with the user's MCP servers and plugins off", () =>
315 withFakeCodexEnv(
316 {
317 output: JSON.stringify({ title: "Remove default shapes" }),
318 mcpServers: [
319 { name: "augmenter", enabled: true },
320 { name: "my.server", enabled: true },
321 { name: "already-off", enabled: false },
322 ],
323 requireArg:
324 '--config features.plugins=false --config features.apps=false --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}}',
325 },
326 (textGeneration) =>
327 Effect.gen(function* () {
328 const result = yield* textGeneration.generateThreadTitle({
329 cwd: process.cwd(),
330 message: "Augmenter task 1. Use the Augmenter MCP: link_thread when you start.",
331 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
332 });
333 expect(result.title).toBe("Remove default shapes");
334 }),
335 ),
336 );
337
338 it.effect("still generates when Codex cannot list its MCP servers", () =>
339 withFakeCodexEnv(
340 {
341 output: JSON.stringify({ branch: "remove-default-shapes" }),
342 mcpServers: 2,
343 requireArg: "--config features.plugins=false --config features.apps=false --ephemeral",
344 forbidArg: "mcp_servers=",
345 },
346 (textGeneration) =>
347 Effect.gen(function* () {
348 const result = yield* textGeneration.generateBranchName({
349 cwd: process.cwd(),
350 message: "Remove default shapes from characters",
351 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
352 });
353 expect(result.branch).toBe("remove-default-shapes");
354 }),
355 ),
356 );
357
358 it.effect("keeps plugins and apps off over launch args that turn them on", () =>
359 withFakeCodexEnv(
360 {
361 output: JSON.stringify({ title: "Remove default shapes" }),
362 launchArgs: "--config features.plugins=true --config features.apps=true",
363 requireArg:
364 "--config features.plugins=true --config features.apps=true --config features.plugins=false --config features.apps=false --ephemeral",
365 },
366 (textGeneration) =>
367 Effect.gen(function* () {
368 const result = yield* textGeneration.generateThreadTitle({
369 cwd: process.cwd(),
370 message: "Remove default shapes from characters",
371 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
372 });
373 expect(result.title).toBe("Remove default shapes");
374 }),
375 ),
376 );
377
378 it.effect("passes exec-safe launch args into codex exec", () =>
379 withFakeCodexEnv(
380 {
381 output: JSON.stringify({
382 subject: "Add important change",
383 body: "",
384 }),
385 launchArgs: "--strict-config --listen off",
386 requireArg: "--strict-config",
387 forbidArg: "--listen",
388 },
389 (textGeneration) =>
390 textGeneration.generateCommitMessage({
391 cwd: process.cwd(),
392 branch: "feature/codex-effect",
393 stagedSummary: "M README.md",
394 stagedPatch: "diff --git a/README.md b/README.md",
395 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
396 }),
397 ),
398 );
399
400 it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for codex exec over settings", () =>
401 withFakeCodexEnv(
402 {
403 output: JSON.stringify({
404 subject: "Add important change",
405 body: "",
406 }),
407 launchArgs: "--enable settings-feature",
408 environment: { ...process.env, T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --listen off " },
409 requireArg: "--strict-config",
410 forbidArg: "settings-feature",
411 },
412 (textGeneration) =>
413 textGeneration.generateCommitMessage({
414 cwd: process.cwd(),
415 branch: "feature/codex-effect",
416 stagedSummary: "M README.md",
417 stagedPatch: "diff --git a/README.md b/README.md",
418 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
419 }),
420 ),
421 );
422
423 it.effect("defaults git text generation codex effort to low", () =>
424 withFakeCodexEnv(
425 {
426 output: JSON.stringify({
427 subject: "Add important change",
428 body: "",
429 }),
430 requireReasoningEffort: "low",
431 },
432 (textGeneration) =>
433 textGeneration.generateCommitMessage({
434 cwd: process.cwd(),
435 branch: "feature/codex-effect",
436 stagedSummary: "M README.md",
437 stagedPatch: "diff --git a/README.md b/README.md",
438 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
439 }),
440 ),
441 );
442
443 it.effect("generates commit message with branch when includeBranch is true", () =>
444 withFakeCodexEnv(
445 {
446 output: JSON.stringify({
447 subject: "Add important change",
448 body: "",
449 branch: "fix/important-system-change",
450 }),
451 stdinMustContain: "branch must be a short semantic git branch fragment",
452 },
453 (textGeneration) =>
454 Effect.gen(function* () {
455 const generated = yield* textGeneration.generateCommitMessage({
456 cwd: process.cwd(),
457 branch: "feature/codex-effect",
458 stagedSummary: "M README.md",
459 stagedPatch: "diff --git a/README.md b/README.md",
460 includeBranch: true,
461 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
462 });
463
464 expect(generated.subject).toBe("Add important change");
465 expect(generated.branch).toBe("fix/important-system-change");
466 }),
467 ),
468 );
469
470 it.effect("generates PR content and trims markdown body", () =>
471 withFakeCodexEnv(
472 {
473 output: JSON.stringify({
474 title: " Improve orchestration flow\nwith ignored suffix",
475 body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
476 }),
477 },
478 (textGeneration) =>
479 Effect.gen(function* () {
480 const generated = yield* textGeneration.generatePrContent({
481 cwd: process.cwd(),
482 baseBranch: "main",
483 headBranch: "feature/codex-effect",
484 commitSummary: "feat: improve orchestration flow",
485 diffSummary: "2 files changed",
486 diffPatch: "diff --git a/a.ts b/a.ts",
487 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
488 });
489
490 expect(generated.title).toBe("Improve orchestration flow");
491 expect(generated.body.startsWith("## Summary")).toBe(true);
492 expect(generated.body.endsWith("\n\n")).toBe(false);
493 }),
494 ),
495 );
496
497 it.effect("generates branch names and normalizes branch fragments", () =>
498 withFakeCodexEnv(
499 {
500 output: JSON.stringify({
501 branch: " Feat/Session ",
502 }),
503 stdinMustNotContain: "Image attachments supplied to the model",
504 },
505 (textGeneration) =>
506 Effect.gen(function* () {
507 const generated = yield* textGeneration.generateBranchName({
508 cwd: process.cwd(),
509 message: "Please update session handling.",
510 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
511 });
512
513 expect(generated.branch).toBe("feat/session");
514 }),
515 ),
516 );
517
518 it.effect.each([
519 {
520 mode: "static",
521 output: "Add Search",
522 expected: "team/add-search",
523 instruction: "without a prefix or namespace",
524 },
525 {
526 mode: "semantic",
527 output: "feat/add-search",
528 expected: "feat/add-search",
529 instruction: "semantic prefix",
530 },
531 {
532 mode: "custom",
533 output: "Julius/ABC-123.v2",
534 expected: "Julius/ABC-123.v2",
535 instruction: "Preserve the issue ID and capitalization.",
536 },
537 ] as const)("generates a branch using $mode naming", (example) =>
538 withFakeCodexEnv(
539 {
540 output: JSON.stringify({ branch: example.output }),
541 stdinMustContain: example.instruction,
542 },
543 (textGeneration) =>
544 Effect.gen(function* () {
545 const generated = yield* textGeneration.generateBranchName({
546 cwd: process.cwd(),
547 message: "Add search",
548 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
549 naming: {
550 mode: example.mode,
551 prefix: "team/",
552 instructions: "Preserve the issue ID and capitalization.",
553 },
554 });
555 expect(generated.branch).toBe(example.expected);
556 }),
557 ),
558 );
559
560 it.effect("generates branch names even when the ambient scope is already closed", () =>
561 withFakeCodexEnv(
562 {
563 output: JSON.stringify({
564 branch: "feat/background-generation",
565 }),
566 },
567 (textGeneration) =>
568 Effect.gen(function* () {
569 // Background fibers (e.g. the worktree branch rename fork) can run
570 // after their launching request's scope has closed; temp files must
571 // not be tied to that ambient scope or they are reaped on creation.
572 const closedScope = yield* Scope.make();
573 yield* Scope.close(closedScope, Exit.void);
574
575 const generated = yield* textGeneration
576 .generateBranchName({
577 cwd: process.cwd(),
578 message: "Please update session handling.",
579 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
580 })
581 .pipe(Effect.provideService(Scope.Scope, closedScope));
582
583 expect(generated.branch).toBe("feat/background-generation");
584 }),
585 ),
586 );
587
588 it.effect("generates thread titles and trims them for sidebar use", () =>
589 withFakeCodexEnv(
590 {
591 output: JSON.stringify({
592 title:
593 ' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
594 }),
595 },
596 (textGeneration) =>
597 Effect.gen(function* () {
598 const generated = yield* textGeneration.generateThreadTitle({
599 cwd: process.cwd(),
600 message: "Please investigate websocket reconnect regressions after a worktree restore.",
601 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
602 });
603
604 expect(generated.title).toBe(
605 "Investigate websocket reconnect regressions after worktree restore",
606 );
607 }),
608 ),
609 );
610
611 it.effect("returns the refinement signal for an unresolved subject", () =>
612 withFakeCodexEnv(
613 { output: JSON.stringify({ title: "Investigate issue", needsRefinement: true }) },
614 (textGeneration) =>
615 Effect.gen(function* () {
616 expect(
617 yield* textGeneration.generateThreadTitle({
618 cwd: process.cwd(),
619 message: "Fix this",
620 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
621 }),
622 ).toEqual({ title: "Investigate issue", needsRefinement: true });
623 }),
624 ),
625 );
626
627 it.effect("falls back when thread title normalization becomes whitespace-only", () =>
628 withFakeCodexEnv(
629 {
630 output: JSON.stringify({
631 title: ' """ """ ',
632 }),
633 },
634 (textGeneration) =>
635 Effect.gen(function* () {
636 const generated = yield* textGeneration.generateThreadTitle({
637 cwd: process.cwd(),
638 message: "Name this thread.",
639 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
640 });
641
642 expect(generated.title).toBe("New thread");
643 }),
644 ),
645 );
646
647 it.effect("trims whitespace exposed after quote removal in thread titles", () =>
648 withFakeCodexEnv(
649 {
650 output: JSON.stringify({
651 title: ` "' hello world '" `,
652 }),
653 },
654 (textGeneration) =>
655 Effect.gen(function* () {
656 const generated = yield* textGeneration.generateThreadTitle({
657 cwd: process.cwd(),
658 message: "Name this thread.",
659 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
660 });
661
662 expect(generated.title).toBe("hello world");
663 }),
664 ),
665 );
666
667 it.effect("omits attachment metadata section when no attachments are provided", () =>
668 withFakeCodexEnv(
669 {
670 output: JSON.stringify({
671 branch: "fix/session-timeout",
672 }),
673 stdinMustNotContain: "Attachment metadata:",
674 },
675 (textGeneration) =>
676 Effect.gen(function* () {
677 const generated = yield* textGeneration.generateBranchName({
678 cwd: process.cwd(),
679 message: "Fix timeout behavior.",
680 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
681 });
682
683 expect(generated.branch).toBe("fix/session-timeout");
684 }),
685 ),
686 );
687
688 it.effect("passes image attachments through as codex image inputs", () =>
689 withFakeCodexEnv(
690 {
691 output: JSON.stringify({
692 branch: "fix/ui-regression",
693 }),
694 requireImage: true,
695 stdinMustContain: "Attachment metadata:",
696 },
697 (textGeneration) =>
698 Effect.gen(function* () {
699 const fs = yield* FileSystem.FileSystem;
700 const path = yield* Path.Path;
701 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
702 const attachmentId = "thread-branch-image-attachment";
703 const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
704 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
705 yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
706
707 const generated = yield* textGeneration.generateBranchName({
708 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
709 cwd: process.cwd(),
710 message: "Fix layout bug from screenshot.",
711 attachments: [
712 {
713 type: "image",
714 id: attachmentId,
715 name: "bug.png",
716 mimeType: "image/png",
717 sizeBytes: 5,
718 },
719 ],
720 });
721
722 expect(generated.branch).toBe("fix/ui-regression");
723 }),
724 ),
725 );
726
727 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
728 withFakeCodexEnv(
729 {
730 output: JSON.stringify({
731 branch: "fix/ui-regression",
732 }),
733 requireImage: true,
734 },
735 (textGeneration) =>
736 Effect.gen(function* () {
737 const fs = yield* FileSystem.FileSystem;
738 const path = yield* Path.Path;
739 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
740 const attachmentId = "thread-1-attachment";
741 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
742 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
743 yield* fs.writeFile(imagePath, Buffer.from("hello"));
744
745 const generated = yield* textGeneration
746 .generateBranchName({
747 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
748 cwd: process.cwd(),
749 message: "Fix layout bug from screenshot.",
750 attachments: [
751 {
752 type: "image",
753 id: attachmentId,
754 name: "bug.png",
755 mimeType: "image/png",
756 sizeBytes: 5,
757 },
758 ],
759 })
760 .pipe(
761 Effect.tap(() =>
762 fs.stat(imagePath).pipe(
763 Effect.map((fileInfo) => {
764 expect(fileInfo.type).toBe("File");
765 }),
766 ),
767 ),
768 Effect.ensuring(fs.remove(imagePath).pipe(Effect.ignore)),
769 );
770
771 expect(generated.branch).toBe("fix/ui-regression");
772 }),
773 ),
774 );
775
776 it.effect("ignores missing attachment ids for codex image inputs", () =>
777 withFakeCodexEnv(
778 {
779 output: JSON.stringify({
780 branch: "fix/ui-regression",
781 }),
782 requireImage: true,
783 },
784 (textGeneration) =>
785 Effect.gen(function* () {
786 const fs = yield* FileSystem.FileSystem;
787 const path = yield* Path.Path;
788 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
789 const missingAttachmentId = "thread-missing-attachment";
790 const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
791 yield* fs.remove(missingPath).pipe(Effect.ignore);
792
793 const result = yield* textGeneration
794 .generateBranchName({
795 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
796 cwd: process.cwd(),
797 message: "Fix layout bug from screenshot.",
798 attachments: [
799 {
800 type: "image",
801 id: missingAttachmentId,
802 name: "outside.png",
803 mimeType: "image/png",
804 sizeBytes: 5,
805 },
806 ],
807 })
808 .pipe(Effect.result);
809
810 expect(Result.isFailure(result)).toBe(true);
811 if (Result.isFailure(result)) {
812 expect(result.failure).toBeInstanceOf(TextGenerationError);
813 expect(result.failure.message).toContain("missing --image input");
814 }
815 }),
816 ),
817 );
818
819 it.effect(
820 "fails with typed TextGenerationError when codex returns wrong branch payload shape",
821 () =>
822 withFakeCodexEnv(
823 {
824 output: JSON.stringify({
825 title: "This is not a branch payload",
826 }),
827 },
828 (textGeneration) =>
829 Effect.gen(function* () {
830 const result = yield* textGeneration
831 .generateBranchName({
832 cwd: process.cwd(),
833 message: "Fix websocket reconnect flake",
834 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
835 })
836 .pipe(Effect.result);
837
838 expect(Result.isFailure(result)).toBe(true);
839 if (Result.isFailure(result)) {
840 expect(result.failure).toBeInstanceOf(TextGenerationError);
841 expect(result.failure.message).toContain("Codex returned invalid structured output");
842 }
843 }),
844 ),
845 );
846
847 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
848 withFakeCodexEnv(
849 {
850 output: JSON.stringify({ subject: "ignored", body: "" }),
851 exitCode: 1,
852 stderr: "codex execution failed",
853 },
854 (textGeneration) =>
855 Effect.gen(function* () {
856 const result = yield* textGeneration
857 .generateCommitMessage({
858 cwd: process.cwd(),
859 branch: "feature/codex-error",
860 stagedSummary: "M README.md",
861 stagedPatch: "diff --git a/README.md b/README.md",
862 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
863 })
864 .pipe(Effect.result);
865
866 expect(Result.isFailure(result)).toBe(true);
867 if (Result.isFailure(result)) {
868 expect(result.failure).toBeInstanceOf(TextGenerationError);
869 expect(result.failure.message).toContain(
870 "Codex CLI command failed: codex execution failed",
871 );
872 }
873 }),
874 ),
875 );
876});