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