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

CodexProvider.test.ts

363 lines12.1 KB

1import { assert, it } from "@effect/vitest";
2import * as Cause from "effect/Cause";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Queue from "effect/Queue";
7import * as Scope from "effect/Scope";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11import * as TestClock from "effect/testing/TestClock";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13​
14import {
15 applyPreferredCodexDefaultModel,
16 codexCustomEndpoint,
17 codexRoutesSpendNativeQuota,
18 makeCodexSkillsProbe,
19 mapCodexModelCapabilities,
20 parseCodexModelListResponse,
21} from "./CodexProvider.ts";
22​
23function makeFakeCodexAppServers() {
24 const helpers: Array<{
25 readonly codexHome: unknown;
26 readonly crash: Effect.Effect<void>;
27 readonly requests: Array<unknown>;
28 closed: boolean;
29 }> = [];
30 const spawner = ChildProcessSpawner.make((command) =>
31 Effect.gen(function* () {
32 const output = yield* Queue.unbounded<Uint8Array, Cause.Done>();
33 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
34 const crash = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(1)).pipe(
35 Effect.andThen(Queue.end(output)),
36 Effect.asVoid,
37 );
38 const helper = {
39 codexHome: command._tag === "StandardCommand" ? command.options.env?.CODEX_HOME : undefined,
40 crash,
41 requests: [] as Array<unknown>,
42 closed: false,
43 };
44 helpers.push(helper);
45 yield* Effect.addFinalizer(() => Effect.sync(() => (helper.closed = true)));
46 const respond = (id: unknown, result: unknown) =>
47 Queue.offer(output, new TextEncoder().encode(`${JSON.stringify({ id, result })}\n`));
48 return ChildProcessSpawner.makeHandle({
49 pid: ChildProcessSpawner.ProcessId(900_000_000 + helpers.length),
50 exitCode: Deferred.await(exited),
51 exitStatus: Effect.map(Deferred.await(exited), (code) => ({ _tag: "Exited", code })),
52 isRunning: Effect.map(Deferred.isDone(exited), (done) => !done),
53 kill: () => crash,
54 unref: Effect.succeed(Effect.void),
55 stdin: Sink.forEach((chunk: string | Uint8Array) =>
56 Effect.forEach(
57 (typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk))
58 .split("\n")
59 .filter(Boolean),
60 (line) => {
61 const frame = JSON.parse(line) as {
62 readonly id?: number;
63 readonly method: string;
64 readonly params?: { readonly cwds: ReadonlyArray<string> };
65 };
66 if (frame.id === undefined) return Effect.void;
67 if (frame.method === "initialize") {
68 return respond(frame.id, {
69 codexHome: "/codex-home",
70 platformFamily: "unix",
71 platformOs: "linux",
72 userAgent: "codex/0.0.0",
73 });
74 }
75 helper.requests.push(frame.params);
76 return respond(frame.id, {
77 data: (frame.params?.cwds ?? []).map((cwd) => ({
78 cwd,
79 errors: [],
80 skills: [
81 {
82 name: `skill-in-${cwd}`,
83 path: `${cwd}/SKILL.md`,
84 enabled: true,
85 description: "",
86 scope: "repo",
87 },
88 ],
89 })),
90 });
91 },
92 { discard: true },
93 ),
94 ),
95 stdout: Stream.fromQueue(output),
96 stderr: Stream.empty,
97 all: Stream.empty,
98 getInputFd: () => Sink.drain,
99 getOutputFd: () => Stream.empty,
100 });
101 }),
102 );
103 return { helpers, spawner };
105​
106it.effect("reuses one Codex skills helper per launch until it idles out", () =>
107 Effect.gen(function* () {
108 const { helpers, spawner } = makeFakeCodexAppServers();
109 const providerScope = yield* Scope.make();
110 const probe = yield* makeCodexSkillsProbe().pipe(
111 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
112 Scope.provide(providerScope),
113 );
114 const read = (cwd: string, homePath = "/home-a") =>
115 probe({ binaryPath: "codex", homePath, cwd, environment: {} }).pipe(
116 Effect.map((skills) => skills.map((skill) => skill.name)),
117 );
118​
119 assert.deepStrictEqual(yield* read("/alpha"), ["skill-in-/alpha"]);
120 assert.deepStrictEqual(yield* read("/beta"), ["skill-in-/beta"]);
121 assert.strictEqual(helpers.length, 1);
122 assert.deepStrictEqual(helpers[0]!.requests, [
123 { cwds: ["/alpha"], forceReload: true },
124 { cwds: ["/beta"], forceReload: true },
125 ]);
126​
127 // Another home is another launch identity; the previous helper retires at once.
128 assert.deepStrictEqual(yield* read("/alpha", "/home-b"), ["skill-in-/alpha"]);
129 assert.strictEqual(helpers.length, 2);
130 assert.strictEqual(helpers[0]!.closed, true);
131 assert.strictEqual(helpers[1]!.codexHome, "/home-b");
132​
133 // A helper that exits is replaced within the same read.
134 yield* helpers[1]!.crash;
135 assert.deepStrictEqual(yield* read("/beta", "/home-b"), ["skill-in-/beta"]);
136 assert.strictEqual(helpers.length, 3);
137​
138 yield* TestClock.adjust("29 seconds");
139 assert.strictEqual(helpers[2]!.closed, false);
140 yield* TestClock.adjust("1 second");
141 assert.strictEqual(helpers[2]!.closed, true);
142 assert.deepStrictEqual(yield* read("/alpha", "/home-b"), ["skill-in-/alpha"]);
143 assert.strictEqual(helpers.length, 4);
144​
145 yield* Scope.close(providerScope, Exit.void);
146 assert.strictEqual(helpers[3]!.closed, true);
147 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
148);
149​
150it("maps current Codex model capability fields", () => {
151 const capabilities = mapCodexModelCapabilities({
152 additionalSpeedTiers: [],
153 defaultReasoningEffort: "super-high",
154 description: "Test model",
155 displayName: "GPT Test",
156 hidden: false,
157 id: "gpt-test",
158 isDefault: true,
159 model: "gpt-test",
160 availableAccessPrograms: { cyber: ["standard", "daybreakBlue"] },
161 defaultServiceTier: "flex",
162 serviceTiers: [
163 {
164 id: "priority",
165 name: "Fast",
166 description: "Lower latency responses.",
167 },
168 {
169 id: "flex",
170 name: "Flex",
171 description: "Lower-cost asynchronous routing.",
172 },
173 ],
174 supportedReasoningEfforts: [
175 {
176 description: "Maximum reasoning",
177 reasoningEffort: "super-high",
178 },
179 ],
180 });
181​
182 assert.deepStrictEqual(capabilities.optionDescriptors, [
183 {
184 id: "reasoningEffort",
185 label: "Reasoning",
186 type: "select",
187 options: [{ id: "super-high", label: "super-high", isDefault: true }],
188 currentValue: "super-high",
189 },
190 {
191 id: "serviceTier",
192 label: "Service Tier",
193 type: "select",
194 options: [
195 { id: "default", label: "Standard" },
196 {
197 id: "priority",
198 label: "Fast",
199 description: "Lower latency responses.",
200 },
201 {
202 id: "flex",
203 label: "Flex",
204 description: "Lower-cost asynchronous routing.",
205 isDefault: true,
206 },
207 ],
208 currentValue: "flex",
209 },
210 {
211 id: "cyberAccessProgram",
212 label: "Cyber Access",
213 type: "select",
214 options: [
215 { id: "standard", label: "Standard", isDefault: true },
216 { id: "daybreakBlue", label: "Daybreak Blue" },
217 ],
218 currentValue: "standard",
219 },
220 ]);
221});
222​
223it("uses standard routing when the catalog has no default service tier", () => {
224 const capabilities = mapCodexModelCapabilities({
225 additionalSpeedTiers: ["fast"],
226 defaultReasoningEffort: "medium",
227 defaultServiceTier: null,
228 description: "Test model",
229 displayName: "GPT Test",
230 hidden: false,
231 id: "gpt-test",
232 isDefault: true,
233 model: "gpt-test",
234 serviceTiers: [
235 {
236 id: "priority",
237 name: "Fast",
238 description: "1.5x speed, increased usage",
239 },
240 {
241 id: "ultrafast",
242 name: "Ultrafast",
243 description: "The fastest available responses for latency-sensitive work.",
244 },
245 ],
246 supportedReasoningEfforts: [],
247 });
248​
249 assert.deepStrictEqual(capabilities.optionDescriptors, [
250 {
251 id: "serviceTier",
252 label: "Service Tier",
253 type: "select",
254 options: [
255 { id: "default", label: "Standard", isDefault: true },
256 {
257 id: "priority",
258 label: "Fast",
259 description: "1.5x speed, increased usage",
260 },
261 {
262 id: "ultrafast",
263 label: "Ultrafast",
264 description: "Even faster, more expensive",
265 },
266 ],
267 currentValue: "default",
268 },
269 ]);
270});
271​
272it("preserves Codex model display names verbatim", () => {
273 const models = parseCodexModelListResponse({
274 data: [
275 {
276 defaultReasoningEffort: "medium",
277 description: "Test model",
278 displayName: "custom-model",
279 hidden: false,
280 id: "custom-model",
281 isDefault: false,
282 model: "custom-model",
283 supportedReasoningEfforts: [],
284 },
285 ],
286 });
287​
288 assert.strictEqual(models[0]?.name, "custom-model");
289});
290​
291it("marks the most preferred available model as default", () => {
292 const models = applyPreferredCodexDefaultModel([
293 { slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
294 { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
295 ]);
296​
297 assert.deepStrictEqual(
298 models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
299 [
300 { slug: "gpt-5.6-terra", isDefault: true },
301 { slug: "gpt-5.4", isDefault: undefined },
302 ],
303 );
304});
305​
306it("ranks qualified Codex models while preserving their wire ids", () => {
307 const models = applyPreferredCodexDefaultModel([
308 {
309 slug: "openai.gpt-5.6-luna",
310 name: "Luna",
311 isCustom: false,
312 isDefault: true,
313 capabilities: null,
314 },
315 { slug: "openai.gpt-5.6-sol", name: "Sol", isCustom: false, capabilities: null },
316 ]);
317 assert.deepStrictEqual(
318 models.filter((model) => model.isDefault).map((model) => model.slug),
319 ["openai.gpt-5.6-sol"],
320 );
321});
322​
323it("ignores custom models that shadow a preferred slug", () => {
324 const models = applyPreferredCodexDefaultModel([
325 { slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
326 { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
327 ]);
328​
329 assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
330});
331​
332it("reports native quota only for an OpenAI login on a native route", () => {
333 const chatgpt = { type: "chatgpt", email: "a@example.com", planType: "pro" } as const;
334 const hub = {
335 model_provider: "hub",
336 model_providers: { hub: { base_url: "https://hub.example.com/v1" } },
337 };
338 const cases = [
339 ["default route", chatgpt, true, {}, true],
340 ["openai base url", chatgpt, true, { openai_base_url: "https://chatgpt.com/x" }, true],
341 ["openai proxy url", chatgpt, true, { openai_base_url: "https://proxy.example.com" }, false],
342 ["custom provider", chatgpt, true, hub, false],
343 ["unknown provider id", chatgpt, true, { model_provider: "missing" }, false],
344 ["unreadable config", chatgpt, true, null, false],
345 ["login not required", chatgpt, false, {}, false],
346 ["api key", { type: "apiKey" }, true, {}, false],
347 ] as const;
348 for (const [name, account, requiresOpenaiAuth, config, expected] of cases) {
349 assert.strictEqual(
350 codexRoutesSpendNativeQuota({ account, requiresOpenaiAuth }, config),
351 expected,
352 name,
353 );
354 }
355 // The custom endpoint is what a usage-limit hub is matched against.
356 assert.strictEqual(codexCustomEndpoint(hub), "https://hub.example.com");
357 assert.strictEqual(
358 codexCustomEndpoint({ openai_base_url: "http://127.0.0.1:8317/v1" }),
359 "http://127.0.0.1:8317",
360 );
361 assert.strictEqual(codexCustomEndpoint({ openai_base_url: "https://chatgpt.com/x" }), undefined);
362 assert.strictEqual(codexCustomEndpoint({}), undefined);
363});