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

CodexTextGeneration.test.ts

646 lines22.7 KB

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