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: {
237 PATH: process.env.PATH,
238 T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --listen off ",
239 },
240 requireArg: "--strict-config",
241 forbidArg: "settings-feature",
242 },
243 (textGeneration) =>
244 textGeneration.generateCommitMessage({
245 cwd: process.cwd(),
246 branch: "feature/codex-effect",
247 stagedSummary: "M README.md",
248 stagedPatch: "diff --git a/README.md b/README.md",
249 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
250 }),
251 ),
252 );
253
254 it.effect("defaults git text generation codex effort to low", () =>
255 withFakeCodexEnv(
256 {
257 output: JSON.stringify({
258 subject: "Add important change",
259 body: "",
260 }),
261 requireReasoningEffort: "low",
262 },
263 (textGeneration) =>
264 textGeneration.generateCommitMessage({
265 cwd: process.cwd(),
266 branch: "feature/codex-effect",
267 stagedSummary: "M README.md",
268 stagedPatch: "diff --git a/README.md b/README.md",
269 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
270 }),
271 ),
272 );
273
274 it.effect("generates commit message with branch when includeBranch is true", () =>
275 withFakeCodexEnv(
276 {
277 output: JSON.stringify({
278 subject: "Add important change",
279 body: "",
280 branch: "fix/important-system-change",
281 }),
282 stdinMustContain: "branch must be a short semantic git branch fragment",
283 },
284 (textGeneration) =>
285 Effect.gen(function* () {
286 const generated = yield* textGeneration.generateCommitMessage({
287 cwd: process.cwd(),
288 branch: "feature/codex-effect",
289 stagedSummary: "M README.md",
290 stagedPatch: "diff --git a/README.md b/README.md",
291 includeBranch: true,
292 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
293 });
294
295 expect(generated.subject).toBe("Add important change");
296 expect(generated.branch).toBe("feature/fix/important-system-change");
297 }),
298 ),
299 );
300
301 it.effect("generates PR content and trims markdown body", () =>
302 withFakeCodexEnv(
303 {
304 output: JSON.stringify({
305 title: " Improve orchestration flow\nwith ignored suffix",
306 body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
307 }),
308 },
309 (textGeneration) =>
310 Effect.gen(function* () {
311 const generated = yield* textGeneration.generatePrContent({
312 cwd: process.cwd(),
313 baseBranch: "main",
314 headBranch: "feature/codex-effect",
315 commitSummary: "feat: improve orchestration flow",
316 diffSummary: "2 files changed",
317 diffPatch: "diff --git a/a.ts b/a.ts",
318 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
319 });
320
321 expect(generated.title).toBe("Improve orchestration flow");
322 expect(generated.body.startsWith("## Summary")).toBe(true);
323 expect(generated.body.endsWith("\n\n")).toBe(false);
324 }),
325 ),
326 );
327
328 it.effect("generates branch names and normalizes branch fragments", () =>
329 withFakeCodexEnv(
330 {
331 output: JSON.stringify({
332 branch: " Feat/Session ",
333 }),
334 stdinMustNotContain: "Image attachments supplied to the model",
335 },
336 (textGeneration) =>
337 Effect.gen(function* () {
338 const generated = yield* textGeneration.generateBranchName({
339 cwd: process.cwd(),
340 message: "Please update session handling.",
341 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
342 });
343
344 expect(generated.branch).toBe("feat/session");
345 }),
346 ),
347 );
348
349 it.effect("generates thread titles and trims them for sidebar use", () =>
350 withFakeCodexEnv(
351 {
352 output: JSON.stringify({
353 title:
354 ' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
355 }),
356 },
357 (textGeneration) =>
358 Effect.gen(function* () {
359 const generated = yield* textGeneration.generateThreadTitle({
360 cwd: process.cwd(),
361 message: "Please investigate websocket reconnect regressions after a worktree restore.",
362 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
363 });
364
365 expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
366 }),
367 ),
368 );
369
370 it.effect("generates handovers with Luna High", () =>
371 withFakeCodexEnv(
372 {
373 output: JSON.stringify({
374 handover: "\n# Goal\n\nContinue the migration.\n",
375 }),
376 requireArg: "gpt-5.6-luna",
377 requireReasoningEffort: "high",
378 stdinMustContain: "Thread contents:",
379 },
380 (textGeneration) =>
381 Effect.gen(function* () {
382 const generated = yield* textGeneration.generateHandover({
383 cwd: process.cwd(),
384 threadContents: "User: Continue the migration",
385 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.6-luna", [
386 { id: "reasoningEffort", value: "high" },
387 ]),
388 });
389
390 expect(generated.handover).toBe("# Goal\n\nContinue the migration.");
391 }),
392 ),
393 );
394
395 it.effect("falls back when thread title normalization becomes whitespace-only", () =>
396 withFakeCodexEnv(
397 {
398 output: JSON.stringify({
399 title: ' """ """ ',
400 }),
401 },
402 (textGeneration) =>
403 Effect.gen(function* () {
404 const generated = yield* textGeneration.generateThreadTitle({
405 cwd: process.cwd(),
406 message: "Name this thread.",
407 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
408 });
409
410 expect(generated.title).toBe("New thread");
411 }),
412 ),
413 );
414
415 it.effect("trims whitespace exposed after quote removal in thread titles", () =>
416 withFakeCodexEnv(
417 {
418 output: JSON.stringify({
419 title: ` "' hello world '" `,
420 }),
421 },
422 (textGeneration) =>
423 Effect.gen(function* () {
424 const generated = yield* textGeneration.generateThreadTitle({
425 cwd: process.cwd(),
426 message: "Name this thread.",
427 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
428 });
429
430 expect(generated.title).toBe("hello world");
431 }),
432 ),
433 );
434
435 it.effect("omits attachment metadata section when no attachments are provided", () =>
436 withFakeCodexEnv(
437 {
438 output: JSON.stringify({
439 branch: "fix/session-timeout",
440 }),
441 stdinMustNotContain: "Attachment metadata:",
442 },
443 (textGeneration) =>
444 Effect.gen(function* () {
445 const generated = yield* textGeneration.generateBranchName({
446 cwd: process.cwd(),
447 message: "Fix timeout behavior.",
448 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
449 });
450
451 expect(generated.branch).toBe("fix/session-timeout");
452 }),
453 ),
454 );
455
456 it.effect("passes image attachments through as codex image inputs", () =>
457 withFakeCodexEnv(
458 {
459 output: JSON.stringify({
460 branch: "fix/ui-regression",
461 }),
462 requireImage: true,
463 stdinMustContain: "Attachment metadata:",
464 },
465 (textGeneration) =>
466 Effect.gen(function* () {
467 const fs = yield* FileSystem.FileSystem;
468 const path = yield* Path.Path;
469 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
470 const attachmentId = "thread-branch-image-attachment";
471 const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
472 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
473 yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
474
475 const generated = yield* textGeneration.generateBranchName({
476 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
477 cwd: process.cwd(),
478 message: "Fix layout bug from screenshot.",
479 attachments: [
480 {
481 type: "image",
482 id: attachmentId,
483 name: "bug.png",
484 mimeType: "image/png",
485 sizeBytes: 5,
486 },
487 ],
488 });
489
490 expect(generated.branch).toBe("fix/ui-regression");
491 }),
492 ),
493 );
494
495 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
496 withFakeCodexEnv(
497 {
498 output: JSON.stringify({
499 branch: "fix/ui-regression",
500 }),
501 requireImage: true,
502 },
503 (textGeneration) =>
504 Effect.gen(function* () {
505 const fs = yield* FileSystem.FileSystem;
506 const path = yield* Path.Path;
507 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
508 const attachmentId = "thread-1-attachment";
509 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
510 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
511 yield* fs.writeFile(imagePath, Buffer.from("hello"));
512
513 const generated = yield* textGeneration
514 .generateBranchName({
515 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
516 cwd: process.cwd(),
517 message: "Fix layout bug from screenshot.",
518 attachments: [
519 {
520 type: "image",
521 id: attachmentId,
522 name: "bug.png",
523 mimeType: "image/png",
524 sizeBytes: 5,
525 },
526 ],
527 })
528 .pipe(
529 Effect.tap(() =>
530 fs.stat(imagePath).pipe(
531 Effect.map((fileInfo) => {
532 expect(fileInfo.type).toBe("File");
533 }),
534 ),
535 ),
536 Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
537 );
538
539 expect(generated.branch).toBe("fix/ui-regression");
540 }),
541 ),
542 );
543
544 it.effect("ignores missing attachment ids for codex image inputs", () =>
545 withFakeCodexEnv(
546 {
547 output: JSON.stringify({
548 branch: "fix/ui-regression",
549 }),
550 requireImage: true,
551 },
552 (textGeneration) =>
553 Effect.gen(function* () {
554 const fs = yield* FileSystem.FileSystem;
555 const path = yield* Path.Path;
556 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
557 const missingAttachmentId = "thread-missing-attachment";
558 const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
559 yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
560
561 const result = yield* textGeneration
562 .generateBranchName({
563 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
564 cwd: process.cwd(),
565 message: "Fix layout bug from screenshot.",
566 attachments: [
567 {
568 type: "image",
569 id: missingAttachmentId,
570 name: "outside.png",
571 mimeType: "image/png",
572 sizeBytes: 5,
573 },
574 ],
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("missing --image input");
582 }
583 }),
584 ),
585 );
586
587 it.effect(
588 "fails with typed TextGenerationError when codex returns wrong branch payload shape",
589 () =>
590 withFakeCodexEnv(
591 {
592 output: JSON.stringify({
593 title: "This is not a branch payload",
594 }),
595 },
596 (textGeneration) =>
597 Effect.gen(function* () {
598 const result = yield* textGeneration
599 .generateBranchName({
600 cwd: process.cwd(),
601 message: "Fix websocket reconnect flake",
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("Codex returned invalid structured output");
610 }
611 }),
612 ),
613 );
614
615 it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
616 withFakeCodexEnv(
617 {
618 output: JSON.stringify({ subject: "ignored", body: "" }),
619 exitCode: 1,
620 stderr: "codex execution failed",
621 },
622 (textGeneration) =>
623 Effect.gen(function* () {
624 const result = yield* textGeneration
625 .generateCommitMessage({
626 cwd: process.cwd(),
627 branch: "feature/codex-error",
628 stagedSummary: "M README.md",
629 stagedPatch: "diff --git a/README.md b/README.md",
630 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
631 })
632 .pipe(Effect.result);
633
634 expect(Result.isFailure(result)).toBe(true);
635 if (Result.isFailure(result)) {
636 expect(result.failure).toBeInstanceOf(TextGenerationError);
637 expect(result.failure.message).toContain(
638 "Codex CLI command failed: codex execution failed",
639 );
640 }
641 }),
642 ),
643 );
644});