Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it } from "@effect/vitest";
3import { Effect, FileSystem, Layer, Path } from "effect";
4import { expect } from "vitest";
5
6import { ServerConfig } from "../../config.ts";
7import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
8import { TextGenerationError } from "../Errors.ts";
9import { TextGeneration } from "../Services/TextGeneration.ts";
10
11const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
12 Layer.provideMerge(
13 ServerConfig.layerTest(process.cwd(), {
14 prefix: "t3code-codex-text-generation-test-",
15 }),
16 ),
17 Layer.provideMerge(NodeServices.layer),
18);
19
20function makeFakeCodexBinary(dir: string) {
21 return Effect.gen(function* () {
22 const fs = yield* FileSystem.FileSystem;
23 const path = yield* Path.Path;
24 const binDir = path.join(dir, "bin");
25 const codexPath = path.join(binDir, "codex");
26 yield* fs.makeDirectory(binDir, { recursive: true });
27
28 yield* fs.writeFileString(
29 codexPath,
30 [
31 "#!/bin/sh",
32 'output_path=""',
33 "while [ $# -gt 0 ]; do",
34 ' if [ "$1" = "--image" ]; then',
35 " shift",
36 ' if [ -n "$1" ]; then',
37 ' seen_image="1"',
38 " fi",
39 " continue",
40 " fi",
41 ' if [ "$1" = "--output-last-message" ]; then',
42 " shift",
43 ' output_path="$1"',
44 " fi",
45 " shift",
46 "done",
47 'stdin_content="$(cat)"',
48 'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
49 ' printf "%s\\n" "missing --image input" >&2',
50 " exit 2",
51 "fi",
52 'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
53 ' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
54 ' printf "%s\\n" "stdin missing expected content" >&2',
55 " exit 3",
56 " }",
57 "fi",
58 'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
59 ' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
60 ' printf "%s\\n" "stdin contained forbidden content" >&2',
61 " exit 4",
62 " fi",
63 "fi",
64 'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
65 ' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
66 "fi",
67 'if [ -n "$output_path" ]; then',
68 ' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
69 "fi",
70 'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
71 "",
72 ].join("\n"),
73 );
74 yield* fs.chmod(codexPath, 0o755);
75 return binDir;
76 });
77}
78
79function withFakeCodexEnv<A, E, R>(
80 input: {
81 output: string;
82 exitCode?: number;
83 stderr?: string;
84 requireImage?: boolean;
85 stdinMustContain?: string;
86 stdinMustNotContain?: string;
87 },
88 effect: Effect.Effect<A, E, R>,
89) {
90 return Effect.acquireUseRelease(
91 Effect.gen(function* () {
92 const fs = yield* FileSystem.FileSystem;
93 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
94 const binDir = yield* makeFakeCodexBinary(tempDir);
95 const previousPath = process.env.PATH;
96 const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
97 const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
98 const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
99 const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
100 const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
101 const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
102
103 yield* Effect.sync(() => {
104 process.env.PATH = `${binDir}:${previousPath ?? ""}`;
105 process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
106
107 if (input.exitCode !== undefined) {
108 process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
109 } else {
110 delete process.env.T3_FAKE_CODEX_EXIT_CODE;
111 }
112
113 if (input.stderr !== undefined) {
114 process.env.T3_FAKE_CODEX_STDERR = input.stderr;
115 } else {
116 delete process.env.T3_FAKE_CODEX_STDERR;
117 }
118
119 if (input.requireImage) {
120 process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
121 } else {
122 delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
123 }
124
125 if (input.stdinMustContain !== undefined) {
126 process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
127 } else {
128 delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
129 }
130
131 if (input.stdinMustNotContain !== undefined) {
132 process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
133 } else {
134 delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
135 }
136 });
137
138 return {
139 previousPath,
140 previousOutput,
141 previousExitCode,
142 previousStderr,
143 previousRequireImage,
144 previousStdinMustContain,
145 previousStdinMustNotContain,
146 };
147 }),
148 () => effect,
149 (previous) =>
150 Effect.sync(() => {
151 process.env.PATH = previous.previousPath;
152
153 if (previous.previousOutput === undefined) {
154 delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
155 } else {
156 process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
157 }
158
159 if (previous.previousExitCode === undefined) {
160 delete process.env.T3_FAKE_CODEX_EXIT_CODE;
161 } else {
162 process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
163 }
164
165 if (previous.previousStderr === undefined) {
166 delete process.env.T3_FAKE_CODEX_STDERR;
167 } else {
168 process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
169 }
170
171 if (previous.previousRequireImage === undefined) {
172 delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
173 } else {
174 process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
175 }
176
177 if (previous.previousStdinMustContain === undefined) {
178 delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
179 } else {
180 process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
181 }
182
183 if (previous.previousStdinMustNotContain === undefined) {
184 delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
185 } else {
186 process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
187 }
188 }),
189 );
190}
191
192it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
193 it.effect("generates and sanitizes commit messages without branch by default", () =>
194 withFakeCodexEnv(
195 {
196 output: JSON.stringify({
197 subject:
198 " Add important change to the system with too much detail and a trailing period.\nsecondary line",
199 body: "\n- added migration\n- updated tests\n",
200 }),
201 stdinMustNotContain: "branch must be a short semantic git branch fragment",
202 },
203 Effect.gen(function* () {
204 const textGeneration = yield* TextGeneration;
205
206 const generated = yield* textGeneration.generateCommitMessage({
207 cwd: process.cwd(),
208 branch: "feature/codex-effect",
209 stagedSummary: "M README.md",
210 stagedPatch: "diff --git a/README.md b/README.md",
211 });
212
213 expect(generated.subject.length).toBeLessThanOrEqual(72);
214 expect(generated.subject.endsWith(".")).toBe(false);
215 expect(generated.body).toBe("- added migration\n- updated tests");
216 expect(generated.branch).toBeUndefined();
217 }),
218 ),
219 );
220
221 it.effect("generates commit message with branch when includeBranch is true", () =>
222 withFakeCodexEnv(
223 {
224 output: JSON.stringify({
225 subject: "Add important change",
226 body: "",
227 branch: "fix/important-system-change",
228 }),
229 stdinMustContain: "branch must be a short semantic git branch fragment",
230 },
231 Effect.gen(function* () {
232 const textGeneration = yield* TextGeneration;
233
234 const generated = yield* textGeneration.generateCommitMessage({
235 cwd: process.cwd(),
236 branch: "feature/codex-effect",
237 stagedSummary: "M README.md",
238 stagedPatch: "diff --git a/README.md b/README.md",
239 includeBranch: true,
240 });
241
242 expect(generated.subject).toBe("Add important change");
243 expect(generated.branch).toBe("feature/fix/important-system-change");
244 }),
245 ),
246 );
247
248 it.effect("generates PR content and trims markdown body", () =>
249 withFakeCodexEnv(
250 {
251 output: JSON.stringify({
252 title: " Improve orchestration flow\nwith ignored suffix",
253 body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
254 }),
255 },
256 Effect.gen(function* () {
257 const textGeneration = yield* TextGeneration;
258
259 const generated = yield* textGeneration.generatePrContent({
260 cwd: process.cwd(),
261 baseBranch: "main",
262 headBranch: "feature/codex-effect",
263 commitSummary: "feat: improve orchestration flow",
264 diffSummary: "2 files changed",
265 diffPatch: "diff --git a/a.ts b/a.ts",
266 });
267
268 expect(generated.title).toBe("Improve orchestration flow");
269 expect(generated.body.startsWith("## Summary")).toBe(true);
270 expect(generated.body.endsWith("\n\n")).toBe(false);
271 }),
272 ),
273 );
274
275 it.effect("generates branch names and normalizes branch fragments", () =>
276 withFakeCodexEnv(
277 {
278 output: JSON.stringify({
279 branch: " Feat/Session ",
280 }),
281 stdinMustNotContain: "Image attachments supplied to the model",
282 },
283 Effect.gen(function* () {
284 const textGeneration = yield* TextGeneration;
285
286 const generated = yield* textGeneration.generateBranchName({
287 cwd: process.cwd(),
288 message: "Please update session handling.",
289 });
290
291 expect(generated.branch).toBe("feat/session");
292 }),
293 ),
294 );
295
296 it.effect("omits attachment metadata section when no attachments are provided", () =>
297 withFakeCodexEnv(
298 {
299 output: JSON.stringify({
300 branch: "fix/session-timeout",
301 }),
302 stdinMustNotContain: "Attachment metadata:",
303 },
304 Effect.gen(function* () {
305 const textGeneration = yield* TextGeneration;
306
307 const generated = yield* textGeneration.generateBranchName({
308 cwd: process.cwd(),
309 message: "Fix timeout behavior.",
310 });
311
312 expect(generated.branch).toBe("fix/session-timeout");
313 }),
314 ),
315 );
316
317 it.effect("passes image attachments through as codex image inputs", () =>
318 withFakeCodexEnv(
319 {
320 output: JSON.stringify({
321 branch: "fix/ui-regression",
322 }),
323 requireImage: true,
324 stdinMustContain: "Attachment metadata:",
325 },
326 Effect.gen(function* () {
327 const fs = yield* FileSystem.FileSystem;
328 const path = yield* Path.Path;
329 const { attachmentsDir } = yield* ServerConfig;
330 const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
331 const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
332 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
333 yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
334
335 const textGeneration = yield* TextGeneration;
336 const generated = yield* textGeneration
337 .generateBranchName({
338 cwd: process.cwd(),
339 message: "Fix layout bug from screenshot.",
340 attachments: [
341 {
342 type: "image",
343 id: attachmentId,
344 name: "bug.png",
345 mimeType: "image/png",
346 sizeBytes: 5,
347 },
348 ],
349 })
350 .pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
351
352 expect(generated.branch).toBe("fix/ui-regression");
353 }),
354 ),
355 );
356
357 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
358 withFakeCodexEnv(
359 {
360 output: JSON.stringify({
361 branch: "fix/ui-regression",
362 }),
363 requireImage: true,
364 },
365 Effect.gen(function* () {
366 const fs = yield* FileSystem.FileSystem;
367 const path = yield* Path.Path;
368 const { attachmentsDir } = yield* ServerConfig;
369 const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
370 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
371 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
372 yield* fs.writeFile(imagePath, Buffer.from("hello"));
373
374 const textGeneration = yield* TextGeneration;
375 const generated = yield* textGeneration
376 .generateBranchName({
377 cwd: process.cwd(),
378 message: "Fix layout bug from screenshot.",
379 attachments: [
380 {
381 type: "image",
382 id: attachmentId,
383 name: "bug.png",
384 mimeType: "image/png",
385 sizeBytes: 5,
386 },
387 ],
388 })
389 .pipe(
390 Effect.tap(() =>
391 fs.stat(imagePath).pipe(
392 Effect.map((fileInfo) => {
393 expect(fileInfo.type).toBe("File");
394 }),
395 ),
396 ),
397 Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
398 );
399
400 expect(generated.branch).toBe("fix/ui-regression");
401 }),
402 ),
403 );
404
405 it.effect("ignores missing attachment ids for codex image inputs", () =>
406 withFakeCodexEnv(
407 {
408 output: JSON.stringify({
409 branch: "fix/ui-regression",
410 }),
411 requireImage: true,
412 },
413 Effect.gen(function* () {
414 const fs = yield* FileSystem.FileSystem;
415 const path = yield* Path.Path;
416 const { attachmentsDir } = yield* ServerConfig;
417 const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
418 const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
419 yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
420
421 const textGeneration = yield* TextGeneration;
422 const result = yield* textGeneration
423 .generateBranchName({
424 cwd: process.cwd(),
425 message: "Fix layout bug from screenshot.",
426 attachments: [
427 {
428 type: "image",
429 id: missingAttachmentId,
430 name: "outside.png",
431 mimeType: "image/png",
432 sizeBytes: 5,
433 },
434 ],
435 })
436 .pipe(
437 Effect.match({
438 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
439 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
440 }),
441 );
442
443 expect(result._tag).toBe("Left");
444 if (result._tag === "Left") {
445 expect(result.left).toBeInstanceOf(TextGenerationError);
446 expect(result.left.message).toContain("missing --image input");
447 }
448 }),
449 ),
450 );
451
452 it.effect(
453 "fails with typed TextGenerationError when codex returns wrong branch payload shape",
454 () =>
455 withFakeCodexEnv(
456 {
457 output: JSON.stringify({
458 title: "This is not a branch payload",
459 }),
460 },
461 Effect.gen(function* () {
462 const textGeneration = yield* TextGeneration;
463
464 const result = yield* textGeneration
465 .generateBranchName({
466 cwd: process.cwd(),
467 message: "Fix websocket reconnect flake",
468 })
469 .pipe(
470 Effect.match({
471 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
472 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
473 }),
474 );
475
476 expect(result._tag).toBe("Left");
477 if (result._tag === "Left") {
478 expect(result.left).toBeInstanceOf(TextGenerationError);
479 expect(result.left.message).toContain("Codex returned invalid structured output");
480 }
481 }),
482 ),
483 );
484
485 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
486 withFakeCodexEnv(
487 {
488 output: JSON.stringify({ subject: "ignored", body: "" }),
489 exitCode: 1,
490 stderr: "codex execution failed",
491 },
492 Effect.gen(function* () {
493 const textGeneration = yield* TextGeneration;
494
495 const result = yield* textGeneration
496 .generateCommitMessage({
497 cwd: process.cwd(),
498 branch: "feature/codex-error",
499 stagedSummary: "M README.md",
500 stagedPatch: "diff --git a/README.md b/README.md",
501 })
502 .pipe(
503 Effect.match({
504 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
505 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
506 }),
507 );
508
509 expect(result._tag).toBe("Left");
510 if (result._tag === "Left") {
511 expect(result.left).toBeInstanceOf(TextGenerationError);
512 expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
513 }
514 }),
515 ),
516 );
517});