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