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