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

ProviderRegistry.test.ts

1,059 lines39.9 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, it, assert } from "@effect/vitest";
3import {
4 Effect,
5 Exit,
6 FileSystem,
7 Layer,
8 Path,
9 PubSub,
10 Ref,
11 Schema,
12 Scope,
13 Sink,
14 Stream,
15} from "effect";
16import {
17 DEFAULT_SERVER_SETTINGS,
18 ServerSettings,
19 type ServerProvider,
20 type ServerSettings as ContractServerSettings,
21} from "@t3tools/contracts";
22import * as PlatformError from "effect/PlatformError";
23import { ChildProcessSpawner } from "effect/unstable/process";
24import { deepMerge } from "@t3tools/shared/Struct";
25​
26import {
27 checkCodexProviderStatus,
28 hasCustomModelProvider,
29 parseAuthStatusFromOutput,
30 readCodexConfigModelProvider,
31} from "./CodexProvider";
32import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider";
33import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry";
34import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings";
35import { ProviderRegistry } from "../Services/ProviderRegistry";
36​
37// ── Test helpers ────────────────────────────────────────────────────
38​
39const encoder = new TextEncoder();
40​
41function mockHandle(result: { stdout: string; stderr: string; code: number }) {
42 return ChildProcessSpawner.makeHandle({
43 pid: ChildProcessSpawner.ProcessId(1),
44 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
45 isRunning: Effect.succeed(false),
46 kill: () => Effect.void,
47 stdin: Sink.drain,
48 stdout: Stream.make(encoder.encode(result.stdout)),
49 stderr: Stream.make(encoder.encode(result.stderr)),
50 all: Stream.empty,
51 getInputFd: () => Sink.drain,
52 getOutputFd: () => Stream.empty,
53 });
55​
56function mockSpawnerLayer(
57 handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
58) {
59 return Layer.succeed(
60 ChildProcessSpawner.ChildProcessSpawner,
61 ChildProcessSpawner.make((command) => {
62 const cmd = command as unknown as { args: ReadonlyArray<string> };
63 return Effect.succeed(mockHandle(handler(cmd.args)));
64 }),
65 );
67​
68function mockCommandSpawnerLayer(
69 handler: (
70 command: string,
71 args: ReadonlyArray<string>,
72 ) => { stdout: string; stderr: string; code: number },
73) {
74 return Layer.succeed(
75 ChildProcessSpawner.ChildProcessSpawner,
76 ChildProcessSpawner.make((command) => {
77 const cmd = command as unknown as { command: string; args: ReadonlyArray<string> };
78 return Effect.succeed(mockHandle(handler(cmd.command, cmd.args)));
79 }),
80 );
82​
83function failingSpawnerLayer(description: string) {
84 return Layer.succeed(
85 ChildProcessSpawner.ChildProcessSpawner,
86 ChildProcessSpawner.make(() =>
87 Effect.fail(
88 PlatformError.systemError({
89 _tag: "NotFound",
90 module: "ChildProcess",
91 method: "spawn",
92 description,
93 }),
94 ),
95 ),
96 );
98​
99function makeMutableServerSettingsService(
100 initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS,
101) {
102 return Effect.gen(function* () {
103 const settingsRef = yield* Ref.make(initial);
104 const changes = yield* PubSub.unbounded<ContractServerSettings>();
105​
106 return {
107 start: Effect.void,
108 ready: Effect.void,
109 getSettings: Ref.get(settingsRef),
110 updateSettings: (patch) =>
111 Effect.gen(function* () {
112 const current = yield* Ref.get(settingsRef);
113 const next = Schema.decodeSync(ServerSettings)(deepMerge(current, patch));
114 yield* Ref.set(settingsRef, next);
115 yield* PubSub.publish(changes, next);
116 return next;
117 }),
118 get streamChanges() {
119 return Stream.fromPubSub(changes);
120 },
121 } satisfies ServerSettingsShape;
122 });
124​
125/**
126 * Create a temporary CODEX_HOME scoped to the current Effect test.
127 * Cleanup is registered in the test scope rather than via Vitest hooks.
128 */
129function withTempCodexHome(configContent?: string) {
130 return Effect.gen(function* () {
131 const fileSystem = yield* FileSystem.FileSystem;
132 const path = yield* Path.Path;
133 const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" });
134​
135 yield* Effect.acquireRelease(
136 Effect.sync(() => {
137 const originalCodexHome = process.env.CODEX_HOME;
138 process.env.CODEX_HOME = tmpDir;
139 return originalCodexHome;
140 }),
141 (originalCodexHome) =>
142 Effect.sync(() => {
143 if (originalCodexHome !== undefined) {
144 process.env.CODEX_HOME = originalCodexHome;
145 } else {
146 delete process.env.CODEX_HOME;
147 }
148 }),
149 );
150​
151 if (configContent !== undefined) {
152 yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent);
153 }
154​
155 return { tmpDir } as const;
156 });
158​
159it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
160 "ProviderRegistry",
161 (it) => {
162 // ── checkCodexProviderStatus tests ────────────────────────────────
163 //
164 // These tests control CODEX_HOME to ensure the custom-provider detection
165 // in hasCustomModelProvider() does not interfere with the auth-probe
166 // path being tested.
167​
168 describe("checkCodexProviderStatus", () => {
169 it.effect("returns ready when codex is installed and authenticated", () =>
170 Effect.gen(function* () {
171 // Point CODEX_HOME at an empty tmp dir (no config.toml) so the
172 // default code path (OpenAI provider, auth probe runs) is exercised.
173 yield* withTempCodexHome();
174 const status = yield* checkCodexProviderStatus();
175 assert.strictEqual(status.provider, "codex");
176 assert.strictEqual(status.status, "ready");
177 assert.strictEqual(status.installed, true);
178 assert.strictEqual(status.auth.status, "authenticated");
179 }).pipe(
180 Effect.provide(
181 mockSpawnerLayer((args) => {
182 const joined = args.join(" ");
183 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
184 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
185 throw new Error(`Unexpected args: ${joined}`);
186 }),
187 ),
188 ),
189 );
190​
191 it.effect("returns the codex plan type in auth and keeps spark for supported plans", () =>
192 Effect.gen(function* () {
193 yield* withTempCodexHome();
194 const status = yield* checkCodexProviderStatus(() =>
195 Effect.succeed({
196 type: "chatgpt" as const,
197 planType: "pro" as const,
198 sparkEnabled: true,
199 }),
200 );
201​
202 assert.strictEqual(status.provider, "codex");
203 assert.strictEqual(status.status, "ready");
204 assert.strictEqual(status.auth.status, "authenticated");
205 assert.strictEqual(status.auth.type, "pro");
206 assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
207 assert.deepStrictEqual(
208 status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
209 true,
210 );
211 }).pipe(
212 Effect.provide(
213 mockSpawnerLayer((args) => {
214 const joined = args.join(" ");
215 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
216 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
217 throw new Error(`Unexpected args: ${joined}`);
218 }),
219 ),
220 ),
221 );
222​
223 it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
224 Effect.gen(function* () {
225 yield* withTempCodexHome();
226 const status = yield* checkCodexProviderStatus(() =>
227 Effect.succeed({
228 type: "chatgpt" as const,
229 planType: "plus" as const,
230 sparkEnabled: false,
231 }),
232 );
233​
234 assert.strictEqual(status.provider, "codex");
235 assert.strictEqual(status.status, "ready");
236 assert.strictEqual(status.auth.status, "authenticated");
237 assert.strictEqual(status.auth.type, "plus");
238 assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");
239 assert.deepStrictEqual(
240 status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
241 false,
242 );
243 }).pipe(
244 Effect.provide(
245 mockSpawnerLayer((args) => {
246 const joined = args.join(" ");
247 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
248 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
249 throw new Error(`Unexpected args: ${joined}`);
250 }),
251 ),
252 ),
253 );
254​
255 it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () =>
256 Effect.gen(function* () {
257 yield* withTempCodexHome();
258 const status = yield* checkCodexProviderStatus(() =>
259 Effect.succeed({
260 type: "chatgpt" as const,
261 planType: "team" as const,
262 sparkEnabled: false,
263 }),
264 );
265​
266 assert.strictEqual(status.provider, "codex");
267 assert.strictEqual(status.auth.type, "team");
268 assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");
269 assert.deepStrictEqual(
270 status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
271 false,
272 );
273 }).pipe(
274 Effect.provide(
275 mockSpawnerLayer((args) => {
276 const joined = args.join(" ");
277 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
278 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
279 throw new Error(`Unexpected args: ${joined}`);
280 }),
281 ),
282 ),
283 );
284​
285 it.effect("returns an api key label for codex api key auth", () =>
286 Effect.gen(function* () {
287 yield* withTempCodexHome();
288 const status = yield* checkCodexProviderStatus(() =>
289 Effect.succeed({
290 type: "apiKey" as const,
291 planType: null,
292 sparkEnabled: false,
293 }),
294 );
295​
296 assert.strictEqual(status.provider, "codex");
297 assert.strictEqual(status.status, "ready");
298 assert.strictEqual(status.auth.status, "authenticated");
299 assert.strictEqual(status.auth.type, "apiKey");
300 assert.strictEqual(status.auth.label, "OpenAI API Key");
301 assert.deepStrictEqual(
302 status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
303 false,
304 );
305 }).pipe(
306 Effect.provide(
307 mockSpawnerLayer((args) => {
308 const joined = args.join(" ");
309 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
310 if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
311 throw new Error(`Unexpected args: ${joined}`);
312 }),
313 ),
314 ),
315 );
316​
317 it.effect.skipIf(process.platform === "win32")(
318 "inherits PATH when launching the codex probe with a CODEX_HOME override",
319 () =>
320 Effect.gen(function* () {
321 const fileSystem = yield* FileSystem.FileSystem;
322 const path = yield* Path.Path;
323 const binDir = yield* fileSystem.makeTempDirectoryScoped({
324 prefix: "t3-test-codex-bin-",
325 });
326 const codexPath = path.join(binDir, "codex");
327 yield* fileSystem.writeFileString(
328 codexPath,
329 [
330 "#!/bin/sh",
331 'if [ "$1" = "--version" ]; then',
332 ' echo "codex-cli 1.0.0"',
333 " exit 0",
334 "fi",
335 'if [ "$1" = "login" ] && [ "$2" = "status" ]; then',
336 ' echo "Logged in using ChatGPT"',
337 " exit 0",
338 "fi",
339 'echo "unexpected args: $*" >&2',
340 "exit 1",
341 "",
342 ].join("\n"),
343 );
344 yield* fileSystem.chmod(codexPath, 0o755);
345 const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({
346 prefix: "t3-test-codex-home-",
347 });
348 const previousPath = process.env.PATH;
349 process.env.PATH = binDir;
350​
351 try {
352 const serverSettingsLayer = ServerSettingsService.layerTest({
353 providers: {
354 codex: {
355 homePath: customCodexHome,
356 },
357 },
358 });
359​
360 const status = yield* checkCodexProviderStatus().pipe(
361 Effect.provide(serverSettingsLayer),
362 );
363 assert.strictEqual(status.provider, "codex");
364 assert.strictEqual(status.installed, true);
365 assert.strictEqual(status.status, "ready");
366 assert.strictEqual(status.auth.status, "authenticated");
367 } finally {
368 process.env.PATH = previousPath;
369 }
370 }),
371 );
372​
373 it.effect("returns unavailable when codex is missing", () =>
374 Effect.gen(function* () {
375 yield* withTempCodexHome();
376 const status = yield* checkCodexProviderStatus();
377 assert.strictEqual(status.provider, "codex");
378 assert.strictEqual(status.status, "error");
379 assert.strictEqual(status.installed, false);
380 assert.strictEqual(status.auth.status, "unknown");
381 assert.strictEqual(
382 status.message,
383 "Codex CLI (`codex`) is not installed or not on PATH.",
384 );
385 }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
386 );
387​
388 it.effect("returns unavailable when codex is below the minimum supported version", () =>
389 Effect.gen(function* () {
390 yield* withTempCodexHome();
391 const status = yield* checkCodexProviderStatus();
392 assert.strictEqual(status.provider, "codex");
393 assert.strictEqual(status.status, "error");
394 assert.strictEqual(status.installed, true);
395 assert.strictEqual(status.auth.status, "unknown");
396 assert.strictEqual(
397 status.message,
398 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
399 );
400 }).pipe(
401 Effect.provide(
402 mockSpawnerLayer((args) => {
403 const joined = args.join(" ");
404 if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
405 throw new Error(`Unexpected args: ${joined}`);
406 }),
407 ),
408 ),
409 );
410​
411 it.effect("returns unauthenticated when auth probe reports login required", () =>
412 Effect.gen(function* () {
413 yield* withTempCodexHome();
414 const status = yield* checkCodexProviderStatus();
415 assert.strictEqual(status.provider, "codex");
416 assert.strictEqual(status.status, "error");
417 assert.strictEqual(status.installed, true);
418 assert.strictEqual(status.auth.status, "unauthenticated");
419 assert.strictEqual(
420 status.message,
421 "Codex CLI is not authenticated. Run `codex login` and try again.",
422 );
423 }).pipe(
424 Effect.provide(
425 mockSpawnerLayer((args) => {
426 const joined = args.join(" ");
427 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
428 if (joined === "login status") {
429 return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
430 }
431 throw new Error(`Unexpected args: ${joined}`);
432 }),
433 ),
434 ),
435 );
436​
437 it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
438 Effect.gen(function* () {
439 yield* withTempCodexHome();
440 const status = yield* checkCodexProviderStatus();
441 assert.strictEqual(status.provider, "codex");
442 assert.strictEqual(status.status, "error");
443 assert.strictEqual(status.installed, true);
444 assert.strictEqual(status.auth.status, "unauthenticated");
445 assert.strictEqual(
446 status.message,
447 "Codex CLI is not authenticated. Run `codex login` and try again.",
448 );
449 }).pipe(
450 Effect.provide(
451 mockSpawnerLayer((args) => {
452 const joined = args.join(" ");
453 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
454 if (joined === "login status")
455 return { stdout: "Not logged in\n", stderr: "", code: 1 };
456 throw new Error(`Unexpected args: ${joined}`);
457 }),
458 ),
459 ),
460 );
461​
462 it.effect("returns warning when login status command is unsupported", () =>
463 Effect.gen(function* () {
464 yield* withTempCodexHome();
465 const status = yield* checkCodexProviderStatus();
466 assert.strictEqual(status.provider, "codex");
467 assert.strictEqual(status.status, "warning");
468 assert.strictEqual(status.installed, true);
469 assert.strictEqual(status.auth.status, "unknown");
470 assert.strictEqual(
471 status.message,
472 "Codex CLI authentication status command is unavailable in this Codex version.",
473 );
474 }).pipe(
475 Effect.provide(
476 mockSpawnerLayer((args) => {
477 const joined = args.join(" ");
478 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
479 if (joined === "login status") {
480 return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
481 }
482 throw new Error(`Unexpected args: ${joined}`);
483 }),
484 ),
485 ),
486 );
487 });
488​
489 describe("ProviderRegistryLive", () => {
490 it("treats equal provider snapshots as unchanged", () => {
491 const providers = [
492 {
493 provider: "codex",
494 status: "ready",
495 enabled: true,
496 installed: true,
497 auth: { status: "authenticated" },
498 checkedAt: "2026-03-25T00:00:00.000Z",
499 version: "1.0.0",
500 models: [],
501 },
502 {
503 provider: "claudeAgent",
504 status: "warning",
505 enabled: true,
506 installed: true,
507 auth: { status: "unknown" },
508 checkedAt: "2026-03-25T00:00:00.000Z",
509 version: "1.0.0",
510 models: [],
511 },
512 ] as const satisfies ReadonlyArray<ServerProvider>;
513​
514 assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
515 });
516​
517 it.effect("reruns codex health when codex provider settings change", () =>
518 Effect.gen(function* () {
519 const serverSettings = yield* makeMutableServerSettingsService();
520 const scope = yield* Scope.make();
521 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
522 const providerRegistryLayer = ProviderRegistryLive.pipe(
523 Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
524 Layer.provideMerge(
525 mockCommandSpawnerLayer((command, args) => {
526 const joined = args.join(" ");
527 if (joined === "--version") {
528 if (command === "codex") {
529 return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
530 }
531 return { stdout: "", stderr: "spawn ENOENT", code: 1 };
532 }
533 if (joined === "login status") {
534 return { stdout: "Logged in\n", stderr: "", code: 0 };
535 }
536 throw new Error(`Unexpected args: ${joined}`);
537 }),
538 ),
539 );
540 const runtimeServices = yield* Layer.build(
541 Layer.mergeAll(
542 Layer.succeed(ServerSettingsService, serverSettings),
543 providerRegistryLayer,
544 ),
545 ).pipe(Scope.provide(scope));
546​
547 yield* Effect.gen(function* () {
548 const registry = yield* ProviderRegistry;
549​
550 const initial = yield* registry.getProviders;
551 assert.strictEqual(
552 initial.find((status) => status.provider === "codex")?.status,
553 "ready",
554 );
555​
556 yield* serverSettings.updateSettings({
557 providers: {
558 codex: {
559 binaryPath: "/custom/codex",
560 },
561 },
562 });
563​
564 for (let attempt = 0; attempt < 20; attempt += 1) {
565 const updated = yield* registry.getProviders;
566 if (updated.find((status) => status.provider === "codex")?.status === "error") {
567 return;
568 }
569 yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 0)));
570 }
571​
572 const updated = yield* registry.getProviders;
573 assert.strictEqual(
574 updated.find((status) => status.provider === "codex")?.status,
575 "error",
576 );
577 }).pipe(Effect.provide(runtimeServices));
578 }),
579 );
580​
581 it.effect("skips codex probes entirely when the provider is disabled", () =>
582 Effect.gen(function* () {
583 const serverSettingsLayer = ServerSettingsService.layerTest({
584 providers: {
585 codex: {
586 enabled: false,
587 },
588 },
589 });
590​
591 const status = yield* checkCodexProviderStatus().pipe(
592 Effect.provide(
593 Layer.mergeAll(serverSettingsLayer, failingSpawnerLayer("spawn codex ENOENT")),
594 ),
595 );
596 assert.strictEqual(status.provider, "codex");
597 assert.strictEqual(status.enabled, false);
598 assert.strictEqual(status.status, "disabled");
599 assert.strictEqual(status.installed, false);
600 assert.strictEqual(status.message, "Codex is disabled in T3 Code settings.");
601 }),
602 );
603 });
604​
605 // ── Custom model provider: checkCodexProviderStatus integration ───
606​
607 describe("checkCodexProviderStatus with custom model provider", () => {
608 it.effect(
609 "skips auth probe and returns ready when a custom model provider is configured",
610 () =>
611 Effect.gen(function* () {
612 yield* withTempCodexHome(
613 [
614 'model_provider = "portkey"',
615 "",
616 "[model_providers.portkey]",
617 'base_url = "https://api.portkey.ai/v1"',
618 'env_key = "PORTKEY_API_KEY"',
619 ].join("\n"),
620 );
621 const status = yield* checkCodexProviderStatus();
622 assert.strictEqual(status.provider, "codex");
623 assert.strictEqual(status.status, "ready");
624 assert.strictEqual(status.installed, true);
625 assert.strictEqual(status.auth.status, "unknown");
626 assert.strictEqual(
627 status.message,
628 "Using a custom Codex model provider; OpenAI login check skipped.",
629 );
630 }).pipe(
631 Effect.provide(
632 // The spawner only handles --version; if the test attempts
633 // "login status" the throw proves the auth probe was NOT skipped.
634 mockSpawnerLayer((args) => {
635 const joined = args.join(" ");
636 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
637 throw new Error(`Auth probe should have been skipped but got args: ${joined}`);
638 }),
639 ),
640 ),
641 );
642​
643 it.effect("still reports error when codex CLI is missing even with custom provider", () =>
644 Effect.gen(function* () {
645 yield* withTempCodexHome(
646 [
647 'model_provider = "portkey"',
648 "",
649 "[model_providers.portkey]",
650 'base_url = "https://api.portkey.ai/v1"',
651 'env_key = "PORTKEY_API_KEY"',
652 ].join("\n"),
653 );
654 const status = yield* checkCodexProviderStatus();
655 assert.strictEqual(status.status, "error");
656 assert.strictEqual(status.installed, false);
657 }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
658 );
659 });
660​
661 describe("checkCodexProviderStatus with openai model provider", () => {
662 it.effect("still runs auth probe when model_provider is openai", () =>
663 Effect.gen(function* () {
664 yield* withTempCodexHome('model_provider = "openai"\n');
665 const status = yield* checkCodexProviderStatus();
666 // The auth probe runs and sees "not logged in" → error
667 assert.strictEqual(status.status, "error");
668 assert.strictEqual(status.auth.status, "unauthenticated");
669 }).pipe(
670 Effect.provide(
671 mockSpawnerLayer((args) => {
672 const joined = args.join(" ");
673 if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
674 if (joined === "login status")
675 return { stdout: "Not logged in\n", stderr: "", code: 1 };
676 throw new Error(`Unexpected args: ${joined}`);
677 }),
678 ),
679 ),
680 );
681 });
682​
683 // ── parseAuthStatusFromOutput pure tests ──────────────────────────
684​
685 describe("parseAuthStatusFromOutput", () => {
686 it("exit code 0 with no auth markers is ready", () => {
687 const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
688 assert.strictEqual(parsed.status, "ready");
689 assert.strictEqual(parsed.auth.status, "authenticated");
690 });
691​
692 it("JSON with authenticated=false is unauthenticated", () => {
693 const parsed = parseAuthStatusFromOutput({
694 stdout: '[{"authenticated":false}]\n',
695 stderr: "",
696 code: 0,
697 });
698 assert.strictEqual(parsed.status, "error");
699 assert.strictEqual(parsed.auth.status, "unauthenticated");
700 });
701​
702 it("JSON without auth marker is warning", () => {
703 const parsed = parseAuthStatusFromOutput({
704 stdout: '[{"ok":true}]\n',
705 stderr: "",
706 code: 0,
707 });
708 assert.strictEqual(parsed.status, "warning");
709 assert.strictEqual(parsed.auth.status, "unknown");
710 });
711 });
712​
713 // ── readCodexConfigModelProvider tests ─────────────────────────────
714​
715 describe("readCodexConfigModelProvider", () => {
716 it.effect("returns undefined when config file does not exist", () =>
717 Effect.gen(function* () {
718 yield* withTempCodexHome();
719 assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
720 }),
721 );
722​
723 it.effect("returns undefined when config has no model_provider key", () =>
724 Effect.gen(function* () {
725 yield* withTempCodexHome('model = "gpt-5-codex"\n');
726 assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
727 }),
728 );
729​
730 it.effect("returns the provider when model_provider is set at top level", () =>
731 Effect.gen(function* () {
732 yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
733 assert.strictEqual(yield* readCodexConfigModelProvider(), "portkey");
734 }),
735 );
736​
737 it.effect("returns openai when model_provider is openai", () =>
738 Effect.gen(function* () {
739 yield* withTempCodexHome('model_provider = "openai"\n');
740 assert.strictEqual(yield* readCodexConfigModelProvider(), "openai");
741 }),
742 );
743​
744 it.effect("ignores model_provider inside section headers", () =>
745 Effect.gen(function* () {
746 yield* withTempCodexHome(
747 [
748 'model = "gpt-5-codex"',
749 "",
750 "[model_providers.portkey]",
751 'base_url = "https://api.portkey.ai/v1"',
752 'model_provider = "should-be-ignored"',
753 "",
754 ].join("\n"),
755 );
756 assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
757 }),
758 );
759​
760 it.effect("handles comments and whitespace", () =>
761 Effect.gen(function* () {
762 yield* withTempCodexHome(
763 [
764 "# This is a comment",
765 "",
766 ' model_provider = "azure" ',
767 "",
768 "[profiles.deep-review]",
769 'model = "gpt-5-pro"',
770 ].join("\n"),
771 );
772 assert.strictEqual(yield* readCodexConfigModelProvider(), "azure");
773 }),
774 );
775​
776 it.effect("handles single-quoted values in TOML", () =>
777 Effect.gen(function* () {
778 yield* withTempCodexHome("model_provider = 'mistral'\n");
779 assert.strictEqual(yield* readCodexConfigModelProvider(), "mistral");
780 }),
781 );
782 });
783​
784 // ── hasCustomModelProvider tests ───────────────────────────────────
785​
786 describe("hasCustomModelProvider", () => {
787 it.effect("returns false when no config file exists", () =>
788 Effect.gen(function* () {
789 yield* withTempCodexHome();
790 assert.strictEqual(yield* hasCustomModelProvider, false);
791 }),
792 );
793​
794 it.effect("returns false when model_provider is not set", () =>
795 Effect.gen(function* () {
796 yield* withTempCodexHome('model = "gpt-5-codex"\n');
797 assert.strictEqual(yield* hasCustomModelProvider, false);
798 }),
799 );
800​
801 it.effect("returns false when model_provider is openai", () =>
802 Effect.gen(function* () {
803 yield* withTempCodexHome('model_provider = "openai"\n');
804 assert.strictEqual(yield* hasCustomModelProvider, false);
805 }),
806 );
807​
808 it.effect("returns true when model_provider is portkey", () =>
809 Effect.gen(function* () {
810 yield* withTempCodexHome('model_provider = "portkey"\n');
811 assert.strictEqual(yield* hasCustomModelProvider, true);
812 }),
813 );
814​
815 it.effect("returns true when model_provider is azure", () =>
816 Effect.gen(function* () {
817 yield* withTempCodexHome('model_provider = "azure"\n');
818 assert.strictEqual(yield* hasCustomModelProvider, true);
819 }),
820 );
821​
822 it.effect("returns true when model_provider is ollama", () =>
823 Effect.gen(function* () {
824 yield* withTempCodexHome('model_provider = "ollama"\n');
825 assert.strictEqual(yield* hasCustomModelProvider, true);
826 }),
827 );
828​
829 it.effect("returns true when model_provider is a custom proxy", () =>
830 Effect.gen(function* () {
831 yield* withTempCodexHome('model_provider = "my-company-proxy"\n');
832 assert.strictEqual(yield* hasCustomModelProvider, true);
833 }),
834 );
835 });
836​
837 // ── checkClaudeProviderStatus tests ──────────────────────────
838​
839 describe("checkClaudeProviderStatus", () => {
840 it.effect("returns ready when claude is installed and authenticated", () =>
841 Effect.gen(function* () {
842 const status = yield* checkClaudeProviderStatus();
843 assert.strictEqual(status.provider, "claudeAgent");
844 assert.strictEqual(status.status, "ready");
845 assert.strictEqual(status.installed, true);
846 assert.strictEqual(status.auth.status, "authenticated");
847 }).pipe(
848 Effect.provide(
849 mockSpawnerLayer((args) => {
850 const joined = args.join(" ");
851 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
852 if (joined === "auth status")
853 return {
854 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
855 stderr: "",
856 code: 0,
857 };
858 throw new Error(`Unexpected args: ${joined}`);
859 }),
860 ),
861 ),
862 );
863​
864 it.effect("returns a display label for claude subscription types", () =>
865 Effect.gen(function* () {
866 const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
867 assert.strictEqual(status.provider, "claudeAgent");
868 assert.strictEqual(status.status, "ready");
869 assert.strictEqual(status.auth.status, "authenticated");
870 assert.strictEqual(status.auth.type, "maxplan");
871 assert.strictEqual(status.auth.label, "Claude Max Subscription");
872 }).pipe(
873 Effect.provide(
874 mockSpawnerLayer((args) => {
875 const joined = args.join(" ");
876 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
877 if (joined === "auth status")
878 return {
879 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
880 stderr: "",
881 code: 0,
882 };
883 throw new Error(`Unexpected args: ${joined}`);
884 }),
885 ),
886 ),
887 );
888​
889 it.effect("returns an api key label for claude api key auth", () =>
890 Effect.gen(function* () {
891 const status = yield* checkClaudeProviderStatus();
892 assert.strictEqual(status.provider, "claudeAgent");
893 assert.strictEqual(status.status, "ready");
894 assert.strictEqual(status.auth.status, "authenticated");
895 assert.strictEqual(status.auth.type, "apiKey");
896 assert.strictEqual(status.auth.label, "Claude API Key");
897 }).pipe(
898 Effect.provide(
899 mockSpawnerLayer((args) => {
900 const joined = args.join(" ");
901 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
902 if (joined === "auth status")
903 return {
904 stdout: '{"loggedIn":true,"authMethod":"api-key"}\n',
905 stderr: "",
906 code: 0,
907 };
908 throw new Error(`Unexpected args: ${joined}`);
909 }),
910 ),
911 ),
912 );
913​
914 it.effect("returns unavailable when claude is missing", () =>
915 Effect.gen(function* () {
916 const status = yield* checkClaudeProviderStatus();
917 assert.strictEqual(status.provider, "claudeAgent");
918 assert.strictEqual(status.status, "error");
919 assert.strictEqual(status.installed, false);
920 assert.strictEqual(status.auth.status, "unknown");
921 assert.strictEqual(
922 status.message,
923 "Claude Agent CLI (`claude`) is not installed or not on PATH.",
924 );
925 }).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
926 );
927​
928 it.effect("returns error when version check fails with non-zero exit code", () =>
929 Effect.gen(function* () {
930 const status = yield* checkClaudeProviderStatus();
931 assert.strictEqual(status.provider, "claudeAgent");
932 assert.strictEqual(status.status, "error");
933 assert.strictEqual(status.installed, true);
934 }).pipe(
935 Effect.provide(
936 mockSpawnerLayer((args) => {
937 const joined = args.join(" ");
938 if (joined === "--version")
939 return { stdout: "", stderr: "Something went wrong", code: 1 };
940 throw new Error(`Unexpected args: ${joined}`);
941 }),
942 ),
943 ),
944 );
945​
946 it.effect("returns unauthenticated when auth status reports not logged in", () =>
947 Effect.gen(function* () {
948 const status = yield* checkClaudeProviderStatus();
949 assert.strictEqual(status.provider, "claudeAgent");
950 assert.strictEqual(status.status, "error");
951 assert.strictEqual(status.installed, true);
952 assert.strictEqual(status.auth.status, "unauthenticated");
953 assert.strictEqual(
954 status.message,
955 "Claude is not authenticated. Run `claude auth login` and try again.",
956 );
957 }).pipe(
958 Effect.provide(
959 mockSpawnerLayer((args) => {
960 const joined = args.join(" ");
961 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
962 if (joined === "auth status")
963 return {
964 stdout: '{"loggedIn":false}\n',
965 stderr: "",
966 code: 1,
967 };
968 throw new Error(`Unexpected args: ${joined}`);
969 }),
970 ),
971 ),
972 );
973​
974 it.effect("returns unauthenticated when output includes 'not logged in'", () =>
975 Effect.gen(function* () {
976 const status = yield* checkClaudeProviderStatus();
977 assert.strictEqual(status.provider, "claudeAgent");
978 assert.strictEqual(status.status, "error");
979 assert.strictEqual(status.installed, true);
980 assert.strictEqual(status.auth.status, "unauthenticated");
981 }).pipe(
982 Effect.provide(
983 mockSpawnerLayer((args) => {
984 const joined = args.join(" ");
985 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
986 if (joined === "auth status")
987 return { stdout: "Not logged in\n", stderr: "", code: 1 };
988 throw new Error(`Unexpected args: ${joined}`);
989 }),
990 ),
991 ),
992 );
993​
994 it.effect("returns warning when auth status command is unsupported", () =>
995 Effect.gen(function* () {
996 const status = yield* checkClaudeProviderStatus();
997 assert.strictEqual(status.provider, "claudeAgent");
998 assert.strictEqual(status.status, "warning");
999 assert.strictEqual(status.installed, true);
1000 assert.strictEqual(status.auth.status, "unknown");
1001 assert.strictEqual(
1002 status.message,
1003 "Claude Agent authentication status command is unavailable in this version of Claude.",
1004 );
1005 }).pipe(
1006 Effect.provide(
1007 mockSpawnerLayer((args) => {
1008 const joined = args.join(" ");
1009 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
1010 if (joined === "auth status")
1011 return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
1012 throw new Error(`Unexpected args: ${joined}`);
1013 }),
1014 ),
1015 ),
1016 );
1017 });
1018​
1019 // ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
1020​
1021 describe("parseClaudeAuthStatusFromOutput", () => {
1022 it("exit code 0 with no auth markers is ready", () => {
1023 const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
1024 assert.strictEqual(parsed.status, "ready");
1025 assert.strictEqual(parsed.auth.status, "authenticated");
1026 });
1027​
1028 it("JSON with loggedIn=true is authenticated", () => {
1029 const parsed = parseClaudeAuthStatusFromOutput({
1030 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
1031 stderr: "",
1032 code: 0,
1033 });
1034 assert.strictEqual(parsed.status, "ready");
1035 assert.strictEqual(parsed.auth.status, "authenticated");
1036 });
1037​
1038 it("JSON with loggedIn=false is unauthenticated", () => {
1039 const parsed = parseClaudeAuthStatusFromOutput({
1040 stdout: '{"loggedIn":false}\n',
1041 stderr: "",
1042 code: 0,
1043 });
1044 assert.strictEqual(parsed.status, "error");
1045 assert.strictEqual(parsed.auth.status, "unauthenticated");
1046 });
1047​
1048 it("JSON without auth marker is warning", () => {
1049 const parsed = parseClaudeAuthStatusFromOutput({
1050 stdout: '{"ok":true}\n',
1051 stderr: "",
1052 code: 0,
1053 });
1054 assert.strictEqual(parsed.status, "warning");
1055 assert.strictEqual(parsed.auth.status, "unknown");
1056 });
1057 });
1058 },