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

ClaudeCapabilitiesProbe.test.ts

375 lines15.6 KB

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