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 { 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 });
56}
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 );
68}
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 );
83}
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 );
99}
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 });
125}
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 });
159}
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(
977 "includes Claude Opus 4.7 with xhigh as the default effort on supported versions",
978 () =>
979 Effect.gen(function* () {
980 const status = yield* checkClaudeProviderStatus();
981 const opus47 = status.models.find((model) => model.slug === "claude-opus-4-7");
982 if (!opus47) {
983 assert.fail("Expected Claude Opus 4.7 to be present for Claude Code v2.1.111.");
984 }
985 if (!opus47.capabilities) {
986 assert.fail(
987 "Expected Claude Opus 4.7 capabilities to be present for Claude Code v2.1.111.",
988 );
989 }
990 assert.deepStrictEqual(
991 opus47.capabilities.reasoningEffortLevels.find((level) => level.isDefault),
992 { value: "xhigh", label: "Extra High", isDefault: true },
993 );
994 }).pipe(
995 Effect.provide(
996 mockSpawnerLayer((args) => {
997 const joined = args.join(" ");
998 if (joined === "--version") return { stdout: "2.1.111\n", stderr: "", code: 0 };
999 if (joined === "auth status")
1000 return {
1001 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
1002 stderr: "",
1003 code: 0,
1004 };
1005 throw new Error(`Unexpected args: ${joined}`);
1006 }),
1007 ),
1008 ),
1009 );
1010
1011 it.effect("hides Claude Opus 4.7 on older Claude Code versions", () =>
1012 Effect.gen(function* () {
1013 const status = yield* checkClaudeProviderStatus();
1014 assert.strictEqual(
1015 status.models.some((model) => model.slug === "claude-opus-4-7"),
1016 false,
1017 );
1018 assert.strictEqual(
1019 status.message,
1020 "Claude Code v2.1.110 is too old for Claude Opus 4.7. Upgrade to v2.1.111 or newer to access it.",
1021 );
1022 }).pipe(
1023 Effect.provide(
1024 mockSpawnerLayer((args) => {
1025 const joined = args.join(" ");
1026 if (joined === "--version") return { stdout: "2.1.110\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("returns a display label for claude subscription types", () =>
1040 Effect.gen(function* () {
1041 const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
1042 assert.strictEqual(status.provider, "claudeAgent");
1043 assert.strictEqual(status.status, "ready");
1044 assert.strictEqual(status.auth.status, "authenticated");
1045 assert.strictEqual(status.auth.type, "maxplan");
1046 assert.strictEqual(status.auth.label, "Claude Max Subscription");
1047 }).pipe(
1048 Effect.provide(
1049 mockSpawnerLayer((args) => {
1050 const joined = args.join(" ");
1051 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
1052 if (joined === "auth status")
1053 return {
1054 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
1055 stderr: "",
1056 code: 0,
1057 };
1058 throw new Error(`Unexpected args: ${joined}`);
1059 }),
1060 ),
1061 ),
1062 );
1063
1064 it.effect("includes probed claude slash commands in the provider snapshot", () =>
1065 Effect.gen(function* () {
1066 const status = yield* checkClaudeProviderStatus(
1067 () => Effect.succeed("maxplan"),
1068 () =>
1069 Effect.succeed([
1070 {
1071 name: "review",
1072 description: "Review a pull request",
1073 input: { hint: "pr-or-branch" },
1074 },
1075 ]),
1076 );
1077
1078 assert.deepStrictEqual(status.slashCommands, [
1079 {
1080 name: "review",
1081 description: "Review a pull request",
1082 input: { hint: "pr-or-branch" },
1083 },
1084 ]);
1085 }).pipe(
1086 Effect.provide(
1087 mockSpawnerLayer((args) => {
1088 const joined = args.join(" ");
1089 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
1090 if (joined === "auth status")
1091 return {
1092 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
1093 stderr: "",
1094 code: 0,
1095 };
1096 throw new Error(`Unexpected args: ${joined}`);
1097 }),
1098 ),
1099 ),
1100 );
1101
1102 it.effect("deduplicates probed claude slash commands by name", () =>
1103 Effect.gen(function* () {
1104 const status = yield* checkClaudeProviderStatus(
1105 () => Effect.succeed("maxplan"),
1106 () =>
1107 Effect.succeed([
1108 {
1109 name: "ui",
1110 description: "Explore and refine UI",
1111 },
1112 {
1113 name: "ui",
1114 input: { hint: "component-or-screen" },
1115 },
1116 ]),
1117 );
1118
1119 assert.deepStrictEqual(status.slashCommands, [
1120 {
1121 name: "ui",
1122 description: "Explore and refine UI",
1123 input: { hint: "component-or-screen" },
1124 },
1125 ]);
1126 }).pipe(
1127 Effect.provide(
1128 mockSpawnerLayer((args) => {
1129 const joined = args.join(" ");
1130 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
1131 if (joined === "auth status")
1132 return {
1133 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
1134 stderr: "",
1135 code: 0,
1136 };
1137 throw new Error(`Unexpected args: ${joined}`);
1138 }),
1139 ),
1140 ),
1141 );
1142
1143 it.effect("returns an api key label for claude api key auth", () =>
1144 Effect.gen(function* () {
1145 const status = yield* checkClaudeProviderStatus();
1146 assert.strictEqual(status.provider, "claudeAgent");
1147 assert.strictEqual(status.status, "ready");
1148 assert.strictEqual(status.auth.status, "authenticated");
1149 assert.strictEqual(status.auth.type, "apiKey");
1150 assert.strictEqual(status.auth.label, "Claude API Key");
1151 }).pipe(
1152 Effect.provide(
1153 mockSpawnerLayer((args) => {
1154 const joined = args.join(" ");
1155 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
1156 if (joined === "auth status")
1157 return {
1158 stdout: '{"loggedIn":true,"authMethod":"api-key"}\n',
1159 stderr: "",
1160 code: 0,
1161 };
1162 throw new Error(`Unexpected args: ${joined}`);
1163 }),
1164 ),
1165 ),
1166 );
1167
1168 it.effect("returns unavailable when claude is missing", () =>
1169 Effect.gen(function* () {
1170 const status = yield* checkClaudeProviderStatus();
1171 assert.strictEqual(status.provider, "claudeAgent");
1172 assert.strictEqual(status.status, "error");
1173 assert.strictEqual(status.installed, false);
1174 assert.strictEqual(status.auth.status, "unknown");
1175 assert.strictEqual(
1176 status.message,
1177 "Claude Agent CLI (`claude`) is not installed or not on PATH.",
1178 );
1179 }).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
1180 );
1181
1182 it.effect("returns error when version check fails with non-zero exit code", () =>
1183 Effect.gen(function* () {
1184 const status = yield* checkClaudeProviderStatus();
1185 assert.strictEqual(status.provider, "claudeAgent");
1186 assert.strictEqual(status.status, "error");
1187 assert.strictEqual(status.installed, true);
1188 }).pipe(
1189 Effect.provide(
1190 mockSpawnerLayer((args) => {
1191 const joined = args.join(" ");
1192 if (joined === "--version")
1193 return { stdout: "", stderr: "Something went wrong", code: 1 };
1194 throw new Error(`Unexpected args: ${joined}`);
1195 }),
1196 ),
1197 ),
1198 );
1199
1200 it.effect("returns unauthenticated when auth status reports not logged in", () =>
1201 Effect.gen(function* () {
1202 const status = yield* checkClaudeProviderStatus();
1203 assert.strictEqual(status.provider, "claudeAgent");
1204 assert.strictEqual(status.status, "error");
1205 assert.strictEqual(status.installed, true);
1206 assert.strictEqual(status.auth.status, "unauthenticated");
1207 assert.strictEqual(
1208 status.message,
1209 "Claude is not authenticated. Run `claude auth login` and try again.",
1210 );
1211 }).pipe(
1212 Effect.provide(
1213 mockSpawnerLayer((args) => {
1214 const joined = args.join(" ");
1215 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
1216 if (joined === "auth status")
1217 return {
1218 stdout: '{"loggedIn":false}\n',
1219 stderr: "",
1220 code: 1,
1221 };
1222 throw new Error(`Unexpected args: ${joined}`);
1223 }),
1224 ),
1225 ),
1226 );
1227
1228 it.effect("returns unauthenticated when output includes 'not logged in'", () =>
1229 Effect.gen(function* () {
1230 const status = yield* checkClaudeProviderStatus();
1231 assert.strictEqual(status.provider, "claudeAgent");
1232 assert.strictEqual(status.status, "error");
1233 assert.strictEqual(status.installed, true);
1234 assert.strictEqual(status.auth.status, "unauthenticated");
1235 }).pipe(
1236 Effect.provide(
1237 mockSpawnerLayer((args) => {
1238 const joined = args.join(" ");
1239 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
1240 if (joined === "auth status")
1241 return { stdout: "Not logged in\n", stderr: "", code: 1 };
1242 throw new Error(`Unexpected args: ${joined}`);
1243 }),
1244 ),
1245 ),
1246 );
1247
1248 it.effect("returns warning when auth status command is unsupported", () =>
1249 Effect.gen(function* () {
1250 const status = yield* checkClaudeProviderStatus();
1251 assert.strictEqual(status.provider, "claudeAgent");
1252 assert.strictEqual(status.status, "warning");
1253 assert.strictEqual(status.installed, true);
1254 assert.strictEqual(status.auth.status, "unknown");
1255 assert.strictEqual(
1256 status.message,
1257 "Claude Agent authentication status command is unavailable in this version of Claude.",
1258 );
1259 }).pipe(
1260 Effect.provide(
1261 mockSpawnerLayer((args) => {
1262 const joined = args.join(" ");
1263 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
1264 if (joined === "auth status")
1265 return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
1266 throw new Error(`Unexpected args: ${joined}`);
1267 }),
1268 ),
1269 ),
1270 );
1271 });
1272
1273 // ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
1274
1275 describe("parseClaudeAuthStatusFromOutput", () => {
1276 it("exit code 0 with no auth markers is ready", () => {
1277 const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
1278 assert.strictEqual(parsed.status, "ready");
1279 assert.strictEqual(parsed.auth.status, "authenticated");
1280 });
1281
1282 it("JSON with loggedIn=true is authenticated", () => {
1283 const parsed = parseClaudeAuthStatusFromOutput({
1284 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
1285 stderr: "",
1286 code: 0,
1287 });
1288 assert.strictEqual(parsed.status, "ready");
1289 assert.strictEqual(parsed.auth.status, "authenticated");
1290 });
1291
1292 it("JSON with loggedIn=false is unauthenticated", () => {
1293 const parsed = parseClaudeAuthStatusFromOutput({
1294 stdout: '{"loggedIn":false}\n',
1295 stderr: "",
1296 code: 0,
1297 });
1298 assert.strictEqual(parsed.status, "error");
1299 assert.strictEqual(parsed.auth.status, "unauthenticated");
1300 });
1301
1302 it("JSON without auth marker is warning", () => {
1303 const parsed = parseClaudeAuthStatusFromOutput({
1304 stdout: '{"ok":true}\n',
1305 stderr: "",
1306 code: 0,
1307 });
1308 assert.strictEqual(parsed.status, "warning");
1309 assert.strictEqual(parsed.auth.status, "unknown");
1310 });
1311 });
1312 },
1313);