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("generates and sanitizes thread titles", () =>
297 withFakeCodexEnv(
298 {
299 output: JSON.stringify({
300 title: ' "Investigate sidebar thread naming regression"\nextra',
301 }),
302 },
303 Effect.gen(function* () {
304 const textGeneration = yield* TextGeneration;
305
306 const generated = yield* textGeneration.generateThreadTitle({
307 cwd: process.cwd(),
308 message: "Please investigate why thread names are hard to scan in the sidebar.",
309 });
310
311 expect(generated.title).toBe("Investigate sidebar thread naming regression");
312 }),
313 ),
314 );
315
316 it.effect("omits attachment metadata section when no attachments are provided", () =>
317 withFakeCodexEnv(
318 {
319 output: JSON.stringify({
320 branch: "fix/session-timeout",
321 }),
322 stdinMustNotContain: "Attachment metadata:",
323 },
324 Effect.gen(function* () {
325 const textGeneration = yield* TextGeneration;
326
327 const generated = yield* textGeneration.generateBranchName({
328 cwd: process.cwd(),
329 message: "Fix timeout behavior.",
330 });
331
332 expect(generated.branch).toBe("fix/session-timeout");
333 }),
334 ),
335 );
336
337 it.effect("passes image attachments through as codex image inputs", () =>
338 withFakeCodexEnv(
339 {
340 output: JSON.stringify({
341 branch: "fix/ui-regression",
342 }),
343 requireImage: true,
344 stdinMustContain: "Attachment metadata:",
345 },
346 Effect.gen(function* () {
347 const fs = yield* FileSystem.FileSystem;
348 const path = yield* Path.Path;
349 const { attachmentsDir } = yield* ServerConfig;
350 const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
351 const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
352 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
353 yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
354
355 const textGeneration = yield* TextGeneration;
356 const generated = yield* textGeneration
357 .generateBranchName({
358 cwd: process.cwd(),
359 message: "Fix layout bug from screenshot.",
360 attachments: [
361 {
362 type: "image",
363 id: attachmentId,
364 name: "bug.png",
365 mimeType: "image/png",
366 sizeBytes: 5,
367 },
368 ],
369 })
370 .pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
371
372 expect(generated.branch).toBe("fix/ui-regression");
373 }),
374 ),
375 );
376
377 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
378 withFakeCodexEnv(
379 {
380 output: JSON.stringify({
381 branch: "fix/ui-regression",
382 }),
383 requireImage: true,
384 },
385 Effect.gen(function* () {
386 const fs = yield* FileSystem.FileSystem;
387 const path = yield* Path.Path;
388 const { attachmentsDir } = yield* ServerConfig;
389 const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
390 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
391 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
392 yield* fs.writeFile(imagePath, Buffer.from("hello"));
393
394 const textGeneration = yield* TextGeneration;
395 const generated = yield* textGeneration
396 .generateBranchName({
397 cwd: process.cwd(),
398 message: "Fix layout bug from screenshot.",
399 attachments: [
400 {
401 type: "image",
402 id: attachmentId,
403 name: "bug.png",
404 mimeType: "image/png",
405 sizeBytes: 5,
406 },
407 ],
408 })
409 .pipe(
410 Effect.tap(() =>
411 fs.stat(imagePath).pipe(
412 Effect.map((fileInfo) => {
413 expect(fileInfo.type).toBe("File");
414 }),
415 ),
416 ),
417 Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
418 );
419
420 expect(generated.branch).toBe("fix/ui-regression");
421 }),
422 ),
423 );
424
425 it.effect("ignores missing attachment ids for codex image inputs", () =>
426 withFakeCodexEnv(
427 {
428 output: JSON.stringify({
429 branch: "fix/ui-regression",
430 }),
431 requireImage: true,
432 },
433 Effect.gen(function* () {
434 const fs = yield* FileSystem.FileSystem;
435 const path = yield* Path.Path;
436 const { attachmentsDir } = yield* ServerConfig;
437 const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
438 const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
439 yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
440
441 const textGeneration = yield* TextGeneration;
442 const result = yield* textGeneration
443 .generateBranchName({
444 cwd: process.cwd(),
445 message: "Fix layout bug from screenshot.",
446 attachments: [
447 {
448 type: "image",
449 id: missingAttachmentId,
450 name: "outside.png",
451 mimeType: "image/png",
452 sizeBytes: 5,
453 },
454 ],
455 })
456 .pipe(
457 Effect.match({
458 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
459 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
460 }),
461 );
462
463 expect(result._tag).toBe("Left");
464 if (result._tag === "Left") {
465 expect(result.left).toBeInstanceOf(TextGenerationError);
466 expect(result.left.message).toContain("missing --image input");
467 }
468 }),
469 ),
470 );
471
472 it.effect(
473 "fails with typed TextGenerationError when codex returns wrong branch payload shape",
474 () =>
475 withFakeCodexEnv(
476 {
477 output: JSON.stringify({
478 title: "This is not a branch payload",
479 }),
480 },
481 Effect.gen(function* () {
482 const textGeneration = yield* TextGeneration;
483
484 const result = yield* textGeneration
485 .generateBranchName({
486 cwd: process.cwd(),
487 message: "Fix websocket reconnect flake",
488 })
489 .pipe(
490 Effect.match({
491 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
492 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
493 }),
494 );
495
496 expect(result._tag).toBe("Left");
497 if (result._tag === "Left") {
498 expect(result.left).toBeInstanceOf(TextGenerationError);
499 expect(result.left.message).toContain("Codex returned invalid structured output");
500 }
501 }),
502 ),
503 );
504
505 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
506 withFakeCodexEnv(
507 {
508 output: JSON.stringify({ subject: "ignored", body: "" }),
509 exitCode: 1,
510 stderr: "codex execution failed",
511 },
512 Effect.gen(function* () {
513 const textGeneration = yield* TextGeneration;
514
515 const result = yield* textGeneration
516 .generateCommitMessage({
517 cwd: process.cwd(),
518 branch: "feature/codex-error",
519 stagedSummary: "M README.md",
520 stagedPatch: "diff --git a/README.md b/README.md",
521 })
522 .pipe(
523 Effect.match({
524 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
525 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
526 }),
527 );
528
529 expect(result._tag).toBe("Left");
530 if (result._tag === "Left") {
531 expect(result.left).toBeInstanceOf(TextGenerationError);
532 expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
533 }
534 }),
535 ),
536 );
537});