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

ProviderRegistry.test.ts

958 lines34.2 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, it, assert } from "@effect/vitest";
3import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect";
4import * as CodexErrors from "effect-codex-app-server/errors";
5import {
6 DEFAULT_SERVER_SETTINGS,
7 ServerSettings,
8 type ServerProvider,
9 type ServerSettings as ContractServerSettings,
10} from "@t3tools/contracts";
11import * as PlatformError from "effect/PlatformError";
12import { ChildProcessSpawner } from "effect/unstable/process";
13import { deepMerge } from "@t3tools/shared/Struct";
14import { createModelCapabilities } from "@t3tools/shared/model";
15​
16import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
17import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";
18import {
19 haveProvidersChanged,
20 mergeProviderSnapshot,
21 ProviderRegistryLive,
22} from "./ProviderRegistry.ts";
23import { ServerConfig } from "../../config.ts";
24import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
25import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
26​
27process.env.T3CODE_CURSOR_ENABLED = "1";
28​
29// ── Test helpers ────────────────────────────────────────────────────
30​
31const encoder = new TextEncoder();
32​
33function selectDescriptor(
34 id: string,
35 label: string,
36 options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>,
37) {
38 return {
39 id,
40 label,
41 type: "select" as const,
42 options: [...options],
43 ...(options.find((option) => option.isDefault)?.id
44 ? { currentValue: options.find((option) => option.isDefault)?.id }
45 : {}),
46 };
48​
49function booleanDescriptor(id: string, label: string) {
50 return {
51 id,
52 label,
53 type: "boolean" as const,
54 };
56​
57function mockHandle(result: { stdout: string; stderr: string; code: number }) {
58 return ChildProcessSpawner.makeHandle({
59 pid: ChildProcessSpawner.ProcessId(1),
60 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
61 isRunning: Effect.succeed(false),
62 kill: () => Effect.void,
63 unref: Effect.succeed(Effect.void),
64 stdin: Sink.drain,
65 stdout: Stream.make(encoder.encode(result.stdout)),
66 stderr: Stream.make(encoder.encode(result.stderr)),
67 all: Stream.empty,
68 getInputFd: () => Sink.drain,
69 getOutputFd: () => Stream.empty,
70 });
72​
73function mockSpawnerLayer(
74 handler: (args: ReadonlyArray<string>) => { 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 { args: ReadonlyArray<string> };
80 return Effect.succeed(mockHandle(handler(cmd.args)));
81 }),
82 );
84​
85function mockCommandSpawnerLayer(
86 handler: (
87 command: string,
88 args: ReadonlyArray<string>,
89 ) => { stdout: string; stderr: string; code: number },
90) {
91 return Layer.succeed(
92 ChildProcessSpawner.ChildProcessSpawner,
93 ChildProcessSpawner.make((command) => {
94 const cmd = command as unknown as { command: string; args: ReadonlyArray<string> };
95 return Effect.succeed(mockHandle(handler(cmd.command, cmd.args)));
96 }),
97 );
99​
100function failingSpawnerLayer(description: string) {
101 return Layer.succeed(
102 ChildProcessSpawner.ChildProcessSpawner,
103 ChildProcessSpawner.make(() =>
104 Effect.fail(
105 PlatformError.systemError({
106 _tag: "NotFound",
107 module: "ChildProcess",
108 method: "spawn",
109 description,
110 }),
111 ),
112 ),
113 );
115​
116const codexModelCapabilities = createModelCapabilities({
117 optionDescriptors: [
118 selectDescriptor("reasoningEffort", "Reasoning", [
119 { id: "high", label: "High", isDefault: true },
120 { id: "low", label: "Low" },
121 ]),
122 booleanDescriptor("fastMode", "Fast Mode"),
123 ],
124}) satisfies NonNullable<ServerProvider["models"][number]["capabilities"]>;
125​
126function makeCodexProbeSnapshot(
127 input: Partial<CodexAppServerProviderSnapshot> = {},
128): CodexAppServerProviderSnapshot {
129 return {
130 version: "1.0.0",
131 account: {
132 account: {
133 type: "chatgpt",
134 email: "test@example.com",
135 planType: "pro",
136 },
137 requiresOpenaiAuth: false,
138 },
139 models: [
140 {
141 slug: "gpt-live-codex",
142 name: "GPT Live Codex",
143 isCustom: false,
144 capabilities: codexModelCapabilities,
145 },
146 ],
147 skills: [],
148 ...input,
149 };
151​
152function makeMutableServerSettingsService(
153 initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS,
154) {
155 return Effect.gen(function* () {
156 const settingsRef = yield* Ref.make(initial);
157 const changes = yield* PubSub.unbounded<ContractServerSettings>();
158​
159 return {
160 start: Effect.void,
161 ready: Effect.void,
162 getSettings: Ref.get(settingsRef),
163 updateSettings: (patch) =>
164 Effect.gen(function* () {
165 const current = yield* Ref.get(settingsRef);
166 const next = Schema.decodeSync(ServerSettings)(deepMerge(current, patch));
167 yield* Ref.set(settingsRef, next);
168 yield* PubSub.publish(changes, next);
169 return next;
170 }),
171 get streamChanges() {
172 return Stream.fromPubSub(changes);
173 },
174 } satisfies ServerSettingsShape;
175 });
177​
178it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
179 "ProviderRegistry",
180 (it) => {
181 describe("checkCodexProviderStatus", () => {
182 it.effect("uses the app-server account and model list for provider status", () =>
183 Effect.gen(function* () {
184 const status = yield* checkCodexProviderStatus(() =>
185 Effect.succeed(
186 makeCodexProbeSnapshot({
187 skills: [
188 {
189 name: "github:gh-fix-ci",
190 path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
191 enabled: true,
192 displayName: "CI Debug",
193 shortDescription: "Debug failing GitHub Actions checks",
194 },
195 ],
196 }),
197 ),
198 );
199​
200 assert.strictEqual(status.provider, "codex");
201 assert.strictEqual(status.status, "ready");
202 assert.strictEqual(status.installed, true);
203 assert.strictEqual(status.version, "1.0.0");
204 assert.strictEqual(status.auth.status, "authenticated");
205 assert.strictEqual(status.auth.type, "chatgpt");
206 assert.strictEqual(status.auth.label, "ChatGPT Pro 20x Subscription");
207 assert.deepStrictEqual(status.models, [
208 {
209 slug: "gpt-live-codex",
210 name: "GPT Live Codex",
211 isCustom: false,
212 capabilities: codexModelCapabilities,
213 },
214 ]);
215 assert.deepStrictEqual(status.skills, [
216 {
217 name: "github:gh-fix-ci",
218 path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
219 enabled: true,
220 displayName: "CI Debug",
221 shortDescription: "Debug failing GitHub Actions checks",
222 },
223 ]);
224 }),
225 );
226​
227 it.effect("returns unauthenticated when app-server requires OpenAI auth", () =>
228 Effect.gen(function* () {
229 const status = yield* checkCodexProviderStatus(() =>
230 Effect.succeed(
231 makeCodexProbeSnapshot({
232 account: {
233 account: null,
234 requiresOpenaiAuth: true,
235 },
236 }),
237 ),
238 );
239​
240 assert.strictEqual(status.status, "error");
241 assert.strictEqual(status.auth.status, "unauthenticated");
242 assert.strictEqual(
243 status.message,
244 "Codex CLI is not authenticated. Run `codex login` and try again.",
245 );
246 }),
247 );
248​
249 it.effect(
250 "returns ready with unknown auth when app-server does not require OpenAI auth",
251 () =>
252 Effect.gen(function* () {
253 const status = yield* checkCodexProviderStatus(() =>
254 Effect.succeed(
255 makeCodexProbeSnapshot({
256 account: {
257 account: null,
258 requiresOpenaiAuth: false,
259 },
260 }),
261 ),
262 );
263​
264 assert.strictEqual(status.status, "ready");
265 assert.strictEqual(status.auth.status, "unknown");
266 }),
267 );
268​
269 it.effect("returns an api key label for codex api key auth", () =>
270 Effect.gen(function* () {
271 const status = yield* checkCodexProviderStatus(() =>
272 Effect.succeed(
273 makeCodexProbeSnapshot({
274 account: {
275 account: { type: "apiKey" },
276 requiresOpenaiAuth: false,
277 },
278 }),
279 ),
280 );
281​
282 assert.strictEqual(status.status, "ready");
283 assert.strictEqual(status.auth.status, "authenticated");
284 assert.strictEqual(status.auth.type, "apiKey");
285 assert.strictEqual(status.auth.label, "OpenAI API Key");
286 }),
287 );
288​
289 it.effect("returns unavailable when codex is missing", () =>
290 Effect.gen(function* () {
291 const status = yield* checkCodexProviderStatus(() =>
292 Effect.fail(
293 new CodexErrors.CodexAppServerSpawnError({
294 command: "codex app-server",
295 cause: new Error("spawn codex ENOENT"),
296 }),
297 ),
298 );
299 assert.strictEqual(status.provider, "codex");
300 assert.strictEqual(status.status, "error");
301 assert.strictEqual(status.installed, false);
302 assert.strictEqual(status.auth.status, "unknown");
303 assert.strictEqual(
304 status.message,
305 "Codex CLI (`codex`) is not installed or not on PATH.",
306 );
307 }),
308 );
309 });
310​
311 describe("ProviderRegistryLive", () => {
312 it("treats equal provider snapshots as unchanged", () => {
313 const providers = [
314 {
315 provider: "codex",
316 status: "ready",
317 enabled: true,
318 installed: true,
319 auth: { status: "authenticated" },
320 checkedAt: "2026-03-25T00:00:00.000Z",
321 version: "1.0.0",
322 models: [],
323 slashCommands: [],
324 skills: [],
325 },
326 {
327 provider: "claudeAgent",
328 status: "warning",
329 enabled: true,
330 installed: true,
331 auth: { status: "unknown" },
332 checkedAt: "2026-03-25T00:00:00.000Z",
333 version: "1.0.0",
334 models: [],
335 slashCommands: [],
336 skills: [],
337 },
338 ] as const satisfies ReadonlyArray<ServerProvider>;
339​
340 assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
341 });
342​
343 it("preserves previously discovered provider models when a refresh returns none", () => {
344 const previousProvider = {
345 provider: "cursor",
346 status: "ready",
347 enabled: true,
348 installed: true,
349 auth: { status: "authenticated" },
350 checkedAt: "2026-04-14T00:00:00.000Z",
351 version: "2026.04.09-f2b0fcd",
352 models: [
353 {
354 slug: "claude-opus-4-6",
355 name: "Opus 4.6",
356 isCustom: false,
357 capabilities: createModelCapabilities({
358 optionDescriptors: [
359 selectDescriptor("reasoning", "Reasoning", [
360 { id: "high", label: "High", isDefault: true },
361 ]),
362 booleanDescriptor("fastMode", "Fast Mode"),
363 booleanDescriptor("thinking", "Thinking"),
364 ],
365 }),
366 },
367 ],
368 slashCommands: [],
369 skills: [],
370 } as const satisfies ServerProvider;
371 const refreshedProvider = {
372 ...previousProvider,
373 checkedAt: "2026-04-14T00:01:00.000Z",
374 models: [],
375 } satisfies ServerProvider;
376​
377 assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
378 ...previousProvider.models,
379 ]);
380 });
381​
382 it("fills missing capabilities from the previous provider snapshot", () => {
383 const previousProvider = {
384 provider: "cursor",
385 status: "ready",
386 enabled: true,
387 installed: true,
388 auth: { status: "authenticated" },
389 checkedAt: "2026-04-14T00:00:00.000Z",
390 version: "2026.04.09-f2b0fcd",
391 models: [
392 {
393 slug: "claude-opus-4-6",
394 name: "Opus 4.6",
395 isCustom: false,
396 capabilities: createModelCapabilities({
397 optionDescriptors: [
398 selectDescriptor("reasoning", "Reasoning", [
399 { id: "high", label: "High", isDefault: true },
400 ]),
401 booleanDescriptor("fastMode", "Fast Mode"),
402 booleanDescriptor("thinking", "Thinking"),
403 ],
404 }),
405 },
406 ],
407 slashCommands: [],
408 skills: [],
409 } as const satisfies ServerProvider;
410 const refreshedProvider = {
411 ...previousProvider,
412 checkedAt: "2026-04-14T00:01:00.000Z",
413 models: [
414 {
415 slug: "claude-opus-4-6",
416 name: "Opus 4.6",
417 isCustom: false,
418 capabilities: createModelCapabilities({
419 optionDescriptors: [],
420 }),
421 },
422 ],
423 } satisfies ServerProvider;
424​
425 assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
426 ...previousProvider.models,
427 ]);
428 });
429​
430 it.effect("probes enabled providers in the background during registry startup", () =>
431 Effect.gen(function* () {
432 let spawnCount = 0;
433 const serverSettings = yield* makeMutableServerSettingsService(
434 Schema.decodeSync(ServerSettings)(
435 deepMerge(DEFAULT_SERVER_SETTINGS, {
436 providers: {
437 codex: { enabled: false },
438 cursor: { enabled: false },
439 },
440 }),
441 ),
442 );
443 const scope = yield* Scope.make();
444 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
445 const providerRegistryLayer = ProviderRegistryLive.pipe(
446 Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
447 Layer.provideMerge(
448 ServerConfig.layerTest(process.cwd(), {
449 prefix: "t3-provider-registry-",
450 }),
451 ),
452 Layer.provideMerge(
453 mockCommandSpawnerLayer((command, args) => {
454 spawnCount += 1;
455 const joined = args.join(" ");
456 if (joined === "--version") {
457 return { stdout: "claude 1.0.0\n", stderr: "", code: 0 };
458 }
459 if (joined === "auth status") {
460 return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
461 }
462 throw new Error(`Unexpected args: ${command} ${joined}`);
463 }),
464 ),
465 );
466 const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
467 Scope.provide(scope),
468 );
469​
470 yield* Effect.gen(function* () {
471 const registry = yield* ProviderRegistry;
472 assert.strictEqual(spawnCount > 0, true);
473 const refreshed = yield* Effect.gen(function* () {
474 for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) {
475 const providers = yield* registry.getProviders;
476 const claudeProvider = providers.find(
477 (provider) => provider.provider === "claudeAgent",
478 );
479 if (claudeProvider?.status === "ready") {
480 return providers;
481 }
482 yield* Effect.sleep("10 millis");
483 }
484 return yield* registry.getProviders;
485 });
486 assert.strictEqual(
487 refreshed.find((provider) => provider.provider === "claudeAgent")?.status,
488 "ready",
489 );
490 }).pipe(Effect.provide(runtimeServices));
491 }),
492 );
493​
494 it.effect(
495 "keeps cursor disabled and skips probing when the provider setting is disabled",
496 () =>
497 Effect.gen(function* () {
498 const serverSettings = yield* makeMutableServerSettingsService(
499 Schema.decodeSync(ServerSettings)(
500 deepMerge(DEFAULT_SERVER_SETTINGS, {
501 providers: {
502 codex: {
503 enabled: false,
504 },
505 cursor: {
506 enabled: false,
507 },
508 },
509 }),
510 ),
511 );
512 let cursorSpawned = false;
513 const scope = yield* Scope.make();
514 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
515 const providerRegistryLayer = ProviderRegistryLive.pipe(
516 Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
517 Layer.provideMerge(
518 ServerConfig.layerTest(process.cwd(), {
519 prefix: "t3-provider-registry-",
520 }),
521 ),
522 Layer.provideMerge(
523 mockCommandSpawnerLayer((command, args) => {
524 if (command === "agent") {
525 cursorSpawned = true;
526 }
527 const joined = args.join(" ");
528 if (joined === "--version") {
529 return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 };
530 }
531 if (joined === "auth status") {
532 return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
533 }
534 throw new Error(`Unexpected args: ${command} ${joined}`);
535 }),
536 ),
537 );
538 const runtimeServices = yield* Layer.build(
539 Layer.mergeAll(
540 Layer.succeed(ServerSettingsService, serverSettings),
541 providerRegistryLayer,
542 ),
543 ).pipe(Scope.provide(scope));
544​
545 yield* Effect.gen(function* () {
546 const registry = yield* ProviderRegistry;
547 const providers = yield* registry.getProviders;
548 const cursorProvider = providers.find((provider) => provider.provider === "cursor");
549​
550 assert.deepStrictEqual(
551 providers.map((provider) => provider.provider),
552 ["codex", "claudeAgent", "opencode", "cursor"],
553 );
554 assert.strictEqual(cursorProvider?.enabled, false);
555 assert.strictEqual(cursorProvider?.status, "disabled");
556 assert.strictEqual(
557 cursorProvider?.message,
558 "Cursor is disabled in T3 Code settings.",
559 );
560 assert.strictEqual(cursorSpawned, false);
561 }).pipe(Effect.provide(runtimeServices));
562 }),
563 );
564​
565 it.effect("skips codex probes entirely when the provider is disabled", () =>
566 Effect.gen(function* () {
567 const serverSettingsLayer = ServerSettingsService.layerTest({
568 providers: {
569 codex: {
570 enabled: false,
571 },
572 },
573 });
574​
575 const status = yield* checkCodexProviderStatus().pipe(
576 Effect.provide(
577 Layer.mergeAll(serverSettingsLayer, failingSpawnerLayer("spawn codex ENOENT")),
578 ),
579 );
580 assert.strictEqual(status.provider, "codex");
581 assert.strictEqual(status.enabled, false);
582 assert.strictEqual(status.status, "disabled");
583 assert.strictEqual(status.installed, false);
584 assert.strictEqual(status.message, "Codex is disabled in T3 Code settings.");
585 }),
586 );
587 });
588​
589 // ── checkClaudeProviderStatus tests ──────────────────────────
590​
591 describe("checkClaudeProviderStatus", () => {
592 it.effect("returns ready when claude is installed and authenticated", () =>
593 Effect.gen(function* () {
594 const status = yield* checkClaudeProviderStatus();
595 assert.strictEqual(status.provider, "claudeAgent");
596 assert.strictEqual(status.status, "ready");
597 assert.strictEqual(status.installed, true);
598 assert.strictEqual(status.auth.status, "authenticated");
599 }).pipe(
600 Effect.provide(
601 mockSpawnerLayer((args) => {
602 const joined = args.join(" ");
603 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
604 if (joined === "auth status")
605 return {
606 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
607 stderr: "",
608 code: 0,
609 };
610 throw new Error(`Unexpected args: ${joined}`);
611 }),
612 ),
613 ),
614 );
615​
616 it.effect(
617 "includes Claude Opus 4.7 with xhigh as the default effort on supported versions",
618 () =>
619 Effect.gen(function* () {
620 const status = yield* checkClaudeProviderStatus();
621 const opus47 = status.models.find((model) => model.slug === "claude-opus-4-7");
622 if (!opus47) {
623 assert.fail("Expected Claude Opus 4.7 to be present for Claude Code v2.1.111.");
624 }
625 if (!opus47.capabilities) {
626 assert.fail(
627 "Expected Claude Opus 4.7 capabilities to be present for Claude Code v2.1.111.",
628 );
629 }
630 const effortDescriptor = opus47.capabilities.optionDescriptors?.find(
631 (descriptor) => descriptor.type === "select" && descriptor.id === "effort",
632 );
633 assert.deepStrictEqual(
634 effortDescriptor?.type === "select"
635 ? effortDescriptor.options.find((option) => option.isDefault)
636 : undefined,
637 { id: "xhigh", label: "Extra High", isDefault: true },
638 );
639 }).pipe(
640 Effect.provide(
641 mockSpawnerLayer((args) => {
642 const joined = args.join(" ");
643 if (joined === "--version") return { stdout: "2.1.111\n", stderr: "", code: 0 };
644 if (joined === "auth status")
645 return {
646 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
647 stderr: "",
648 code: 0,
649 };
650 throw new Error(`Unexpected args: ${joined}`);
651 }),
652 ),
653 ),
654 );
655​
656 it.effect("hides Claude Opus 4.7 on older Claude Code versions", () =>
657 Effect.gen(function* () {
658 const status = yield* checkClaudeProviderStatus();
659 assert.strictEqual(
660 status.models.some((model) => model.slug === "claude-opus-4-7"),
661 false,
662 );
663 assert.strictEqual(
664 status.message,
665 "Claude Code v2.1.110 is too old for Claude Opus 4.7. Upgrade to v2.1.111 or newer to access it.",
666 );
667 }).pipe(
668 Effect.provide(
669 mockSpawnerLayer((args) => {
670 const joined = args.join(" ");
671 if (joined === "--version") return { stdout: "2.1.110\n", stderr: "", code: 0 };
672 if (joined === "auth status")
673 return {
674 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
675 stderr: "",
676 code: 0,
677 };
678 throw new Error(`Unexpected args: ${joined}`);
679 }),
680 ),
681 ),
682 );
683​
684 it.effect("returns a display label for claude subscription types", () =>
685 Effect.gen(function* () {
686 const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
687 assert.strictEqual(status.provider, "claudeAgent");
688 assert.strictEqual(status.status, "ready");
689 assert.strictEqual(status.auth.status, "authenticated");
690 assert.strictEqual(status.auth.type, "maxplan");
691 assert.strictEqual(status.auth.label, "Claude Max Subscription");
692 }).pipe(
693 Effect.provide(
694 mockSpawnerLayer((args) => {
695 const joined = args.join(" ");
696 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
697 if (joined === "auth status")
698 return {
699 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
700 stderr: "",
701 code: 0,
702 };
703 throw new Error(`Unexpected args: ${joined}`);
704 }),
705 ),
706 ),
707 );
708​
709 it.effect("includes probed claude slash commands in the provider snapshot", () =>
710 Effect.gen(function* () {
711 const status = yield* checkClaudeProviderStatus(
712 () => Effect.succeed("maxplan"),
713 () =>
714 Effect.succeed([
715 {
716 name: "review",
717 description: "Review a pull request",
718 input: { hint: "pr-or-branch" },
719 },
720 ]),
721 );
722​
723 assert.deepStrictEqual(status.slashCommands, [
724 {
725 name: "review",
726 description: "Review a pull request",
727 input: { hint: "pr-or-branch" },
728 },
729 ]);
730 }).pipe(
731 Effect.provide(
732 mockSpawnerLayer((args) => {
733 const joined = args.join(" ");
734 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
735 if (joined === "auth status")
736 return {
737 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
738 stderr: "",
739 code: 0,
740 };
741 throw new Error(`Unexpected args: ${joined}`);
742 }),
743 ),
744 ),
745 );
746​
747 it.effect("deduplicates probed claude slash commands by name", () =>
748 Effect.gen(function* () {
749 const status = yield* checkClaudeProviderStatus(
750 () => Effect.succeed("maxplan"),
751 () =>
752 Effect.succeed([
753 {
754 name: "ui",
755 description: "Explore and refine UI",
756 },
757 {
758 name: "ui",
759 input: { hint: "component-or-screen" },
760 },
761 ]),
762 );
763​
764 assert.deepStrictEqual(status.slashCommands, [
765 {
766 name: "ui",
767 description: "Explore and refine UI",
768 input: { hint: "component-or-screen" },
769 },
770 ]);
771 }).pipe(
772 Effect.provide(
773 mockSpawnerLayer((args) => {
774 const joined = args.join(" ");
775 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
776 if (joined === "auth status")
777 return {
778 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
779 stderr: "",
780 code: 0,
781 };
782 throw new Error(`Unexpected args: ${joined}`);
783 }),
784 ),
785 ),
786 );
787​
788 it.effect("returns an api key label for claude api key auth", () =>
789 Effect.gen(function* () {
790 const status = yield* checkClaudeProviderStatus();
791 assert.strictEqual(status.provider, "claudeAgent");
792 assert.strictEqual(status.status, "ready");
793 assert.strictEqual(status.auth.status, "authenticated");
794 assert.strictEqual(status.auth.type, "apiKey");
795 assert.strictEqual(status.auth.label, "Claude API Key");
796 }).pipe(
797 Effect.provide(
798 mockSpawnerLayer((args) => {
799 const joined = args.join(" ");
800 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
801 if (joined === "auth status")
802 return {
803 stdout: '{"loggedIn":true,"authMethod":"api-key"}\n',
804 stderr: "",
805 code: 0,
806 };
807 throw new Error(`Unexpected args: ${joined}`);
808 }),
809 ),
810 ),
811 );
812​
813 it.effect("returns unavailable when claude is missing", () =>
814 Effect.gen(function* () {
815 const status = yield* checkClaudeProviderStatus();
816 assert.strictEqual(status.provider, "claudeAgent");
817 assert.strictEqual(status.status, "error");
818 assert.strictEqual(status.installed, false);
819 assert.strictEqual(status.auth.status, "unknown");
820 assert.strictEqual(
821 status.message,
822 "Claude Agent CLI (`claude`) is not installed or not on PATH.",
823 );
824 }).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
825 );
826​
827 it.effect("returns error when version check fails with non-zero exit code", () =>
828 Effect.gen(function* () {
829 const status = yield* checkClaudeProviderStatus();
830 assert.strictEqual(status.provider, "claudeAgent");
831 assert.strictEqual(status.status, "error");
832 assert.strictEqual(status.installed, true);
833 }).pipe(
834 Effect.provide(
835 mockSpawnerLayer((args) => {
836 const joined = args.join(" ");
837 if (joined === "--version")
838 return { stdout: "", stderr: "Something went wrong", code: 1 };
839 throw new Error(`Unexpected args: ${joined}`);
840 }),
841 ),
842 ),
843 );
844​
845 it.effect("returns unauthenticated when auth status reports not logged in", () =>
846 Effect.gen(function* () {
847 const status = yield* checkClaudeProviderStatus();
848 assert.strictEqual(status.provider, "claudeAgent");
849 assert.strictEqual(status.status, "error");
850 assert.strictEqual(status.installed, true);
851 assert.strictEqual(status.auth.status, "unauthenticated");
852 assert.strictEqual(
853 status.message,
854 "Claude is not authenticated. Run `claude auth login` and try again.",
855 );
856 }).pipe(
857 Effect.provide(
858 mockSpawnerLayer((args) => {
859 const joined = args.join(" ");
860 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
861 if (joined === "auth status")
862 return {
863 stdout: '{"loggedIn":false}\n',
864 stderr: "",
865 code: 1,
866 };
867 throw new Error(`Unexpected args: ${joined}`);
868 }),
869 ),
870 ),
871 );
872​
873 it.effect("returns unauthenticated when output includes 'not logged in'", () =>
874 Effect.gen(function* () {
875 const status = yield* checkClaudeProviderStatus();
876 assert.strictEqual(status.provider, "claudeAgent");
877 assert.strictEqual(status.status, "error");
878 assert.strictEqual(status.installed, true);
879 assert.strictEqual(status.auth.status, "unauthenticated");
880 }).pipe(
881 Effect.provide(
882 mockSpawnerLayer((args) => {
883 const joined = args.join(" ");
884 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
885 if (joined === "auth status")
886 return { stdout: "Not logged in\n", stderr: "", code: 1 };
887 throw new Error(`Unexpected args: ${joined}`);
888 }),
889 ),
890 ),
891 );
892​
893 it.effect("returns warning when auth status command is unsupported", () =>
894 Effect.gen(function* () {
895 const status = yield* checkClaudeProviderStatus();
896 assert.strictEqual(status.provider, "claudeAgent");
897 assert.strictEqual(status.status, "warning");
898 assert.strictEqual(status.installed, true);
899 assert.strictEqual(status.auth.status, "unknown");
900 assert.strictEqual(
901 status.message,
902 "Claude Agent authentication status command is unavailable in this version of Claude.",
903 );
904 }).pipe(
905 Effect.provide(
906 mockSpawnerLayer((args) => {
907 const joined = args.join(" ");
908 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
909 if (joined === "auth status")
910 return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
911 throw new Error(`Unexpected args: ${joined}`);
912 }),
913 ),
914 ),
915 );
916 });
917​
918 // ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
919​
920 describe("parseClaudeAuthStatusFromOutput", () => {
921 it("exit code 0 with no auth markers is ready", () => {
922 const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
923 assert.strictEqual(parsed.status, "ready");
924 assert.strictEqual(parsed.auth.status, "authenticated");
925 });
926​
927 it("JSON with loggedIn=true is authenticated", () => {
928 const parsed = parseClaudeAuthStatusFromOutput({
929 stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
930 stderr: "",
931 code: 0,
932 });
933 assert.strictEqual(parsed.status, "ready");
934 assert.strictEqual(parsed.auth.status, "authenticated");
935 });
936​
937 it("JSON with loggedIn=false is unauthenticated", () => {
938 const parsed = parseClaudeAuthStatusFromOutput({
939 stdout: '{"loggedIn":false}\n',
940 stderr: "",
941 code: 0,
942 });
943 assert.strictEqual(parsed.status, "error");
944 assert.strictEqual(parsed.auth.status, "unauthenticated");
945 });
946​
947 it("JSON without auth marker is warning", () => {
948 const parsed = parseClaudeAuthStatusFromOutput({
949 stdout: '{"ok":true}\n',
950 stderr: "",
951 code: 0,
952 });
953 assert.strictEqual(parsed.status, "warning");
954 assert.strictEqual(parsed.auth.status, "unknown");
955 });
956 });
957 },
958);