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: { 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("Investigate websocket reconnect regressions aft...");
396 }),
397 ),
398 );
399
400 it.effect("falls back when thread title normalization becomes whitespace-only", () =>
401 withFakeCodexEnv(
402 {
403 output: JSON.stringify({
404 title: ' """ """ ',
405 }),
406 },
407 (textGeneration) =>
408 Effect.gen(function* () {
409 const generated = yield* textGeneration.generateThreadTitle({
410 cwd: process.cwd(),
411 message: "Name this thread.",
412 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
413 });
414
415 expect(generated.title).toBe("New thread");
416 }),
417 ),
418 );
419
420 it.effect("trims whitespace exposed after quote removal in thread titles", () =>
421 withFakeCodexEnv(
422 {
423 output: JSON.stringify({
424 title: ` "' hello world '" `,
425 }),
426 },
427 (textGeneration) =>
428 Effect.gen(function* () {
429 const generated = yield* textGeneration.generateThreadTitle({
430 cwd: process.cwd(),
431 message: "Name this thread.",
432 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
433 });
434
435 expect(generated.title).toBe("hello world");
436 }),
437 ),
438 );
439
440 it.effect("omits attachment metadata section when no attachments are provided", () =>
441 withFakeCodexEnv(
442 {
443 output: JSON.stringify({
444 branch: "fix/session-timeout",
445 }),
446 stdinMustNotContain: "Attachment metadata:",
447 },
448 (textGeneration) =>
449 Effect.gen(function* () {
450 const generated = yield* textGeneration.generateBranchName({
451 cwd: process.cwd(),
452 message: "Fix timeout behavior.",
453 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
454 });
455
456 expect(generated.branch).toBe("fix/session-timeout");
457 }),
458 ),
459 );
460
461 it.effect("passes image attachments through as codex image inputs", () =>
462 withFakeCodexEnv(
463 {
464 output: JSON.stringify({
465 branch: "fix/ui-regression",
466 }),
467 requireImage: true,
468 stdinMustContain: "Attachment metadata:",
469 },
470 (textGeneration) =>
471 Effect.gen(function* () {
472 const fs = yield* FileSystem.FileSystem;
473 const path = yield* Path.Path;
474 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
475 const attachmentId = "thread-branch-image-attachment";
476 const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
477 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
478 yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
479
480 const generated = yield* textGeneration.generateBranchName({
481 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
482 cwd: process.cwd(),
483 message: "Fix layout bug from screenshot.",
484 attachments: [
485 {
486 type: "image",
487 id: attachmentId,
488 name: "bug.png",
489 mimeType: "image/png",
490 sizeBytes: 5,
491 },
492 ],
493 });
494
495 expect(generated.branch).toBe("fix/ui-regression");
496 }),
497 ),
498 );
499
500 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
501 withFakeCodexEnv(
502 {
503 output: JSON.stringify({
504 branch: "fix/ui-regression",
505 }),
506 requireImage: true,
507 },
508 (textGeneration) =>
509 Effect.gen(function* () {
510 const fs = yield* FileSystem.FileSystem;
511 const path = yield* Path.Path;
512 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
513 const attachmentId = "thread-1-attachment";
514 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
515 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
516 yield* fs.writeFile(imagePath, Buffer.from("hello"));
517
518 const generated = yield* textGeneration
519 .generateBranchName({
520 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
521 cwd: process.cwd(),
522 message: "Fix layout bug from screenshot.",
523 attachments: [
524 {
525 type: "image",
526 id: attachmentId,
527 name: "bug.png",
528 mimeType: "image/png",
529 sizeBytes: 5,
530 },
531 ],
532 })
533 .pipe(
534 Effect.tap(() =>
535 fs.stat(imagePath).pipe(
536 Effect.map((fileInfo) => {
537 expect(fileInfo.type).toBe("File");
538 }),
539 ),
540 ),
541 Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
542 );
543
544 expect(generated.branch).toBe("fix/ui-regression");
545 }),
546 ),
547 );
548
549 it.effect("ignores missing attachment ids for codex image inputs", () =>
550 withFakeCodexEnv(
551 {
552 output: JSON.stringify({
553 branch: "fix/ui-regression",
554 }),
555 requireImage: true,
556 },
557 (textGeneration) =>
558 Effect.gen(function* () {
559 const fs = yield* FileSystem.FileSystem;
560 const path = yield* Path.Path;
561 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
562 const missingAttachmentId = "thread-missing-attachment";
563 const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
564 yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
565
566 const result = yield* textGeneration
567 .generateBranchName({
568 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
569 cwd: process.cwd(),
570 message: "Fix layout bug from screenshot.",
571 attachments: [
572 {
573 type: "image",
574 id: missingAttachmentId,
575 name: "outside.png",
576 mimeType: "image/png",
577 sizeBytes: 5,
578 },
579 ],
580 })
581 .pipe(Effect.result);
582
583 expect(Result.isFailure(result)).toBe(true);
584 if (Result.isFailure(result)) {
585 expect(result.failure).toBeInstanceOf(TextGenerationError);
586 expect(result.failure.message).toContain("missing --image input");
587 }
588 }),
589 ),
590 );
591
592 it.effect(
593 "fails with typed TextGenerationError when codex returns wrong branch payload shape",
594 () =>
595 withFakeCodexEnv(
596 {
597 output: JSON.stringify({
598 title: "This is not a branch payload",
599 }),
600 },
601 (textGeneration) =>
602 Effect.gen(function* () {
603 const result = yield* textGeneration
604 .generateBranchName({
605 cwd: process.cwd(),
606 message: "Fix websocket reconnect flake",
607 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
608 })
609 .pipe(Effect.result);
610
611 expect(Result.isFailure(result)).toBe(true);
612 if (Result.isFailure(result)) {
613 expect(result.failure).toBeInstanceOf(TextGenerationError);
614 expect(result.failure.message).toContain("Codex returned invalid structured output");
615 }
616 }),
617 ),
618 );
619
620 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
621 withFakeCodexEnv(
622 {
623 output: JSON.stringify({ subject: "ignored", body: "" }),
624 exitCode: 1,
625 stderr: "codex execution failed",
626 },
627 (textGeneration) =>
628 Effect.gen(function* () {
629 const result = yield* textGeneration
630 .generateCommitMessage({
631 cwd: process.cwd(),
632 branch: "feature/codex-error",
633 stagedSummary: "M README.md",
634 stagedPatch: "diff --git a/README.md b/README.md",
635 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
636 })
637 .pipe(Effect.result);
638
639 expect(Result.isFailure(result)).toBe(true);
640 if (Result.isFailure(result)) {
641 expect(result.failure).toBeInstanceOf(TextGenerationError);
642 expect(result.failure.message).toContain(
643 "Codex CLI command failed: codex execution failed",
644 );
645 }
646 }),
647 ),
648 );
649});