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

CodexTextGeneration.test.ts

767 lines26.4 KB

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