Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexTextGeneration.test.ts

513 lines17.4 KB

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 });
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 );
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 = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
367 const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
368 yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
369 yield* fs.writeFile(imagePath, Buffer.from("hello"));
370​
371 const textGeneration = yield* TextGeneration;
372 const generated = yield* textGeneration
373 .generateBranchName({
374 cwd: process.cwd(),
375 message: "Fix layout bug from screenshot.",
376 attachments: [
377 {
378 type: "image",
379 id: attachmentId,
380 name: "bug.png",
381 mimeType: "image/png",
382 sizeBytes: 5,
383 },
384 ],
385 })
386 .pipe(
387 Effect.tap(() =>
388 fs.stat(imagePath).pipe(
389 Effect.map((fileInfo) => {
390 expect(fileInfo.type).toBe("File");
391 }),
392 ),
393 ),
394 Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
395 );
396​
397 expect(generated.branch).toBe("fix/ui-regression");
398 }),
399 ),
400 );
401​
402 it.effect("ignores missing attachment ids for codex image inputs", () =>
403 withFakeCodexEnv(
404 {
405 output: JSON.stringify({
406 branch: "fix/ui-regression",
407 }),
408 requireImage: true,
409 },
410 Effect.gen(function* () {
411 const fs = yield* FileSystem.FileSystem;
412 const path = yield* Path.Path;
413 const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
414 const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
415 yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
416​
417 const textGeneration = yield* TextGeneration;
418 const result = yield* textGeneration
419 .generateBranchName({
420 cwd: process.cwd(),
421 message: "Fix layout bug from screenshot.",
422 attachments: [
423 {
424 type: "image",
425 id: missingAttachmentId,
426 name: "outside.png",
427 mimeType: "image/png",
428 sizeBytes: 5,
429 },
430 ],
431 })
432 .pipe(
433 Effect.match({
434 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
435 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
436 }),
437 );
438​
439 expect(result._tag).toBe("Left");
440 if (result._tag === "Left") {
441 expect(result.left).toBeInstanceOf(TextGenerationError);
442 expect(result.left.message).toContain("missing --image input");
443 }
444 }),
445 ),
446 );
447​
448 it.effect(
449 "fails with typed TextGenerationError when codex returns wrong branch payload shape",
450 () =>
451 withFakeCodexEnv(
452 {
453 output: JSON.stringify({
454 title: "This is not a branch payload",
455 }),
456 },
457 Effect.gen(function* () {
458 const textGeneration = yield* TextGeneration;
459​
460 const result = yield* textGeneration
461 .generateBranchName({
462 cwd: process.cwd(),
463 message: "Fix websocket reconnect flake",
464 })
465 .pipe(
466 Effect.match({
467 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
468 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
469 }),
470 );
471​
472 expect(result._tag).toBe("Left");
473 if (result._tag === "Left") {
474 expect(result.left).toBeInstanceOf(TextGenerationError);
475 expect(result.left.message).toContain("Codex returned invalid structured output");
476 }
477 }),
478 ),
479 );
480​
481 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
482 withFakeCodexEnv(
483 {
484 output: JSON.stringify({ subject: "ignored", body: "" }),
485 exitCode: 1,
486 stderr: "codex execution failed",
487 },
488 Effect.gen(function* () {
489 const textGeneration = yield* TextGeneration;
490​
491 const result = yield* textGeneration
492 .generateCommitMessage({
493 cwd: process.cwd(),
494 branch: "feature/codex-error",
495 stagedSummary: "M README.md",
496 stagedPatch: "diff --git a/README.md b/README.md",
497 })
498 .pipe(
499 Effect.match({
500 onFailure: (error) => ({ _tag: "Left" as const, left: error }),
501 onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
502 }),
503 );
504​
505 expect(result._tag).toBe("Left");
506 if (result._tag === "Left") {
507 expect(result.left).toBeInstanceOf(TextGenerationError);
508 expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
509 }
510 }),
511 ),
512 );
513});