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