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