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