Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it } from "@effect/vitest";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as Scope from "effect/Scope";
12import { createModelSelection } from "@t3tools/shared/model";
13import { expect } from "vite-plus/test";
14
15import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts";
16
17import * as ServerConfig from "../config.ts";
18import { makeProcessProbe, processProbeSource } from "../testUtils/processProbe.ts";
19import * as TextGeneration from "./TextGeneration.ts";
20import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
21import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
22const decodeCodexSettings = Schema.decodeSync(CodexSettings);
23
24const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
25 ProviderInstanceId.make("codex"),
26 "gpt-5.4-mini",
27);
28
29const layerCodexTextGenerationTest = ServerConfig.ServerConfig.layerTest(process.cwd(), {
30 prefix: "t3code-codex-text-generation-test-",
31}).pipe(Layer.provideMerge(NodeServices.layer));
32
33interface FakeCodexInput {
34 output: string;
35 lifecycle?: { port: number; command: "exec" | "mcp list" };
36 exitCode?: number;
37 stderr?: string;
38 requireImage?: boolean;
39 requireServiceTier?: string;
40 requireReasoningEffort?: string;
41 forbidReasoningEffort?: boolean;
42 requireArg?: string;
43 forbidArg?: string;
44 stdinMustContain?: string;
45 stdinMustNotContain?: string;
46 mcpServers?: ReadonlyArray<{ name: string; enabled: boolean }> | number;
47}
48
49function makeFakeCodexBinary(dir: string, input: FakeCodexInput) {
50 const check = JSON.stringify({
51 requireImage: input.requireImage ?? false,
52 requireServiceTier: input.requireServiceTier ?? null,
53 requireReasoningEffort: input.requireReasoningEffort ?? null,
54 forbidReasoningEffort: input.forbidReasoningEffort ?? false,
55 requireArg: input.requireArg ?? null,
56 forbidArg: input.forbidArg ?? null,
57 stdinMustContain: input.stdinMustContain ?? null,
58 stdinMustNotContain: input.stdinMustNotContain ?? null,
59 mcpServers: input.mcpServers ?? [],
60 stderr: input.stderr ?? null,
61 output: input.output,
62 exitCode: input.exitCode ?? 0,
63 });
64 return Effect.gen(function* () {
65 const path = yield* Path.Path;
66 return writeFakeCli({
67 directory: path.join(dir, "bin"),
68 name: "codex",
69 source: [
70 'import * as NodeFS from "node:fs";',
71 `const check = ${check};`,
72 "const args = process.argv.slice(2);",
73 'const isMcpList = args.includes("mcp") && args.includes("list");',
74 ...(input.lifecycle === undefined
75 ? []
76 : [
77 `if (isMcpList === ${input.lifecycle.command === "mcp list"}) {`,
78 'process.on("SIGTERM", () => {});',
79 processProbeSource(input.lifecycle.port),
80 "await new Promise(() => {});",
81 "}",
82 ]),
83 "if (isMcpList) {",
84 ' if (typeof check.mcpServers === "number") process.exit(check.mcpServers);',
85 " process.stdout.write(JSON.stringify(check.mcpServers));",
86 " process.exit(0);",
87 "}",
88 'const originalArgs = ` ${args.join(" ")} `;',
89 "let outputPath = null;",
90 "let seenImage = false;",
91 'let seenServiceTier = "";',
92 'let seenReasoningEffort = "";',
93 "for (let index = 0; index < args.length; index += 1) {",
94 ' if (args[index] === "--image") {',
95 " index += 1;",
96 " if (args[index]) seenImage = true;",
97 ' } else if (args[index] === "--config") {',
98 " index += 1;",
99 ' const value = args[index] ?? "";',
100 ' if (value.startsWith("service_tier=")) seenServiceTier = value;',
101 ' if (value.startsWith("model_reasoning_effort=")) seenReasoningEffort = value;',
102 ' } else if (args[index] === "--output-last-message") {',
103 " index += 1;",
104 " outputPath = args[index] ?? null;",
105 " }",
106 "}",
107 "const chunks = [];",
108 "for await (const chunk of process.stdin) chunks.push(chunk);",
109 'const stdinContent = Buffer.concat(chunks).toString("utf8");',
110 "function fail(message, code) {",
111 ' process.stderr.write(message + "\\n");',
112 " process.exit(code);",
113 "}",
114 "if (check.requireArg !== null && !originalArgs.includes(` ${check.requireArg} `)) {",
115 ' fail("missing arg: " + check.requireArg, 8);',
116 "}",
117 "if (check.forbidArg !== null && originalArgs.includes(` ${check.forbidArg} `)) {",
118 ' fail("forbidden arg: " + check.forbidArg, 9);',
119 "}",
120 'if (check.requireImage && !seenImage) fail("missing --image input", 2);',
121 "if (",
122 " check.requireServiceTier !== null &&",
123 ' seenServiceTier !== `service_tier="${check.requireServiceTier}"`',
124 ") {",
125 ' fail("unexpected service tier config: " + seenServiceTier, 5);',
126 "}",
127 "if (",
128 " check.requireReasoningEffort !== null &&",
129 ' seenReasoningEffort !== `model_reasoning_effort="${check.requireReasoningEffort}"`',
130 ") {",
131 ' fail("unexpected reasoning effort config: " + seenReasoningEffort, 6);',
132 "}",
133 "if (check.forbidReasoningEffort && seenReasoningEffort.length > 0) {",
134 ' fail("reasoning effort config should be omitted: " + seenReasoningEffort, 7);',
135 "}",
136 "if (check.stdinMustContain !== null && !stdinContent.includes(check.stdinMustContain)) {",
137 ' fail("stdin missing expected content", 3);',
138 "}",
139 "if (check.stdinMustNotContain !== null && stdinContent.includes(check.stdinMustNotContain)) {",
140 ' fail("stdin contained forbidden content", 4);',
141 "}",
142 'if (check.stderr !== null) process.stderr.write(check.stderr + "\\n");',
143 'if (outputPath !== null) NodeFS.writeFileSync(outputPath, check.output + "\\n");',
144 "process.exitCode = check.exitCode;",
145 "",
146 ].join("\n"),
147 });
148 });
149}
150
151function withFakeCodexEnv<A, E, R>(
152 input: FakeCodexInput & {
153 launchArgs?: string;
154 environment?: NodeJS.ProcessEnv;
155 models?: ReadonlyArray<string>;
156 managedRuntime?: boolean;
157 },
158 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
159) {
160 return Effect.gen(function* () {
161 const fs = yield* FileSystem.FileSystem;
162 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
163 const codexPath = yield* makeFakeCodexBinary(tempDir, input);
164 const config = decodeCodexSettings({ binaryPath: codexPath, launchArgs: input.launchArgs });
165 const textGeneration = yield* makeCodexTextGeneration(
166 config,
167 input.environment === undefined ? undefined : { ...process.env, ...input.environment },
168 Effect.succeed(
169 (input.models ?? []).map((slug) => ({
170 slug,
171 name: slug,
172 isCustom: false,
173 capabilities: null,
174 })),
175 ),
176 input.managedRuntime
177 ? Effect.succeed({
178 config,
179 environment: input.environment ?? process.env,
180 revision: "test",
181 })
182 : undefined,
183 );
184 return yield* effectFn(textGeneration);
185 }).pipe(Effect.scoped);
186}
187
188it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => {
189 it.effect.each(["exec", "mcp list"] as const)(
190 "kills a stalled %s CLI when its request is interrupted",
191 (command) =>
192 Effect.gen(function* () {
193 const probe = yield* makeProcessProbe;
194 yield* withFakeCodexEnv(
195 { output: "", lifecycle: { port: probe.port, command } },
196 (textGeneration) =>
197 Effect.gen(function* () {
198 const fiber = yield* textGeneration
199 .generateThreadTitle({
200 cwd: process.cwd(),
201 message: "Name this thread",
202 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
203 })
204 .pipe(Effect.forkScoped);
205 yield* probe.started;
206
207 const interrupted = yield* Fiber.interrupt(fiber).pipe(Effect.forkScoped);
208 yield* probe.exited;
209 yield* Fiber.join(interrupted);
210 const exit = yield* Fiber.await(fiber);
211 expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
212 }),
213 );
214 }),
215 );
216
217 it.effect.each(["gpt-5.6-luna", "openai.gpt-5.6-luna"])(
218 "dispatches the qualified live model for %s",
219 (selectedModel) =>
220 withFakeCodexEnv(
221 {
222 output: JSON.stringify({ title: "Bedrock title" }),
223 models: ["openai.gpt-5.6-luna"],
224 requireArg: "--model openai.gpt-5.6-luna",
225 forbidArg: "--model gpt-5.6-luna",
226 },
227 (textGeneration) =>
228 Effect.gen(function* () {
229 const result = yield* textGeneration.generateThreadTitle({
230 cwd: process.cwd(),
231 message: "Describe this change",
232 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), selectedModel),
233 });
234 expect(result.title).toBe("Bedrock title");
235 }),
236 ),
237 );
238
239 it.effect("omits a persisted service tier for managed ChatGPT text generation", () =>
240 withFakeCodexEnv(
241 {
242 output: JSON.stringify({ subject: "Update project", body: "" }),
243 managedRuntime: true,
244 forbidArg: 'service_tier="priority"',
245 },
246 (textGeneration) =>
247 textGeneration.generateCommitMessage({
248 cwd: process.cwd(),
249 branch: "feature/chatgpt",
250 stagedSummary: "M README.md",
251 stagedPatch: "diff --git a/README.md b/README.md",
252 modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
253 { id: "serviceTier", value: "priority" },
254 ]),
255 }),
256 ),
257 );
258
259 it.effect("generates titles with the user's MCP servers and plugins off", () =>
260 withFakeCodexEnv(
261 {
262 output: JSON.stringify({ title: "Remove default shapes" }),
263 mcpServers: [
264 { name: "augmenter", enabled: true },
265 { name: "my.server", enabled: true },
266 { name: "already-off", enabled: false },
267 ],
268 requireArg:
269 '--config features.plugins=false --config features.apps=false --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}}',
270 },
271 (textGeneration) =>
272 Effect.gen(function* () {
273 const result = yield* textGeneration.generateThreadTitle({
274 cwd: process.cwd(),
275 message: "Augmenter task 1. Use the Augmenter MCP: link_thread when you start.",
276 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
277 });
278 expect(result.title).toBe("Remove default shapes");
279 }),
280 ),
281 );
282
283 it.effect("still generates when Codex cannot list its MCP servers", () =>
284 withFakeCodexEnv(
285 {
286 output: JSON.stringify({ branch: "remove-default-shapes" }),
287 mcpServers: 2,
288 requireArg: "--config features.plugins=false --config features.apps=false --ephemeral",
289 forbidArg: "mcp_servers=",
290 },
291 (textGeneration) =>
292 Effect.gen(function* () {
293 const result = yield* textGeneration.generateBranchName({
294 cwd: process.cwd(),
295 message: "Remove default shapes from characters",
296 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
297 });
298 expect(result.branch).toBe("remove-default-shapes");
299 }),
300 ),
301 );
302
303 it.effect("keeps plugins and apps off over launch args that turn them on", () =>
304 withFakeCodexEnv(
305 {
306 output: JSON.stringify({ title: "Remove default shapes" }),
307 launchArgs: "--config features.plugins=true --config features.apps=true",
308 requireArg:
309 "--config features.plugins=true --config features.apps=true --config features.plugins=false --config features.apps=false --ephemeral",
310 },
311 (textGeneration) =>
312 Effect.gen(function* () {
313 const result = yield* textGeneration.generateThreadTitle({
314 cwd: process.cwd(),
315 message: "Remove default shapes from characters",
316 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
317 });
318 expect(result.title).toBe("Remove default shapes");
319 }),
320 ),
321 );
322
323 it.effect("passes exec-safe launch args into codex exec", () =>
324 withFakeCodexEnv(
325 {
326 output: JSON.stringify({
327 subject: "Add important change",
328 body: "",
329 }),
330 launchArgs: "--strict-config --listen off",
331 requireArg: "--strict-config",
332 forbidArg: "--listen",
333 },
334 (textGeneration) =>
335 textGeneration.generateCommitMessage({
336 cwd: process.cwd(),
337 branch: "feature/codex-effect",
338 stagedSummary: "M README.md",
339 stagedPatch: "diff --git a/README.md b/README.md",
340 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
341 }),
342 ),
343 );
344
345 it.effect("generates branch names even when the ambient scope is already closed", () =>
346 withFakeCodexEnv(
347 {
348 output: JSON.stringify({
349 branch: "feat/background-generation",
350 }),
351 },
352 (textGeneration) =>
353 Effect.gen(function* () {
354 // Background fibers can outlive request scopes; temp files scoped there would be reaped on creation.
355 const closedScope = yield* Scope.make();
356 yield* Scope.close(closedScope, Exit.void);
357
358 const generated = yield* textGeneration
359 .generateBranchName({
360 cwd: process.cwd(),
361 message: "Please update session handling.",
362 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
363 })
364 .pipe(Effect.provideService(Scope.Scope, closedScope));
365
366 expect(generated.branch).toBe("feat/background-generation");
367 }),
368 ),
369 );
370
371 it.effect("returns the refinement signal for an unresolved subject", () =>
372 withFakeCodexEnv(
373 { output: JSON.stringify({ title: "Investigate issue", needsRefinement: true }) },
374 (textGeneration) =>
375 Effect.gen(function* () {
376 expect(
377 yield* textGeneration.generateThreadTitle({
378 cwd: process.cwd(),
379 message: "Fix this",
380 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
381 }),
382 ).toEqual({ title: "Investigate issue", needsRefinement: true });
383 }),
384 ),
385 );
386
387 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
388 withFakeCodexEnv(
389 {
390 output: JSON.stringify({
391 branch: "fix/ui-regression",
392 }),
393 requireImage: true,
394 },
395 (textGeneration) =>
396 Effect.gen(function* () {
397 const fs = yield* FileSystem.FileSystem;
398 const path = yield* Path.Path;
399 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
400 const attachmentId = "thread-1-attachment";
401 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
402 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
403 yield* fs.writeFile(imagePath, Buffer.from("hello"));
404
405 const generated = yield* textGeneration
406 .generateBranchName({
407 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
408 cwd: process.cwd(),
409 message: "Fix layout bug from screenshot.",
410 attachments: [
411 {
412 type: "image",
413 id: attachmentId,
414 name: "bug.png",
415 mimeType: "image/png",
416 sizeBytes: 5,
417 },
418 ],
419 })
420 .pipe(
421 Effect.tap(() =>
422 fs.stat(imagePath).pipe(
423 Effect.map((fileInfo) => {
424 expect(fileInfo.type).toBe("File");
425 }),
426 ),
427 ),
428 Effect.ensuring(fs.remove(imagePath).pipe(Effect.ignore)),
429 );
430
431 expect(generated.branch).toBe("fix/ui-regression");
432 }),
433 ),
434 );
435});