Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexTextGeneration.test.ts

437 lines16.3 KB

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;
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 });
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);
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 (e.g. the worktree branch rename fork) can run
355 // after their launching request's scope has closed; temp files must
356 // not be tied to that ambient scope or they are reaped on creation.
357 const closedScope = yield* Scope.make();
358 yield* Scope.close(closedScope, Exit.void);
359​
360 const generated = yield* textGeneration
361 .generateBranchName({
362 cwd: process.cwd(),
363 message: "Please update session handling.",
364 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
365 })
366 .pipe(Effect.provideService(Scope.Scope, closedScope));
367​
368 expect(generated.branch).toBe("feat/background-generation");
369 }),
370 ),
371 );
372​
373 it.effect("returns the refinement signal for an unresolved subject", () =>
374 withFakeCodexEnv(
375 { output: JSON.stringify({ title: "Investigate issue", needsRefinement: true }) },
376 (textGeneration) =>
377 Effect.gen(function* () {
378 expect(
379 yield* textGeneration.generateThreadTitle({
380 cwd: process.cwd(),
381 message: "Fix this",
382 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
383 }),
384 ).toEqual({ title: "Investigate issue", needsRefinement: true });
385 }),
386 ),
387 );
388​
389 it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
390 withFakeCodexEnv(
391 {
392 output: JSON.stringify({
393 branch: "fix/ui-regression",
394 }),
395 requireImage: true,
396 },
397 (textGeneration) =>
398 Effect.gen(function* () {
399 const fs = yield* FileSystem.FileSystem;
400 const path = yield* Path.Path;
401 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
402 const attachmentId = "thread-1-attachment";
403 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
404 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
405 yield* fs.writeFile(imagePath, Buffer.from("hello"));
406​
407 const generated = yield* textGeneration
408 .generateBranchName({
409 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
410 cwd: process.cwd(),
411 message: "Fix layout bug from screenshot.",
412 attachments: [
413 {
414 type: "image",
415 id: attachmentId,
416 name: "bug.png",
417 mimeType: "image/png",
418 sizeBytes: 5,
419 },
420 ],
421 })
422 .pipe(
423 Effect.tap(() =>
424 fs.stat(imagePath).pipe(
425 Effect.map((fileInfo) => {
426 expect(fileInfo.type).toBe("File");
427 }),
428 ),
429 ),
430 Effect.ensuring(fs.remove(imagePath).pipe(Effect.ignore)),
431 );
432​
433 expect(generated.branch).toBe("fix/ui-regression");
434 }),
435 ),
436 );
437});