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

CodexTextGeneration.test.ts

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