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

CodexTextGeneration.test.ts

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