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

CodexTextGeneration.test.ts

637 lines20.3 KB

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