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