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 ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
3import { vi } from "vite-plus/test";
4import * as Deferred from "effect/Deferred";
5import * as Fiber from "effect/Fiber";
6import * as TestClock from "effect/testing/TestClock";
7import {
8 ClaudeSettings,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 type ServerProvider,
12} from "@t3tools/contracts";
13import * as NodeFSP from "node:fs/promises";
14import * as NodeServices from "@effect/platform-node/NodeServices";
15import { assert, it } from "@effect/vitest";
16import * as Cause from "effect/Cause";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Path from "effect/Path";
20import * as Schema from "effect/Schema";
21import * as Result from "effect/Result";
22
23import {
24 buildClaudeCapabilitiesProbeQueryOptions,
25 CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES,
26 probeClaudeCapabilities,
27 probeClaudeWorkspaceSnapshot,
28} from "./ClaudeProvider.ts";
29import { COMPACT_SLASH_COMMAND } from "@t3tools/provider-core/server/snapshotProbe";
30
31vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
32
33const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
34
35it("isolates Claude capability probes without dropping workspace setting sources", () => {
36 const abortController = new AbortController();
37 const options = buildClaudeCapabilitiesProbeQueryOptions({
38 executablePath: "/usr/bin/claude",
39 abortController,
40 environment: {
41 HOME: "/home/user",
42 ENABLE_CLAUDEAI_MCP_SERVERS: "true",
43 FORCE_CODE_TERMINAL: "1",
44 },
45 cwd: "/workspace/project",
46 managedMcpConfig: false,
47 });
48
49 assert.deepEqual(options.mcpServers, {});
50 assert.equal(options.strictMcpConfig, true);
51 assert.equal(options.cwd, "/workspace/project");
52 assert.deepEqual(options.settingSources, [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES]);
53 assert.deepEqual(options.settings, { disableAllHooks: true });
54 assert.deepEqual(options.allowedTools, []);
55 assert.equal(options.persistSession, false);
56 assert.equal(options.pathToClaudeCodeExecutable, "/usr/bin/claude");
57 assert.equal(options.abortController, abortController);
58 assert.equal(options.env?.HOME, "/home/user");
59 assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false");
60 assert.equal(options.env?.FORCE_CODE_TERMINAL, undefined);
61 assert.equal(options.env?.CLAUDE_CODE_AUTO_CONNECT_IDE, "0");
62 assert.equal(options.env?.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL, "1");
63});
64
65it("drops strict MCP mode, and only that, next to an administrator's managed-mcp.json", () => {
66 const options = buildClaudeCapabilitiesProbeQueryOptions({
67 executablePath: "/usr/bin/claude",
68 abortController: new AbortController(),
69 environment: { HOME: "/home/user" },
70 cwd: undefined,
71 managedMcpConfig: true,
72 });
73
74 // Claude exits before initializing when handed --strict-mcp-config here.
75 assert.equal(options.strictMcpConfig, undefined);
76 assert.deepEqual(options.mcpServers, {});
77 assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false");
78});
79
80it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
81 it.effect(
82 "discovers commands and skills separately for each cwd without replacing machine metadata",
83 () =>
84 Effect.gen(function* () {
85 const fs = yield* FileSystem.FileSystem;
86 const path = yield* Path.Path;
87 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-workspaces-" });
88 const configDir = path.join(tempDir, "claude-home");
89 const workspaces = [path.join(tempDir, "one"), path.join(tempDir, "two")];
90 for (const cwd of workspaces) {
91 const skillDir = path.join(cwd, ".claude", "skills", "existing-skill");
92 yield* fs.makeDirectory(skillDir, { recursive: true });
93 yield* fs.writeFileString(
94 path.join(skillDir, "SKILL.md"),
95 "---\nname: existing-skill\ndescription: Existing project skill\n---\nUse this skill.",
96 );
97 }
98 const machineSnapshot = {
99 instanceId: ProviderInstanceId.make("claude"),
100 driver: ProviderDriverKind.make("claudeAgent"),
101 enabled: true,
102 installed: true,
103 status: "ready",
104 auth: { status: "authenticated", email: "machine@example.com" },
105 checkedAt: "2026-03-25T00:00:00.000Z",
106 version: "2.1.288",
107 models: [],
108 slashCommands: [{ name: "server-cwd-only" }],
109 skills: [],
110 } satisfies ServerProvider;
111 let usageCalls = 0;
112 const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
113 assert.equal(options?.env?.CLAUDE_CONFIG_DIR, configDir);
114 assert.equal(options?.env?.T3_WORKSPACE_PROBE, "owned-instance");
115 return {
116 initializationResult: async () => ({
117 account: { email: "workspace@example.com" },
118 commands: [
119 {
120 name: options?.cwd === workspaces[0] ? "start-session" : "other-project",
121 description: "Project command",
122 argumentHint: "[topic]",
123 },
124 { name: "nested:review", description: "Review changes", argumentHint: "" },
125 { name: "NESTED:review", description: "", argumentHint: "[path]" },
126 { name: "compact", description: "Provider compact", argumentHint: "" },
127 { name: "user-command", description: "Existing user command", argumentHint: "" },
128 ],
129 }),
130 usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => {
131 usageCalls++;
132 return { rate_limits_available: false, rate_limits: null };
133 },
134 } as ReturnType<typeof ClaudeSdk.query>;
135 });
136 yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
137 for (const [index, cwd] of workspaces.entries()) {
138 const scoped = yield* probeClaudeWorkspaceSnapshot(
139 decodeClaudeSettings({ homePath: configDir }),
140 machineSnapshot,
141 cwd,
142 { ...process.env, T3_WORKSPACE_PROBE: "owned-instance" },
143 );
144 assert.deepEqual(scoped, {
145 ...machineSnapshot,
146 slashCommandsPending: false,
147 slashCommands: [
148 COMPACT_SLASH_COMMAND,
149 {
150 name: index === 0 ? "start-session" : "other-project",
151 description: "Project command",
152 input: { hint: "[topic]" },
153 },
154 { name: "nested:review", description: "Review changes", input: { hint: "[path]" } },
155 { name: "user-command", description: "Existing user command" },
156 ],
157 skills: [
158 {
159 name: "existing-skill",
160 path: path.join(cwd, ".claude", "skills", "existing-skill", "SKILL.md"),
161 enabled: true,
162 scope: "project",
163 description: "Existing project skill",
164 },
165 ],
166 });
167 }
168 assert.deepEqual(
169 query.mock.calls.map(([input]) => input.options?.cwd),
170 workspaces,
171 );
172 assert.equal(usageCalls, 0);
173 }).pipe(Effect.scoped),
174 );
175
176 it.effect("keeps readable skills during failed command discovery and recovers on retry", () =>
177 Effect.gen(function* () {
178 const fs = yield* FileSystem.FileSystem;
179 const path = yield* Path.Path;
180 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-workspace-retry-" });
181 const skillDir = path.join(cwd, ".claude", "skills", "existing-skill");
182 yield* fs.makeDirectory(skillDir, { recursive: true });
183 yield* fs.writeFileString(
184 path.join(skillDir, "SKILL.md"),
185 "---\nname: existing-skill\ndescription: Existing project skill\n---\nUse this skill.",
186 );
187 const machineSnapshot = {
188 instanceId: ProviderInstanceId.make("claude"),
189 driver: ProviderDriverKind.make("claudeAgent"),
190 enabled: true,
191 installed: true,
192 status: "ready",
193 auth: { status: "authenticated" },
194 checkedAt: "2026-03-25T00:00:00.000Z",
195 version: "2.1.288",
196 models: [],
197 slashCommands: [{ name: "server-cwd-only" }],
198 skills: [],
199 } satisfies ServerProvider;
200 const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(
201 () =>
202 ({
203 initializationResult: () =>
204 Promise.reject<ClaudeSdk.SDKControlInitializeResponse>(
205 new Error("Initialization failed"),
206 ),
207 usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({
208 rate_limits_available: false,
209 rate_limits: null,
210 }),
211 }) as ReturnType<typeof ClaudeSdk.query>,
212 );
213 yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
214 const settings = decodeClaudeSettings({ homePath: cwd });
215 const failed = yield* probeClaudeWorkspaceSnapshot(settings, machineSnapshot, cwd);
216 assert.deepEqual(failed, {
217 ...machineSnapshot,
218 slashCommands: [COMPACT_SLASH_COMMAND],
219 slashCommandsPending: true,
220 skills: [
221 {
222 name: "existing-skill",
223 path: path.join(skillDir, "SKILL.md"),
224 enabled: true,
225 scope: "project",
226 description: "Existing project skill",
227 },
228 ],
229 });
230 query.mockImplementation(
231 () =>
232 ({
233 initializationResult: async () => ({
234 commands: [{ name: "recovered", description: "", argumentHint: "" }],
235 }),
236 usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({
237 rate_limits_available: false,
238 rate_limits: null,
239 }),
240 }) as ReturnType<typeof ClaudeSdk.query>,
241 );
242 const recovered = yield* probeClaudeWorkspaceSnapshot(settings, machineSnapshot, cwd);
243 assert.deepEqual(recovered.slashCommands, [COMPACT_SLASH_COMMAND, { name: "recovered" }]);
244 assert.equal(recovered.status, "ready");
245 assert.equal(recovered.slashCommandsPending, false);
246 assert.deepEqual(recovered.skills, failed.skills);
247 const disabled = yield* probeClaudeWorkspaceSnapshot(
248 { ...settings, enabled: false },
249 machineSnapshot,
250 cwd,
251 );
252 assert.equal(disabled, machineSnapshot);
253 assert.equal(query.mock.calls.length, 2);
254 }).pipe(Effect.scoped),
255 );
256
257 it.effect("serializes strict no-MCP options and still resolves account capabilities", () =>
258 Effect.gen(function* () {
259 const fs = yield* FileSystem.FileSystem;
260 const path = yield* Path.Path;
261 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-probe-sdk-" });
262 const executablePath = yield* path.fromFileUrl(
263 new URL("./testing/ClaudeCapabilitiesProbe.fixture.mjs", import.meta.url),
264 );
265 const invocationPath = path.join(tempDir, "invocation.json");
266 // The probe aborts the SDK without awaiting the child's exit, and on
267 // Windows a directory that is still some process's cwd cannot be
268 // removed. Keep the workspace outside the scoped directory and let it
269 // go with a retrying removal once the child has gone.
270 const workspaceCwd = yield* fs.makeTempDirectory({ prefix: "t3-claude-probe-cwd-" });
271 // Node's own retry rather than an Effect schedule: it.effect runs on a
272 // TestClock, so a scheduled retry would wait for time nobody advances.
273 yield* Effect.addFinalizer(() =>
274 Effect.promise(() =>
275 NodeFSP.rm(workspaceCwd, {
276 recursive: true,
277 force: true,
278 maxRetries: 20,
279 retryDelay: 250,
280 }).catch(() => undefined),
281 ),
282 );
283
284 const capabilities = yield* probeClaudeCapabilities(
285 decodeClaudeSettings({ binaryPath: executablePath }),
286 {
287 ...process.env,
288 T3_PROBE_INVOCATION_PATH: invocationPath,
289 ENABLE_CLAUDEAI_MCP_SERVERS: "true",
290 },
291 workspaceCwd,
292 );
293
294 assert.deepEqual(capabilities, {
295 email: "dev@example.com",
296 subscriptionType: "pro",
297 tokenSource: "oauth",
298 apiKeySource: undefined,
299 apiProvider: undefined,
300 slashCommands: [
301 {
302 name: "review",
303 description: "Review changes",
304 input: { hint: "[path]" },
305 },
306 ],
307 usage: {
308 rate_limits_available: true,
309 rate_limits: { five_hour: { utilization: 12, resets_at: "2026-07-18T14:39:00Z" } },
310 },
311 usageCheckedAt: "1970-01-01T00:00:00.000Z",
312 });
313
314 const invocation = JSON.parse(yield* fs.readFileString(invocationPath)) as {
315 readonly args: ReadonlyArray<string>;
316 readonly cwd: string;
317 readonly connectorEnv: string;
318 readonly mcpConfig: unknown;
319 };
320 assert.equal(invocation.cwd, yield* fs.realPath(workspaceCwd));
321 assert.equal(invocation.connectorEnv, "false");
322 assert.equal(invocation.args.includes("--strict-mcp-config"), true);
323 assert.equal(invocation.args.includes("--mcp-config"), false);
324 assert.equal(invocation.mcpConfig, undefined);
325
326 assert.equal(invocation.args.includes("--setting-sources=user,project,local"), true);
327
328 const settingsFlagIndex = invocation.args.indexOf("--settings");
329 assert.notEqual(settingsFlagIndex, -1);
330 const flagSettings = JSON.parse(invocation.args[settingsFlagIndex + 1] ?? "{}") as {
331 readonly disableAllHooks?: boolean;
332 };
333 assert.equal(flagSettings.disableAllHooks, true);
334 }).pipe(Effect.scoped),
335 );
336});
337
338it.effect("preserves initialized capabilities when optional usage times out", () =>
339 Effect.gen(function* () {
340 const usageStarted = yield* Deferred.make<void>();
341 let abortSignal: AbortSignal | undefined;
342 const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
343 abortSignal = options?.abortController?.signal;
344 return {
345 initializationResult: async () => ({
346 account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" },
347 commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],
348 }),
349 usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: () => {
350 Deferred.doneUnsafe(usageStarted, Effect.void);
351 return new Promise(() => {});
352 },
353 } as ReturnType<typeof ClaudeSdk.query>;
354 });
355 yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
356 const probe = yield* probeClaudeCapabilities(
357 decodeClaudeSettings({ binaryPath: "claude" }),
358 ).pipe(Effect.forkChild);
359 yield* Deferred.await(usageStarted);
360 yield* TestClock.adjust("4 seconds");
361 const capabilities = yield* Fiber.join(probe);
362 assert.equal(capabilities?.email, "dev@example.com");
363 assert.equal(capabilities?.subscriptionType, "pro");
364 assert.equal(capabilities?.tokenSource, "oauth");
365 assert.deepEqual(capabilities?.slashCommands, [
366 { name: "review", description: "Review changes", input: { hint: "[path]" } },
367 ]);
368 assert.equal(capabilities?.usage, undefined);
369 assert.equal(abortSignal?.aborted, true);
370 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
371);
372
373it.effect("fails a hung initialization probe with a timeout", () =>
374 Effect.gen(function* () {
375 const initializationStarted = yield* Deferred.make<void>();
376 const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(
377 () =>
378 ({
379 initializationResult: () => {
380 Deferred.doneUnsafe(initializationStarted, Effect.void);
381 return new Promise(() => {});
382 },
383 usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({
384 rate_limits_available: true,
385 rate_limits: {},
386 }),
387 }) as ReturnType<typeof ClaudeSdk.query>,
388 );
389 yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
390 const probe = yield* probeClaudeCapabilities(
391 decodeClaudeSettings({ binaryPath: "claude" }),
392 ).pipe(Effect.result, Effect.forkChild);
393
394 yield* Deferred.await(initializationStarted);
395 yield* TestClock.adjust("25 seconds");
396 const result = yield* Fiber.join(probe);
397
398 assert.isTrue(Result.isFailure(result));
399 if (Result.isFailure(result)) assert.isTrue(Cause.isTimeoutError(result.failure));
400 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
401);
402
403it.effect("asks for usage without the local transcript scan", () =>
404 Effect.gen(function* () {
405 let usageOptions: unknown;
406 const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(
407 () =>
408 ({
409 initializationResult: async () => ({
410 account: { email: "dev@example.com", subscriptionType: "max", tokenSource: "oauth" },
411 commands: [],
412 }),
413 usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async (options?: unknown) => {
414 usageOptions = options;
415 return { rate_limits_available: true, rate_limits: null };
416 },
417 }) as unknown as ReturnType<typeof ClaudeSdk.query>,
418 );
419 yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
420 yield* probeClaudeCapabilities(decodeClaudeSettings({ binaryPath: "claude" }));
421 assert.deepEqual(usageOptions, { skipBehaviors: true });
422 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
423);