Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - cleanup uses Node's retrying rm, which the FileSystem service does not expose.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { ClaudeSettings, type ServerProvider } from "@t3tools/contracts";
4import { vi } from "vite-plus/test";
5import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
6import { assert, it } from "@effect/vitest";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12import * as Schema from "effect/Schema";
13import * as TestClock from "effect/testing/TestClock";
14
15import {
16 buildClaudeCapabilitiesProbeQueryOptions,
17 probeClaudeCapabilities,
18 probeClaudeWorkspaceSnapshot,
19 spawnClaudeProbeThroughLauncher,
20} from "./ClaudeProvider.ts";
21import * as LaunchedChild from "../process/launchedChild.ts";
22import * as NonBlockingSpawner from "../process/NonBlockingSpawner.ts";
23
24vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
25
26const hostPath = process.env.PATH;
27
28const decodeClaudeSettings = Schema.decodeEffect(ClaudeSettings);
29
30it("drops strict MCP mode, and only that, next to an administrator's managed-mcp.json", () => {
31 const options = buildClaudeCapabilitiesProbeQueryOptions({
32 executablePath: "/usr/bin/claude",
33 abortController: new AbortController(),
34 environment: { HOME: "/home/user" },
35 cwd: undefined,
36 managedMcpConfig: true,
37 spawnVia: undefined,
38 });
39
40 // Claude exits before initializing when handed --strict-mcp-config here.
41 assert.equal(options.strictMcpConfig, undefined);
42 assert.deepEqual(options.mcpServers, {});
43 assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false");
44});
45
46// A shell trampoline would not do: dash drops the exported function, and the launcher exits 127.
47it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
48 "starts a Bash launcher that calls an exported function in the probe's workspace",
49 () =>
50 Effect.gen(function* () {
51 const fileSystem = yield* FileSystem.FileSystem;
52 const workspace = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped());
53 yield* fileSystem.writeFileString(`${workspace}/claude`, '#!/bin/bash\nt3_launch "$@"\n');
54 yield* fileSystem.chmod(`${workspace}/claude`, 0o755);
55 const launch = LaunchedChild.makeLaunch(yield* ChildProcessSpawner.ChildProcessSpawner);
56 const child = spawnClaudeProbeThroughLauncher(launch)({
57 command: "claude",
58 args: ["--probe"],
59 cwd: workspace,
60 env: { PATH: `.:${hostPath}`, "BASH_FUNC_t3_launch%%": '() { echo "$PWD $@"; }' },
61 // @effect-diagnostics-next-line abortControllerInEffect:off - The launcher exits on its own.
62 signal: new AbortController().signal,
63 });
64 const output = yield* Effect.promise(() => child.stdout.setEncoding("utf8").toArray());
65 assert.equal(output.join(""), `${workspace} --probe\n`);
66 }).pipe(
67 Effect.scoped,
68 Effect.provide(NonBlockingSpawner.layer.pipe(Layer.provideMerge(NodeServices.layer))),
69 ),
70);
71
72it.effect("reports a deleted worktree's scan as finished, not pending", () =>
73 Effect.gen(function* () {
74 const snapshot = yield* probeClaudeWorkspaceSnapshot(
75 yield* decodeClaudeSettings({}),
76 { skills: [], slashCommands: [{ name: "code-review" }] } as unknown as ServerProvider,
77 "/nonexistent/t3-deleted-worktree",
78 { HOME: "/nonexistent/t3-home" },
79 );
80 assert.strictEqual(snapshot.slashCommandsPending, false);
81 // Nothing will ever rescan this cwd, so the machine's commands are all it gets.
82 assert.deepEqual(
83 snapshot.slashCommands.map((command) => command.name),
84 ["compact", "code-review"],
85 );
86 }).pipe(Effect.provide(NodeServices.layer)),
87);
88
89it.effect("keeps the machine's slash commands while a workspace probe fails", () =>
90 Effect.gen(function* () {
91 const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(
92 () =>
93 ({
94 initializationResult: () => Promise.reject(new Error("probe timed out")),
95 }) as unknown as ReturnType<typeof ClaudeSdk.query>,
96 );
97 yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
98 const fileSystem = yield* FileSystem.FileSystem;
99 const workspace = yield* fileSystem.makeTempDirectoryScoped();
100 const snapshot = yield* probeClaudeWorkspaceSnapshot(
101 yield* decodeClaudeSettings({ binaryPath: "claude" }),
102 {
103 skills: [],
104 slashCommands: [{ name: "compact" }, { name: "code-review" }],
105 } as unknown as ServerProvider,
106 workspace,
107 { PATH: hostPath, HOME: workspace },
108 );
109 assert.deepEqual(
110 snapshot.slashCommands.map((command) => command.name),
111 ["compact", "code-review"],
112 );
113 assert.strictEqual(snapshot.slashCommandsPending, true);
114 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
115);
116
117it.effect("keeps the probe subprocess alive while gateway model discovery can finish", () =>
118 Effect.gen(function* () {
119 let abortSignal: AbortSignal | undefined;
120 const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
121 abortSignal = options?.abortController?.signal;
122 return {
123 initializationResult: async () => ({
124 account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" },
125 commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],
126 models: [{ value: "gateway/claude-relay", displayName: "Relay", description: "" }],
127 }),
128 usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: () =>
129 new Promise((_, reject) => reject(new Error("usage unavailable"))),
130 } as ReturnType<typeof ClaudeSdk.query>;
131 });
132 yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
133 const fileSystem = yield* FileSystem.FileSystem;
134 const configDir = yield* fileSystem.makeTempDirectoryScoped();
135 // Claude Code also reads these from settings.json, which is where gateway users set them.
136 yield* fileSystem.writeFileString(
137 `${configDir}/settings.json`,
138 JSON.stringify({
139 env: {
140 ANTHROPIC_BASE_URL: "https://gateway.example",
141 CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: "1",
142 },
143 }),
144 );
145 const capabilities = yield* probeClaudeCapabilities(
146 yield* decodeClaudeSettings({ binaryPath: "claude" }),
147 { PATH: (yield* HostProcess.Environment).PATH, CLAUDE_CONFIG_DIR: configDir },
148 );
149 assert.deepEqual(
150 capabilities.models?.map((model) => model.value),
151 ["gateway/claude-relay"],
152 );
153 assert.equal(abortSignal?.aborted, false);
154 yield* TestClock.adjust("3 seconds");
155 assert.equal(abortSignal?.aborted, true);
156 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
157);