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

CodexTextGeneration.test.ts

679 lines23.8 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 models?: ReadonlyArray<string>;
140 },
141 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
142) {
143 return Effect.gen(function* () {
144 const fs = yield* FileSystem.FileSystem;
145 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
146 const codexPath = yield* makeFakeCodexBinary(tempDir, input);
147 const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs });
148 const textGeneration = yield* makeCodexTextGeneration(
149 config,
150 input.environment === undefined ? undefined : { ...process.env, ...input.environment },
151 Effect.succeed(
152 (input.models ?? []).map((slug) => ({
153 slug,
154 name: slug,
155 isCustom: false,
156 capabilities: null,
157 })),
158 ),
159 );
160 return yield* effectFn(textGeneration);
161 }).pipe(Effect.scoped);
163​
164it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
165 for (const selectedModel of ["gpt-5.6-luna", "openai.gpt-5.6-luna"]) {
166 it.effect(`dispatches the qualified live model for ${selectedModel}`, () =>
167 withFakeCodexEnv(
168 {
169 output: JSON.stringify({ title: "Bedrock title" }),
170 models: ["openai.gpt-5.6-luna"],
171 requireArg: "--model openai.gpt-5.6-luna",
172 forbidArg: "--model gpt-5.6-luna",
173 },
174 (textGeneration) =>
175 Effect.gen(function* () {
176 const result = yield* textGeneration.generateThreadTitle({
177 cwd: process.cwd(),
178 message: "Describe this change",
179 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), selectedModel),
180 });
181 expect(result.title).toBe("Bedrock title");
182 }),
183 ),
184 );
185 }
186 it.effect("generates and sanitizes commit messages without branch by default", () =>
187 withFakeCodexEnv(
188 {
189 output: JSON.stringify({
190 subject:
191 " Add important change to the system with too much detail and a trailing period.\nsecondary line",
192 body: "\n- added migration\n- updated tests\n",
193 }),
194 stdinMustNotContain: "branch must be a short semantic git branch fragment",
195 },
196 (textGeneration) =>
197 Effect.gen(function* () {
198 const generated = yield* textGeneration.generateCommitMessage({
199 cwd: process.cwd(),
200 branch: "feature/codex-effect",
201 stagedSummary: "M README.md",
202 stagedPatch: "diff --git a/README.md b/README.md",
203 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
204 });
205​
206 expect(generated.subject.length).toBeLessThanOrEqual(72);
207 expect(generated.subject.endsWith(".")).toBe(false);
208 expect(generated.body).toBe("- added migration\n- updated tests");
209 expect(generated.branch).toBeUndefined();
210 }),
211 ),
212 );
213​
214 it.effect(
215 "forwards codex service tier and non-default reasoning effort into codex exec config",
216 () =>
217 withFakeCodexEnv(
218 {
219 output: JSON.stringify({
220 subject: "Add important change",
221 body: "",
222 }),
223 requireServiceTier: "priority",
224 requireReasoningEffort: "xhigh",
225 stdinMustNotContain: "branch must be a short semantic git branch fragment",
226 },
227 (textGeneration) =>
228 textGeneration.generateCommitMessage({
229 cwd: process.cwd(),
230 branch: "feature/codex-effect",
231 stagedSummary: "M README.md",
232 stagedPatch: "diff --git a/README.md b/README.md",
233 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
234 { id: "reasoningEffort", value: "xhigh" },
235 { id: "serviceTier", value: "priority" },
236 ]),
237 }),
238 ),
239 );
240​
241 it.effect("passes exec-safe launch args into codex exec", () =>
242 withFakeCodexEnv(
243 {
244 output: JSON.stringify({
245 subject: "Add important change",
246 body: "",
247 }),
248 launchArgs: "--strict-config --listen off",
249 requireArg: "--strict-config",
250 forbidArg: "--listen",
251 },
252 (textGeneration) =>
253 textGeneration.generateCommitMessage({
254 cwd: process.cwd(),
255 branch: "feature/codex-effect",
256 stagedSummary: "M README.md",
257 stagedPatch: "diff --git a/README.md b/README.md",
258 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
259 }),
260 ),
261 );
262​
263 it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for codex exec over settings", () =>
264 withFakeCodexEnv(
265 {
266 output: JSON.stringify({
267 subject: "Add important change",
268 body: "",
269 }),
270 launchArgs: "--enable settings-feature",
271 environment: { T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --listen off " },
272 requireArg: "--strict-config",
273 forbidArg: "settings-feature",
274 },
275 (textGeneration) =>
276 textGeneration.generateCommitMessage({
277 cwd: process.cwd(),
278 branch: "feature/codex-effect",
279 stagedSummary: "M README.md",
280 stagedPatch: "diff --git a/README.md b/README.md",
281 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
282 }),
283 ),
284 );
285​
286 it.effect("defaults git text generation codex effort to low", () =>
287 withFakeCodexEnv(
288 {
289 output: JSON.stringify({
290 subject: "Add important change",
291 body: "",
292 }),
293 requireReasoningEffort: "low",
294 },
295 (textGeneration) =>
296 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 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
302 }),
303 ),
304 );
305​
306 it.effect("generates commit message with branch when includeBranch is true", () =>
307 withFakeCodexEnv(
308 {
309 output: JSON.stringify({
310 subject: "Add important change",
311 body: "",
312 branch: "fix/important-system-change",
313 }),
314 stdinMustContain: "branch must be a short semantic git branch fragment",
315 },
316 (textGeneration) =>
317 Effect.gen(function* () {
318 const generated = yield* textGeneration.generateCommitMessage({
319 cwd: process.cwd(),
320 branch: "feature/codex-effect",
321 stagedSummary: "M README.md",
322 stagedPatch: "diff --git a/README.md b/README.md",
323 includeBranch: true,
324 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
325 });
326​
327 expect(generated.subject).toBe("Add important change");
328 expect(generated.branch).toBe("feature/fix/important-system-change");
329 }),
330 ),
331 );
332​
333 it.effect("generates PR content and trims markdown body", () =>
334 withFakeCodexEnv(
335 {
336 output: JSON.stringify({
337 title: " Improve orchestration flow\nwith ignored suffix",
338 body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
339 }),
340 },
341 (textGeneration) =>
342 Effect.gen(function* () {
343 const generated = yield* textGeneration.generatePrContent({
344 cwd: process.cwd(),
345 baseBranch: "main",
346 headBranch: "feature/codex-effect",
347 commitSummary: "feat: improve orchestration flow",
348 diffSummary: "2 files changed",
349 diffPatch: "diff --git a/a.ts b/a.ts",
350 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
351 });
352​
353 expect(generated.title).toBe("Improve orchestration flow");
354 expect(generated.body.startsWith("## Summary")).toBe(true);
355 expect(generated.body.endsWith("\n\n")).toBe(false);
356 }),
357 ),
358 );
359​
360 it.effect("generates branch names and normalizes branch fragments", () =>
361 withFakeCodexEnv(
362 {
363 output: JSON.stringify({
364 branch: " Feat/Session ",
365 }),
366 stdinMustNotContain: "Image attachments supplied to the model",
367 },
368 (textGeneration) =>
369 Effect.gen(function* () {
370 const generated = yield* textGeneration.generateBranchName({
371 cwd: process.cwd(),
372 message: "Please update session handling.",
373 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
374 });
375​
376 expect(generated.branch).toBe("feat/session");
377 }),
378 ),
379 );
380​
381 it.effect("generates branch names even when the ambient scope is already closed", () =>
382 withFakeCodexEnv(
383 {
384 output: JSON.stringify({
385 branch: "feat/background-generation",
386 }),
387 },
388 (textGeneration) =>
389 Effect.gen(function* () {
390 // Background fibers (e.g. the worktree branch rename fork) can run
391 // after their launching request's scope has closed; temp files must
392 // not be tied to that ambient scope or they are reaped on creation.
393 const closedScope = yield* Scope.make();
394 yield* Scope.close(closedScope, Exit.void);
395​
396 const generated = yield* textGeneration
397 .generateBranchName({
398 cwd: process.cwd(),
399 message: "Please update session handling.",
400 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
401 })
402 .pipe(Effect.provideService(Scope.Scope, closedScope));
403​
404 expect(generated.branch).toBe("feat/background-generation");
405 }),
406 ),
407 );
408​
409 it.effect("generates thread titles and trims them for sidebar use", () =>
410 withFakeCodexEnv(
411 {
412 output: JSON.stringify({
413 title:
414 ' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
415 }),
416 },
417 (textGeneration) =>
418 Effect.gen(function* () {
419 const generated = yield* textGeneration.generateThreadTitle({
420 cwd: process.cwd(),
421 message: "Please investigate websocket reconnect regressions after a worktree restore.",
422 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
423 });
424​
425 expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
426 }),
427 ),
428 );
429​
430 it.effect("falls back when thread title normalization becomes whitespace-only", () =>
431 withFakeCodexEnv(
432 {
433 output: JSON.stringify({
434 title: ' """ """ ',
435 }),
436 },
437 (textGeneration) =>
438 Effect.gen(function* () {
439 const generated = yield* textGeneration.generateThreadTitle({
440 cwd: process.cwd(),
441 message: "Name this thread.",
442 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
443 });
444​
445 expect(generated.title).toBe("New thread");
446 }),
447 ),
448 );
449​
450 it.effect("trims whitespace exposed after quote removal in thread titles", () =>
451 withFakeCodexEnv(
452 {
453 output: JSON.stringify({
454 title: ` "' hello world '" `,
455 }),
456 },
457 (textGeneration) =>
458 Effect.gen(function* () {
459 const generated = yield* textGeneration.generateThreadTitle({
460 cwd: process.cwd(),
461 message: "Name this thread.",
462 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
463 });
464​
465 expect(generated.title).toBe("hello world");
466 }),
467 ),
468 );
469​
470 it.effect("omits attachment metadata section when no attachments are provided", () =>
471 withFakeCodexEnv(
472 {
473 output: JSON.stringify({
474 branch: "fix/session-timeout",
475 }),
476 stdinMustNotContain: "Attachment metadata:",
477 },
478 (textGeneration) =>
479 Effect.gen(function* () {
480 const generated = yield* textGeneration.generateBranchName({
481 cwd: process.cwd(),
482 message: "Fix timeout behavior.",
483 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
484 });
485​
486 expect(generated.branch).toBe("fix/session-timeout");
487 }),
488 ),
489 );
490​
491 it.effect("passes image attachments through as codex image inputs", () =>
492 withFakeCodexEnv(
493 {
494 output: JSON.stringify({
495 branch: "fix/ui-regression",
496 }),
497 requireImage: true,
498 stdinMustContain: "Attachment metadata:",
499 },
500 (textGeneration) =>
501 Effect.gen(function* () {
502 const fs = yield* FileSystem.FileSystem;
503 const path = yield* Path.Path;
504 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
505 const attachmentId = "thread-branch-image-attachment";
506 const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
507 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
508 yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
509​
510 const generated = yield* textGeneration.generateBranchName({
511 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
512 cwd: process.cwd(),
513 message: "Fix layout bug from screenshot.",
514 attachments: [
515 {
516 type: "image",
517 id: attachmentId,
518 name: "bug.png",
519 mimeType: "image/png",
520 sizeBytes: 5,
521 },
522 ],
523 });
524​
525 expect(generated.branch).toBe("fix/ui-regression");
526 }),
527 ),
528 );
529​
530 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
531 withFakeCodexEnv(
532 {
533 output: JSON.stringify({
534 branch: "fix/ui-regression",
535 }),
536 requireImage: true,
537 },
538 (textGeneration) =>
539 Effect.gen(function* () {
540 const fs = yield* FileSystem.FileSystem;
541 const path = yield* Path.Path;
542 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
543 const attachmentId = "thread-1-attachment";
544 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
545 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
546 yield* fs.writeFile(imagePath, Buffer.from("hello"));
547​
548 const generated = yield* textGeneration
549 .generateBranchName({
550 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
551 cwd: process.cwd(),
552 message: "Fix layout bug from screenshot.",
553 attachments: [
554 {
555 type: "image",
556 id: attachmentId,
557 name: "bug.png",
558 mimeType: "image/png",
559 sizeBytes: 5,
560 },
561 ],
562 })
563 .pipe(
564 Effect.tap(() =>
565 fs.stat(imagePath).pipe(
566 Effect.map((fileInfo) => {
567 expect(fileInfo.type).toBe("File");
568 }),
569 ),
570 ),
571 Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
572 );
573​
574 expect(generated.branch).toBe("fix/ui-regression");
575 }),
576 ),
577 );
578​
579 it.effect("ignores missing attachment ids for codex image inputs", () =>
580 withFakeCodexEnv(
581 {
582 output: JSON.stringify({
583 branch: "fix/ui-regression",
584 }),
585 requireImage: true,
586 },
587 (textGeneration) =>
588 Effect.gen(function* () {
589 const fs = yield* FileSystem.FileSystem;
590 const path = yield* Path.Path;
591 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
592 const missingAttachmentId = "thread-missing-attachment";
593 const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
594 yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
595​
596 const result = yield* textGeneration
597 .generateBranchName({
598 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
599 cwd: process.cwd(),
600 message: "Fix layout bug from screenshot.",
601 attachments: [
602 {
603 type: "image",
604 id: missingAttachmentId,
605 name: "outside.png",
606 mimeType: "image/png",
607 sizeBytes: 5,
608 },
609 ],
610 })
611 .pipe(Effect.result);
612​
613 expect(Result.isFailure(result)).toBe(true);
614 if (Result.isFailure(result)) {
615 expect(result.failure).toBeInstanceOf(TextGenerationError);
616 expect(result.failure.message).toContain("missing --image input");
617 }
618 }),
619 ),
620 );
621​
622 it.effect(
623 "fails with typed TextGenerationError when codex returns wrong branch payload shape",
624 () =>
625 withFakeCodexEnv(
626 {
627 output: JSON.stringify({
628 title: "This is not a branch payload",
629 }),
630 },
631 (textGeneration) =>
632 Effect.gen(function* () {
633 const result = yield* textGeneration
634 .generateBranchName({
635 cwd: process.cwd(),
636 message: "Fix websocket reconnect flake",
637 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
638 })
639 .pipe(Effect.result);
640​
641 expect(Result.isFailure(result)).toBe(true);
642 if (Result.isFailure(result)) {
643 expect(result.failure).toBeInstanceOf(TextGenerationError);
644 expect(result.failure.message).toContain("Codex returned invalid structured output");
645 }
646 }),
647 ),
648 );
649​
650 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
651 withFakeCodexEnv(
652 {
653 output: JSON.stringify({ subject: "ignored", body: "" }),
654 exitCode: 1,
655 stderr: "codex execution failed",
656 },
657 (textGeneration) =>
658 Effect.gen(function* () {
659 const result = yield* textGeneration
660 .generateCommitMessage({
661 cwd: process.cwd(),
662 branch: "feature/codex-error",
663 stagedSummary: "M README.md",
664 stagedPatch: "diff --git a/README.md b/README.md",
665 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
666 })
667 .pipe(Effect.result);
668​
669 expect(Result.isFailure(result)).toBe(true);
670 if (Result.isFailure(result)) {
671 expect(result.failure).toBeInstanceOf(TextGenerationError);
672 expect(result.failure.message).toContain(
673 "Codex CLI command failed: codex execution failed",
674 );
675 }
676 }),
677 ),
678 );
679});