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

CodexTextGeneration.test.ts

538 lines19.8 KB

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