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