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

ProviderRegistry.test.ts

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