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

CodexTextGeneration.test.ts

741 lines25.6 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 CodexTextGenerationTestLayer = 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 },
141 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
142) {
143 return Effect.gen(function* () {
144 const fs = yield* FileSystem.FileSystem;
145 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
146 const codexPath = yield* makeFakeCodexBinary(tempDir, input);
147 const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs });
148 const textGeneration = yield* makeCodexTextGeneration(
149 config,
150 input.environment === undefined ? undefined : { ...process.env, ...input.environment },
151 Effect.succeed(
152 (input.models ?? []).map((slug) => ({
153 slug,
154 name: slug,
155 isCustom: false,
156 capabilities: null,
157 })),
158 ),
159 );
160 return yield* effectFn(textGeneration);
161 }).pipe(Effect.scoped);
163​
164it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
165 for (const selectedModel of ["gpt-5.6-luna", "openai.gpt-5.6-luna"]) {
166 it.effect(`dispatches the qualified live model for ${selectedModel}`, () =>
167 withFakeCodexEnv(
168 {
169 output: JSON.stringify({ title: "Bedrock title" }),
170 models: ["openai.gpt-5.6-luna"],
171 requireArg: "--model openai.gpt-5.6-luna",
172 forbidArg: "--model gpt-5.6-luna",
173 },
174 (textGeneration) =>
175 Effect.gen(function* () {
176 const result = yield* textGeneration.generateThreadTitle({
177 cwd: process.cwd(),
178 message: "Describe this change",
179 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), selectedModel),
180 });
181 expect(result.title).toBe("Bedrock title");
182 }),
183 ),
184 );
185 }
186 it.effect("generates and sanitizes commit messages without branch by default", () =>
187 withFakeCodexEnv(
188 {
189 output: JSON.stringify({
190 subject:
191 " Add important change to the system with too much detail and a trailing period.\nsecondary line",
192 body: "\n- added migration\n- updated tests\n",
193 }),
194 stdinMustNotContain: "branch must be a short semantic git branch fragment",
195 },
196 (textGeneration) =>
197 Effect.gen(function* () {
198 const generated = yield* textGeneration.generateCommitMessage({
199 cwd: process.cwd(),
200 branch: "feature/codex-effect",
201 stagedSummary: "M README.md",
202 stagedPatch: "diff --git a/README.md b/README.md",
203 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
204 });
205​
206 expect(generated.subject.length).toBeLessThanOrEqual(72);
207 expect(generated.subject.endsWith(".")).toBe(false);
208 expect(generated.body).toBe("- added migration\n- updated tests");
209 expect(generated.branch).toBeUndefined();
210 }),
211 ),
212 );
213​
214 it.effect(
215 "forwards codex service tier and non-default reasoning effort into codex exec config",
216 () =>
217 withFakeCodexEnv(
218 {
219 output: JSON.stringify({
220 subject: "Add important change",
221 body: "",
222 }),
223 requireServiceTier: "priority",
224 requireReasoningEffort: "xhigh",
225 stdinMustNotContain: "branch must be a short semantic git branch fragment",
226 },
227 (textGeneration) =>
228 textGeneration.generateCommitMessage({
229 cwd: process.cwd(),
230 branch: "feature/codex-effect",
231 stagedSummary: "M README.md",
232 stagedPatch: "diff --git a/README.md b/README.md",
233 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
234 { id: "reasoningEffort", value: "xhigh" },
235 { id: "serviceTier", value: "priority" },
236 ]),
237 }),
238 ),
239 );
240​
241 it.effect("passes exec-safe launch args into codex exec", () =>
242 withFakeCodexEnv(
243 {
244 output: JSON.stringify({
245 subject: "Add important change",
246 body: "",
247 }),
248 launchArgs: "--strict-config --listen off",
249 requireArg: "--strict-config",
250 forbidArg: "--listen",
251 },
252 (textGeneration) =>
253 textGeneration.generateCommitMessage({
254 cwd: process.cwd(),
255 branch: "feature/codex-effect",
256 stagedSummary: "M README.md",
257 stagedPatch: "diff --git a/README.md b/README.md",
258 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
259 }),
260 ),
261 );
262​
263 it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for codex exec over settings", () =>
264 withFakeCodexEnv(
265 {
266 output: JSON.stringify({
267 subject: "Add important change",
268 body: "",
269 }),
270 launchArgs: "--enable settings-feature",
271 environment: { ...process.env, T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --listen off " },
272 requireArg: "--strict-config",
273 forbidArg: "settings-feature",
274 },
275 (textGeneration) =>
276 textGeneration.generateCommitMessage({
277 cwd: process.cwd(),
278 branch: "feature/codex-effect",
279 stagedSummary: "M README.md",
280 stagedPatch: "diff --git a/README.md b/README.md",
281 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
282 }),
283 ),
284 );
285​
286 it.effect("defaults git text generation codex effort to low", () =>
287 withFakeCodexEnv(
288 {
289 output: JSON.stringify({
290 subject: "Add important change",
291 body: "",
292 }),
293 requireReasoningEffort: "low",
294 },
295 (textGeneration) =>
296 textGeneration.generateCommitMessage({
297 cwd: process.cwd(),
298 branch: "feature/codex-effect",
299 stagedSummary: "M README.md",
300 stagedPatch: "diff --git a/README.md b/README.md",
301 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
302 }),
303 ),
304 );
305​
306 it.effect("generates commit message with branch when includeBranch is true", () =>
307 withFakeCodexEnv(
308 {
309 output: JSON.stringify({
310 subject: "Add important change",
311 body: "",
312 branch: "fix/important-system-change",
313 }),
314 stdinMustContain: "branch must be a short semantic git branch fragment",
315 },
316 (textGeneration) =>
317 Effect.gen(function* () {
318 const generated = yield* textGeneration.generateCommitMessage({
319 cwd: process.cwd(),
320 branch: "feature/codex-effect",
321 stagedSummary: "M README.md",
322 stagedPatch: "diff --git a/README.md b/README.md",
323 includeBranch: true,
324 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
325 });
326​
327 expect(generated.subject).toBe("Add important change");
328 expect(generated.branch).toBe("feature/fix/important-system-change");
329 }),
330 ),
331 );
332​
333 it.effect("generates PR content and trims markdown body", () =>
334 withFakeCodexEnv(
335 {
336 output: JSON.stringify({
337 title: " Improve orchestration flow\nwith ignored suffix",
338 body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
339 }),
340 },
341 (textGeneration) =>
342 Effect.gen(function* () {
343 const generated = yield* textGeneration.generatePrContent({
344 cwd: process.cwd(),
345 baseBranch: "main",
346 headBranch: "feature/codex-effect",
347 commitSummary: "feat: improve orchestration flow",
348 diffSummary: "2 files changed",
349 diffPatch: "diff --git a/a.ts b/a.ts",
350 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
351 });
352​
353 expect(generated.title).toBe("Improve orchestration flow");
354 expect(generated.body.startsWith("## Summary")).toBe(true);
355 expect(generated.body.endsWith("\n\n")).toBe(false);
356 }),
357 ),
358 );
359​
360 it.effect("generates branch names and normalizes branch fragments", () =>
361 withFakeCodexEnv(
362 {
363 output: JSON.stringify({
364 branch: " Feat/Session ",
365 }),
366 stdinMustNotContain: "Image attachments supplied to the model",
367 },
368 (textGeneration) =>
369 Effect.gen(function* () {
370 const generated = yield* textGeneration.generateBranchName({
371 cwd: process.cwd(),
372 message: "Please update session handling.",
373 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
374 });
375​
376 expect(generated.branch).toBe("feat/session");
377 }),
378 ),
379 );
380​
381 for (const example of [
382 {
383 mode: "static",
384 output: "Add Search",
385 expected: "team/add-search",
386 instruction: "without a prefix or namespace",
387 },
388 {
389 mode: "semantic",
390 output: "feat/add-search",
391 expected: "feat/add-search",
392 instruction: "semantic prefix",
393 },
394 {
395 mode: "custom",
396 output: "Julius/ABC-123.v2",
397 expected: "Julius/ABC-123.v2",
398 instruction: "Preserve the issue ID and capitalization.",
399 },
400 ] as const) {
401 it.effect(`generates a branch using ${example.mode} naming`, () =>
402 withFakeCodexEnv(
403 {
404 output: JSON.stringify({ branch: example.output }),
405 stdinMustContain: example.instruction,
406 },
407 (textGeneration) =>
408 Effect.gen(function* () {
409 const generated = yield* textGeneration.generateBranchName({
410 cwd: process.cwd(),
411 message: "Add search",
412 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
413 naming: {
414 mode: example.mode,
415 prefix: "team/",
416 instructions: "Preserve the issue ID and capitalization.",
417 },
418 });
419 expect(generated.branch).toBe(example.expected);
420 }),
421 ),
422 );
423 }
424​
425 it.effect("generates branch names even when the ambient scope is already closed", () =>
426 withFakeCodexEnv(
427 {
428 output: JSON.stringify({
429 branch: "feat/background-generation",
430 }),
431 },
432 (textGeneration) =>
433 Effect.gen(function* () {
434 // Background fibers (e.g. the worktree branch rename fork) can run
435 // after their launching request's scope has closed; temp files must
436 // not be tied to that ambient scope or they are reaped on creation.
437 const closedScope = yield* Scope.make();
438 yield* Scope.close(closedScope, Exit.void);
439​
440 const generated = yield* textGeneration
441 .generateBranchName({
442 cwd: process.cwd(),
443 message: "Please update session handling.",
444 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
445 })
446 .pipe(Effect.provideService(Scope.Scope, closedScope));
447​
448 expect(generated.branch).toBe("feat/background-generation");
449 }),
450 ),
451 );
452​
453 it.effect("generates thread titles and trims them for sidebar use", () =>
454 withFakeCodexEnv(
455 {
456 output: JSON.stringify({
457 title:
458 ' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
459 }),
460 },
461 (textGeneration) =>
462 Effect.gen(function* () {
463 const generated = yield* textGeneration.generateThreadTitle({
464 cwd: process.cwd(),
465 message: "Please investigate websocket reconnect regressions after a worktree restore.",
466 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
467 });
468​
469 expect(generated.title).toBe(
470 "Investigate websocket reconnect regressions after worktree restore",
471 );
472 }),
473 ),
474 );
475​
476 it.effect("returns the refinement signal for an unresolved subject", () =>
477 withFakeCodexEnv(
478 { output: JSON.stringify({ title: "Investigate issue", needsRefinement: true }) },
479 (textGeneration) =>
480 Effect.gen(function* () {
481 expect(
482 yield* textGeneration.generateThreadTitle({
483 cwd: process.cwd(),
484 message: "Fix this",
485 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
486 }),
487 ).toEqual({ title: "Investigate issue", needsRefinement: true });
488 }),
489 ),
490 );
491​
492 it.effect("falls back when thread title normalization becomes whitespace-only", () =>
493 withFakeCodexEnv(
494 {
495 output: JSON.stringify({
496 title: ' """ """ ',
497 }),
498 },
499 (textGeneration) =>
500 Effect.gen(function* () {
501 const generated = yield* textGeneration.generateThreadTitle({
502 cwd: process.cwd(),
503 message: "Name this thread.",
504 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
505 });
506​
507 expect(generated.title).toBe("New thread");
508 }),
509 ),
510 );
511​
512 it.effect("trims whitespace exposed after quote removal in thread titles", () =>
513 withFakeCodexEnv(
514 {
515 output: JSON.stringify({
516 title: ` "' hello world '" `,
517 }),
518 },
519 (textGeneration) =>
520 Effect.gen(function* () {
521 const generated = yield* textGeneration.generateThreadTitle({
522 cwd: process.cwd(),
523 message: "Name this thread.",
524 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
525 });
526​
527 expect(generated.title).toBe("hello world");
528 }),
529 ),
530 );
531​
532 it.effect("omits attachment metadata section when no attachments are provided", () =>
533 withFakeCodexEnv(
534 {
535 output: JSON.stringify({
536 branch: "fix/session-timeout",
537 }),
538 stdinMustNotContain: "Attachment metadata:",
539 },
540 (textGeneration) =>
541 Effect.gen(function* () {
542 const generated = yield* textGeneration.generateBranchName({
543 cwd: process.cwd(),
544 message: "Fix timeout behavior.",
545 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
546 });
547​
548 expect(generated.branch).toBe("fix/session-timeout");
549 }),
550 ),
551 );
552​
553 it.effect("passes image attachments through as codex image inputs", () =>
554 withFakeCodexEnv(
555 {
556 output: JSON.stringify({
557 branch: "fix/ui-regression",
558 }),
559 requireImage: true,
560 stdinMustContain: "Attachment metadata:",
561 },
562 (textGeneration) =>
563 Effect.gen(function* () {
564 const fs = yield* FileSystem.FileSystem;
565 const path = yield* Path.Path;
566 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
567 const attachmentId = "thread-branch-image-attachment";
568 const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
569 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
570 yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
571​
572 const generated = yield* textGeneration.generateBranchName({
573 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
574 cwd: process.cwd(),
575 message: "Fix layout bug from screenshot.",
576 attachments: [
577 {
578 type: "image",
579 id: attachmentId,
580 name: "bug.png",
581 mimeType: "image/png",
582 sizeBytes: 5,
583 },
584 ],
585 });
586​
587 expect(generated.branch).toBe("fix/ui-regression");
588 }),
589 ),
590 );
591​
592 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
593 withFakeCodexEnv(
594 {
595 output: JSON.stringify({
596 branch: "fix/ui-regression",
597 }),
598 requireImage: true,
599 },
600 (textGeneration) =>
601 Effect.gen(function* () {
602 const fs = yield* FileSystem.FileSystem;
603 const path = yield* Path.Path;
604 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
605 const attachmentId = "thread-1-attachment";
606 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
607 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
608 yield* fs.writeFile(imagePath, Buffer.from("hello"));
609​
610 const generated = yield* textGeneration
611 .generateBranchName({
612 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
613 cwd: process.cwd(),
614 message: "Fix layout bug from screenshot.",
615 attachments: [
616 {
617 type: "image",
618 id: attachmentId,
619 name: "bug.png",
620 mimeType: "image/png",
621 sizeBytes: 5,
622 },
623 ],
624 })
625 .pipe(
626 Effect.tap(() =>
627 fs.stat(imagePath).pipe(
628 Effect.map((fileInfo) => {
629 expect(fileInfo.type).toBe("File");
630 }),
631 ),
632 ),
633 Effect.ensuring(fs.remove(imagePath).pipe(Effect.ignore)),
634 );
635​
636 expect(generated.branch).toBe("fix/ui-regression");
637 }),
638 ),
639 );
640​
641 it.effect("ignores missing attachment ids for codex image inputs", () =>
642 withFakeCodexEnv(
643 {
644 output: JSON.stringify({
645 branch: "fix/ui-regression",
646 }),
647 requireImage: true,
648 },
649 (textGeneration) =>
650 Effect.gen(function* () {
651 const fs = yield* FileSystem.FileSystem;
652 const path = yield* Path.Path;
653 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
654 const missingAttachmentId = "thread-missing-attachment";
655 const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
656 yield* fs.remove(missingPath).pipe(Effect.ignore);
657​
658 const result = yield* textGeneration
659 .generateBranchName({
660 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
661 cwd: process.cwd(),
662 message: "Fix layout bug from screenshot.",
663 attachments: [
664 {
665 type: "image",
666 id: missingAttachmentId,
667 name: "outside.png",
668 mimeType: "image/png",
669 sizeBytes: 5,
670 },
671 ],
672 })
673 .pipe(Effect.result);
674​
675 expect(Result.isFailure(result)).toBe(true);
676 if (Result.isFailure(result)) {
677 expect(result.failure).toBeInstanceOf(TextGenerationError);
678 expect(result.failure.message).toContain("missing --image input");
679 }
680 }),
681 ),
682 );
683​
684 it.effect(
685 "fails with typed TextGenerationError when codex returns wrong branch payload shape",
686 () =>
687 withFakeCodexEnv(
688 {
689 output: JSON.stringify({
690 title: "This is not a branch payload",
691 }),
692 },
693 (textGeneration) =>
694 Effect.gen(function* () {
695 const result = yield* textGeneration
696 .generateBranchName({
697 cwd: process.cwd(),
698 message: "Fix websocket reconnect flake",
699 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
700 })
701 .pipe(Effect.result);
702​
703 expect(Result.isFailure(result)).toBe(true);
704 if (Result.isFailure(result)) {
705 expect(result.failure).toBeInstanceOf(TextGenerationError);
706 expect(result.failure.message).toContain("Codex returned invalid structured output");
707 }
708 }),
709 ),
710 );
711​
712 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
713 withFakeCodexEnv(
714 {
715 output: JSON.stringify({ subject: "ignored", body: "" }),
716 exitCode: 1,
717 stderr: "codex execution failed",
718 },
719 (textGeneration) =>
720 Effect.gen(function* () {
721 const result = yield* textGeneration
722 .generateCommitMessage({
723 cwd: process.cwd(),
724 branch: "feature/codex-error",
725 stagedSummary: "M README.md",
726 stagedPatch: "diff --git a/README.md b/README.md",
727 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
728 })
729 .pipe(Effect.result);
730​
731 expect(Result.isFailure(result)).toBe(true);
732 if (Result.isFailure(result)) {
733 expect(result.failure).toBeInstanceOf(TextGenerationError);
734 expect(result.failure.message).toContain(
735 "Codex CLI command failed: codex execution failed",
736 );
737 }
738 }),
739 ),
740 );
741});