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