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