Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Path from "effect/Path";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import { createModelSelection } from "@t3tools/shared/model";
10import { expect } from "vite-plus/test";
11
12import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
13
14import * as ServerConfig from "../config.ts";
15import * as TextGeneration from "./TextGeneration.ts";
16import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
17const decodeCodexSettings = Schema.decodeSync(CodexSettings);
18
19const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
20 ProviderInstanceId.make("codex"),
21 "gpt-5.4-mini",
22);
23
24const CodexTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
25 prefix: "t3code-codex-text-generation-test-",
26}).pipe(Layer.provideMerge(NodeServices.layer));
27
28function makeFakeCodexBinary(
29 dir: string,
30 input: {
31 output: string;
32 exitCode?: number;
33 stderr?: string;
34 requireImage?: boolean;
35 requireServiceTier?: string;
36 requireReasoningEffort?: string;
37 forbidReasoningEffort?: boolean;
38 requireArg?: string;
39 forbidArg?: string;
40 stdinMustContain?: string;
41 stdinMustNotContain?: string;
42 },
43) {
44 return Effect.gen(function* () {
45 const fs = yield* FileSystem.FileSystem;
46 const path = yield* Path.Path;
47 const binDir = path.join(dir, "bin");
48 const codexPath = path.join(binDir, "codex");
49 yield* fs.makeDirectory(binDir, { recursive: true });
50
51 yield* fs.writeFileString(
52 codexPath,
53 [
54 "#!/bin/sh",
55 'original_args="$*"',
56 'output_path=""',
57 'seen_image="0"',
58 'seen_service_tier=""',
59 'seen_reasoning_effort=""',
60 "while [ $# -gt 0 ]; do",
61 ' if [ "$1" = "--image" ]; then',
62 " shift",
63 ' if [ -n "$1" ]; then',
64 ' seen_image="1"',
65 " fi",
66 " shift",
67 " continue",
68 " fi",
69 ' if [ "$1" = "--config" ]; then',
70 " shift",
71 ' case "$1" in',
72 " service_tier=*)",
73 ' seen_service_tier="$1"',
74 " ;;",
75 " esac",
76 ' case "$1" in',
77 " model_reasoning_effort=*)",
78 ' seen_reasoning_effort="$1"',
79 " ;;",
80 " esac",
81 " shift",
82 " continue",
83 " fi",
84 ' if [ "$1" = "--output-last-message" ]; then',
85 " shift",
86 ' output_path="$1"',
87 " shift",
88 " continue",
89 " fi",
90 " shift",
91 "done",
92 'stdin_content="$(cat)"',
93 ...(input.requireArg !== undefined
94 ? [
95 `case " $original_args " in *" ${input.requireArg} "*) ;; *)`,
96 ` printf "%s\\n" "missing arg: ${input.requireArg}" >&2`,
97 ` exit 8`,
98 "esac",
99 ]
100 : []),
101 ...(input.forbidArg !== undefined
102 ? [
103 `case " $original_args " in *" ${input.forbidArg} "*)`,
104 ` printf "%s\\n" "forbidden arg: ${input.forbidArg}" >&2`,
105 ` exit 9`,
106 "esac",
107 ]
108 : []),
109 ...(input.requireImage
110 ? [
111 'if [ "$seen_image" != "1" ]; then',
112 ' printf "%s\\n" "missing --image input" >&2',
113 ` exit 2`,
114 "fi",
115 ]
116 : []),
117 ...(input.requireServiceTier
118 ? [
119 `if [ "$seen_service_tier" != "service_tier=\\"${input.requireServiceTier}\\"" ]; then`,
120 ' printf "%s\\n" "unexpected service tier config: $seen_service_tier" >&2',
121 ` exit 5`,
122 "fi",
123 ]
124 : []),
125 ...(input.requireReasoningEffort !== undefined
126 ? [
127 `if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`,
128 ' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
129 ` exit 6`,
130 "fi",
131 ]
132 : []),
133 ...(input.forbidReasoningEffort
134 ? [
135 'if [ -n "$seen_reasoning_effort" ]; then',
136 ' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
137 ` exit 7`,
138 "fi",
139 ]
140 : []),
141 ...(input.stdinMustContain !== undefined
142 ? [
143 // @effect-diagnostics-next-line preferSchemaOverJson:off
144 `if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
145 ' printf "%s\\n" "stdin missing expected content" >&2',
146 ` exit 3`,
147 "fi",
148 ]
149 : []),
150 ...(input.stdinMustNotContain !== undefined
151 ? [
152 // @effect-diagnostics-next-line preferSchemaOverJson:off
153 `if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
154 ' printf "%s\\n" "stdin contained forbidden content" >&2',
155 ` exit 4`,
156 "fi",
157 ]
158 : []),
159 ...(input.stderr !== undefined
160 ? [
161 // @effect-diagnostics-next-line preferSchemaOverJson:off
162 `printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`,
163 ]
164 : []),
165 'if [ -n "$output_path" ]; then',
166 " cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
167 input.output,
168 "__T3CODE_FAKE_CODEX_OUTPUT__",
169 "fi",
170 `exit ${input.exitCode ?? 0}`,
171 "",
172 ].join("\n"),
173 );
174 yield* fs.chmod(codexPath, 0o755);
175 return codexPath;
176 });
177}
178
179function withFakeCodexEnv<A, E, R>(
180 input: {
181 output: string;
182 exitCode?: number;
183 stderr?: string;
184 requireImage?: boolean;
185 requireServiceTier?: string;
186 requireReasoningEffort?: string;
187 forbidReasoningEffort?: boolean;
188 requireArg?: string;
189 forbidArg?: string;
190 stdinMustContain?: string;
191 stdinMustNotContain?: string;
192 launchArgs?: string;
193 environment?: NodeJS.ProcessEnv;
194 },
195 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
196) {
197 return Effect.gen(function* () {
198 const fs = yield* FileSystem.FileSystem;
199 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
200 const codexPath = yield* makeFakeCodexBinary(tempDir, input);
201 const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs });
202 const textGeneration = yield* makeCodexTextGeneration(config, input.environment);
203 return yield* effectFn(textGeneration);
204 }).pipe(Effect.scoped);
205}
206
207it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
208 it.effect("generates and sanitizes commit messages without branch by default", () =>
209 withFakeCodexEnv(
210 {
211 output: JSON.stringify({
212 subject:
213 " Add important change to the system with too much detail and a trailing period.\nsecondary line",
214 body: "\n- added migration\n- updated tests\n",
215 }),
216 stdinMustNotContain: "branch must be a short semantic git branch fragment",
217 },
218 (textGeneration) =>
219 Effect.gen(function* () {
220 const generated = yield* textGeneration.generateCommitMessage({
221 cwd: process.cwd(),
222 branch: "feature/codex-effect",
223 stagedSummary: "M README.md",
224 stagedPatch: "diff --git a/README.md b/README.md",
225 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
226 });
227
228 expect(generated.subject.length).toBeLessThanOrEqual(72);
229 expect(generated.subject.endsWith(".")).toBe(false);
230 expect(generated.body).toBe("- added migration\n- updated tests");
231 expect(generated.branch).toBeUndefined();
232 }),
233 ),
234 );
235
236 it.effect(
237 "forwards codex service tier and non-default reasoning effort into codex exec config",
238 () =>
239 withFakeCodexEnv(
240 {
241 output: JSON.stringify({
242 subject: "Add important change",
243 body: "",
244 }),
245 requireServiceTier: "priority",
246 requireReasoningEffort: "xhigh",
247 stdinMustNotContain: "branch must be a short semantic git branch fragment",
248 },
249 (textGeneration) =>
250 textGeneration.generateCommitMessage({
251 cwd: process.cwd(),
252 branch: "feature/codex-effect",
253 stagedSummary: "M README.md",
254 stagedPatch: "diff --git a/README.md b/README.md",
255 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
256 { id: "reasoningEffort", value: "xhigh" },
257 { id: "serviceTier", value: "priority" },
258 ]),
259 }),
260 ),
261 );
262
263 it.effect("passes exec-safe launch args into codex exec", () =>
264 withFakeCodexEnv(
265 {
266 output: JSON.stringify({
267 subject: "Add important change",
268 body: "",
269 }),
270 launchArgs: "--strict-config --listen off",
271 requireArg: "--strict-config",
272 forbidArg: "--listen",
273 },
274 (textGeneration) =>
275 textGeneration.generateCommitMessage({
276 cwd: process.cwd(),
277 branch: "feature/codex-effect",
278 stagedSummary: "M README.md",
279 stagedPatch: "diff --git a/README.md b/README.md",
280 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
281 }),
282 ),
283 );
284
285 it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for codex exec over settings", () =>
286 withFakeCodexEnv(
287 {
288 output: JSON.stringify({
289 subject: "Add important change",
290 body: "",
291 }),
292 launchArgs: "--enable settings-feature",
293 environment: { T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --listen off " },
294 requireArg: "--strict-config",
295 forbidArg: "settings-feature",
296 },
297 (textGeneration) =>
298 textGeneration.generateCommitMessage({
299 cwd: process.cwd(),
300 branch: "feature/codex-effect",
301 stagedSummary: "M README.md",
302 stagedPatch: "diff --git a/README.md b/README.md",
303 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
304 }),
305 ),
306 );
307
308 it.effect("defaults git text generation codex effort to low", () =>
309 withFakeCodexEnv(
310 {
311 output: JSON.stringify({
312 subject: "Add important change",
313 body: "",
314 }),
315 requireReasoningEffort: "low",
316 },
317 (textGeneration) =>
318 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 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
324 }),
325 ),
326 );
327
328 it.effect("generates commit message with branch when includeBranch is true", () =>
329 withFakeCodexEnv(
330 {
331 output: JSON.stringify({
332 subject: "Add important change",
333 body: "",
334 branch: "fix/important-system-change",
335 }),
336 stdinMustContain: "branch must be a short semantic git branch fragment",
337 },
338 (textGeneration) =>
339 Effect.gen(function* () {
340 const generated = yield* textGeneration.generateCommitMessage({
341 cwd: process.cwd(),
342 branch: "feature/codex-effect",
343 stagedSummary: "M README.md",
344 stagedPatch: "diff --git a/README.md b/README.md",
345 includeBranch: true,
346 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
347 });
348
349 expect(generated.subject).toBe("Add important change");
350 expect(generated.branch).toBe("feature/fix/important-system-change");
351 }),
352 ),
353 );
354
355 it.effect("generates PR content and trims markdown body", () =>
356 withFakeCodexEnv(
357 {
358 output: JSON.stringify({
359 title: " Improve orchestration flow\nwith ignored suffix",
360 body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
361 }),
362 },
363 (textGeneration) =>
364 Effect.gen(function* () {
365 const generated = yield* textGeneration.generatePrContent({
366 cwd: process.cwd(),
367 baseBranch: "main",
368 headBranch: "feature/codex-effect",
369 commitSummary: "feat: improve orchestration flow",
370 diffSummary: "2 files changed",
371 diffPatch: "diff --git a/a.ts b/a.ts",
372 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
373 });
374
375 expect(generated.title).toBe("Improve orchestration flow");
376 expect(generated.body.startsWith("## Summary")).toBe(true);
377 expect(generated.body.endsWith("\n\n")).toBe(false);
378 }),
379 ),
380 );
381
382 it.effect("generates branch names and normalizes branch fragments", () =>
383 withFakeCodexEnv(
384 {
385 output: JSON.stringify({
386 branch: " Feat/Session ",
387 }),
388 stdinMustNotContain: "Image attachments supplied to the model",
389 },
390 (textGeneration) =>
391 Effect.gen(function* () {
392 const generated = yield* textGeneration.generateBranchName({
393 cwd: process.cwd(),
394 message: "Please update session handling.",
395 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
396 });
397
398 expect(generated.branch).toBe("feat/session");
399 }),
400 ),
401 );
402
403 it.effect("generates thread titles and trims them for sidebar use", () =>
404 withFakeCodexEnv(
405 {
406 output: JSON.stringify({
407 title:
408 ' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
409 }),
410 },
411 (textGeneration) =>
412 Effect.gen(function* () {
413 const generated = yield* textGeneration.generateThreadTitle({
414 cwd: process.cwd(),
415 message: "Please investigate websocket reconnect regressions after a worktree restore.",
416 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
417 });
418
419 expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
420 }),
421 ),
422 );
423
424 it.effect("falls back when thread title normalization becomes whitespace-only", () =>
425 withFakeCodexEnv(
426 {
427 output: JSON.stringify({
428 title: ' """ """ ',
429 }),
430 },
431 (textGeneration) =>
432 Effect.gen(function* () {
433 const generated = yield* textGeneration.generateThreadTitle({
434 cwd: process.cwd(),
435 message: "Name this thread.",
436 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
437 });
438
439 expect(generated.title).toBe("New thread");
440 }),
441 ),
442 );
443
444 it.effect("trims whitespace exposed after quote removal in thread titles", () =>
445 withFakeCodexEnv(
446 {
447 output: JSON.stringify({
448 title: ` "' hello world '" `,
449 }),
450 },
451 (textGeneration) =>
452 Effect.gen(function* () {
453 const generated = yield* textGeneration.generateThreadTitle({
454 cwd: process.cwd(),
455 message: "Name this thread.",
456 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
457 });
458
459 expect(generated.title).toBe("hello world");
460 }),
461 ),
462 );
463
464 it.effect("omits attachment metadata section when no attachments are provided", () =>
465 withFakeCodexEnv(
466 {
467 output: JSON.stringify({
468 branch: "fix/session-timeout",
469 }),
470 stdinMustNotContain: "Attachment metadata:",
471 },
472 (textGeneration) =>
473 Effect.gen(function* () {
474 const generated = yield* textGeneration.generateBranchName({
475 cwd: process.cwd(),
476 message: "Fix timeout behavior.",
477 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
478 });
479
480 expect(generated.branch).toBe("fix/session-timeout");
481 }),
482 ),
483 );
484
485 it.effect("passes image attachments through as codex image inputs", () =>
486 withFakeCodexEnv(
487 {
488 output: JSON.stringify({
489 branch: "fix/ui-regression",
490 }),
491 requireImage: true,
492 stdinMustContain: "Attachment metadata:",
493 },
494 (textGeneration) =>
495 Effect.gen(function* () {
496 const fs = yield* FileSystem.FileSystem;
497 const path = yield* Path.Path;
498 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
499 const attachmentId = "thread-branch-image-attachment";
500 const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
501 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
502 yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
503
504 const generated = yield* textGeneration.generateBranchName({
505 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
506 cwd: process.cwd(),
507 message: "Fix layout bug from screenshot.",
508 attachments: [
509 {
510 type: "image",
511 id: attachmentId,
512 name: "bug.png",
513 mimeType: "image/png",
514 sizeBytes: 5,
515 },
516 ],
517 });
518
519 expect(generated.branch).toBe("fix/ui-regression");
520 }),
521 ),
522 );
523
524 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
525 withFakeCodexEnv(
526 {
527 output: JSON.stringify({
528 branch: "fix/ui-regression",
529 }),
530 requireImage: true,
531 },
532 (textGeneration) =>
533 Effect.gen(function* () {
534 const fs = yield* FileSystem.FileSystem;
535 const path = yield* Path.Path;
536 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
537 const attachmentId = "thread-1-attachment";
538 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
539 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
540 yield* fs.writeFile(imagePath, Buffer.from("hello"));
541
542 const generated = yield* textGeneration
543 .generateBranchName({
544 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
545 cwd: process.cwd(),
546 message: "Fix layout bug from screenshot.",
547 attachments: [
548 {
549 type: "image",
550 id: attachmentId,
551 name: "bug.png",
552 mimeType: "image/png",
553 sizeBytes: 5,
554 },
555 ],
556 })
557 .pipe(
558 Effect.tap(() =>
559 fs.stat(imagePath).pipe(
560 Effect.map((fileInfo) => {
561 expect(fileInfo.type).toBe("File");
562 }),
563 ),
564 ),
565 Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
566 );
567
568 expect(generated.branch).toBe("fix/ui-regression");
569 }),
570 ),
571 );
572
573 it.effect("ignores missing attachment ids for codex image inputs", () =>
574 withFakeCodexEnv(
575 {
576 output: JSON.stringify({
577 branch: "fix/ui-regression",
578 }),
579 requireImage: true,
580 },
581 (textGeneration) =>
582 Effect.gen(function* () {
583 const fs = yield* FileSystem.FileSystem;
584 const path = yield* Path.Path;
585 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
586 const missingAttachmentId = "thread-missing-attachment";
587 const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
588 yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
589
590 const result = yield* textGeneration
591 .generateBranchName({
592 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
593 cwd: process.cwd(),
594 message: "Fix layout bug from screenshot.",
595 attachments: [
596 {
597 type: "image",
598 id: missingAttachmentId,
599 name: "outside.png",
600 mimeType: "image/png",
601 sizeBytes: 5,
602 },
603 ],
604 })
605 .pipe(Effect.result);
606
607 expect(Result.isFailure(result)).toBe(true);
608 if (Result.isFailure(result)) {
609 expect(result.failure).toBeInstanceOf(TextGenerationError);
610 expect(result.failure.message).toContain("missing --image input");
611 }
612 }),
613 ),
614 );
615
616 it.effect(
617 "fails with typed TextGenerationError when codex returns wrong branch payload shape",
618 () =>
619 withFakeCodexEnv(
620 {
621 output: JSON.stringify({
622 title: "This is not a branch payload",
623 }),
624 },
625 (textGeneration) =>
626 Effect.gen(function* () {
627 const result = yield* textGeneration
628 .generateBranchName({
629 cwd: process.cwd(),
630 message: "Fix websocket reconnect flake",
631 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
632 })
633 .pipe(Effect.result);
634
635 expect(Result.isFailure(result)).toBe(true);
636 if (Result.isFailure(result)) {
637 expect(result.failure).toBeInstanceOf(TextGenerationError);
638 expect(result.failure.message).toContain("Codex returned invalid structured output");
639 }
640 }),
641 ),
642 );
643
644 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
645 withFakeCodexEnv(
646 {
647 output: JSON.stringify({ subject: "ignored", body: "" }),
648 exitCode: 1,
649 stderr: "codex execution failed",
650 },
651 (textGeneration) =>
652 Effect.gen(function* () {
653 const result = yield* textGeneration
654 .generateCommitMessage({
655 cwd: process.cwd(),
656 branch: "feature/codex-error",
657 stagedSummary: "M README.md",
658 stagedPatch: "diff --git a/README.md b/README.md",
659 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
660 })
661 .pipe(Effect.result);
662
663 expect(Result.isFailure(result)).toBe(true);
664 if (Result.isFailure(result)) {
665 expect(result.failure).toBeInstanceOf(TextGenerationError);
666 expect(result.failure.message).toContain(
667 "Codex CLI command failed: codex execution failed",
668 );
669 }
670 }),
671 ),
672 );
673});