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

ClaudeCapabilitiesProbe.test.ts

225 lines9.7 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 { ClaudeSettings } from "@t3tools/contracts";
8import * as NodeFSP from "node:fs/promises";
9import * as NodeServices from "@effect/platform-node/NodeServices";
10import { assert, it } from "@effect/vitest";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Path from "effect/Path";
14import * as Schema from "effect/Schema";
15​
16import {
17 buildClaudeCapabilitiesProbeQueryOptions,
18 CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES,
19 probeClaudeCapabilities,
20} from "./ClaudeProvider.ts";
21​
22vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
23​
24const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
25​
26it("isolates Claude capability probes without dropping workspace setting sources", () => {
27 const abortController = new AbortController();
28 const options = buildClaudeCapabilitiesProbeQueryOptions({
29 executablePath: "/usr/bin/claude",
30 abortController,
31 environment: {
32 HOME: "/home/user",
33 ENABLE_CLAUDEAI_MCP_SERVERS: "true",
34 FORCE_CODE_TERMINAL: "1",
35 },
36 cwd: "/workspace/project",
37 });
38​
39 assert.deepEqual(options.mcpServers, {});
40 assert.equal(options.strictMcpConfig, true);
41 assert.equal(options.cwd, "/workspace/project");
42 assert.deepEqual(options.settingSources, [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES]);
43 assert.deepEqual(options.settings, { disableAllHooks: true });
44 assert.deepEqual(options.allowedTools, []);
45 assert.equal(options.persistSession, false);
46 assert.equal(options.pathToClaudeCodeExecutable, "/usr/bin/claude");
47 assert.equal(options.abortController, abortController);
48 assert.equal(options.env?.HOME, "/home/user");
49 assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false");
50 assert.equal(options.env?.FORCE_CODE_TERMINAL, undefined);
51 assert.equal(options.env?.CLAUDE_CODE_AUTO_CONNECT_IDE, "0");
52 assert.equal(options.env?.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL, "1");
53});
54​
55it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => {
56 it.effect("serializes strict no-MCP options and still resolves account capabilities", () =>
57 Effect.gen(function* () {
58 const fs = yield* FileSystem.FileSystem;
59 const path = yield* Path.Path;
60 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-probe-sdk-" });
61 const executablePath = path.join(tempDir, "fake-claude.mjs");
62 const invocationPath = path.join(tempDir, "invocation.json");
63 // The probe aborts the SDK without awaiting the child's exit, and on
64 // Windows a directory that is still some process's cwd cannot be
65 // removed. Keep the workspace outside the scoped directory and let it
66 // go with a retrying removal once the child has gone.
67 const workspaceCwd = yield* fs.makeTempDirectory({ prefix: "t3-claude-probe-cwd-" });
68 // Node's own retry rather than an Effect schedule: it.effect runs on a
69 // TestClock, so a scheduled retry would wait for time nobody advances.
70 // If the child still holds the directory after that, an empty temp
71 // directory is left behind rather than failing the test for it.
72 yield* Effect.addFinalizer(() =>
73 Effect.promise(() =>
74 NodeFSP.rm(workspaceCwd, {
75 recursive: true,
76 force: true,
77 maxRetries: 20,
78 retryDelay: 250,
79 }).catch(() => undefined),
80 ),
81 );
82​
83 yield* fs.writeFileString(
84 executablePath,
85 [
86 "#!/usr/bin/env node",
87 'import { existsSync, readFileSync, writeFileSync } from "node:fs";',
88 'import { createInterface } from "node:readline";',
89 "const args = process.argv.slice(2);",
90 'const mcpConfigIndex = args.indexOf("--mcp-config");',
91 "const rawMcpConfig = mcpConfigIndex >= 0 ? args[mcpConfigIndex + 1] : undefined;",
92 "let mcpConfig;",
93 "if (rawMcpConfig) {",
94 ' const contents = existsSync(rawMcpConfig) ? readFileSync(rawMcpConfig, "utf8") : rawMcpConfig;',
95 " try { mcpConfig = JSON.parse(contents); } catch { mcpConfig = contents; }",
96 "}",
97 "writeFileSync(process.env.T3_PROBE_INVOCATION_PATH, JSON.stringify({",
98 " args,",
99 " cwd: process.cwd(),",
100 " connectorEnv: process.env.ENABLE_CLAUDEAI_MCP_SERVERS,",
101 " mcpConfig,",
102 "}));",
103 "const lines = createInterface({ input: process.stdin });",
104 'lines.on("line", (line) => {',
105 " const message = JSON.parse(line);",
106 ' if (message.type !== "control_request") return;',
107 " const reply = (response) => process.stdout.write(JSON.stringify({",
108 ' type: "control_response",',
109 ' response: { subtype: "success", request_id: message.request_id, response },',
110 ' }) + "\\n");',
111 ' if (message.request?.subtype === "initialize") {',
112 " reply({",
113 ' commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],',
114 " agents: [],",
115 ' output_style: "default",',
116 ' available_output_styles: ["default"],',
117 " models: [],",
118 ' account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" },',
119 " });",
120 " }",
121 " // The probe follows initialize with get_usage on the same process.",
122 ' if (message.request?.subtype === "get_usage") {',
123 " reply({",
124 " session: {},",
125 ' subscription_type: "pro",',
126 " rate_limits_available: true,",
127 ' rate_limits: { five_hour: { utilization: 12, resets_at: "2026-07-18T14:39:00Z" } },',
128 " behaviors: null,",
129 " });",
130 " }",
131 "});",
132 "setInterval(() => {}, 1_000);",
133 "",
134 ].join("\n"),
135 );
136 yield* fs.chmod(executablePath, 0o755);
137​
138 const capabilities = yield* probeClaudeCapabilities(
139 decodeClaudeSettings({ binaryPath: executablePath }),
140 {
141 ...process.env,
142 T3_PROBE_INVOCATION_PATH: invocationPath,
143 ENABLE_CLAUDEAI_MCP_SERVERS: "true",
144 },
145 workspaceCwd,
146 );
147​
148 assert.deepEqual(capabilities, {
149 email: "dev@example.com",
150 subscriptionType: "pro",
151 tokenSource: "oauth",
152 apiProvider: undefined,
153 slashCommands: [
154 {
155 name: "review",
156 description: "Review changes",
157 input: { hint: "[path]" },
158 },
159 ],
160 usage: {
161 rate_limits_available: true,
162 rate_limits: { five_hour: { utilization: 12, resets_at: "2026-07-18T14:39:00Z" } },
163 },
164 });
165​
166 // @effect-diagnostics-next-line preferSchemaOverJson:off
167 const invocation = JSON.parse(yield* fs.readFileString(invocationPath)) as {
168 readonly args: ReadonlyArray<string>;
169 readonly cwd: string;
170 readonly connectorEnv: string;
171 readonly mcpConfig: unknown;
172 };
173 assert.equal(invocation.cwd, yield* fs.realPath(workspaceCwd));
174 assert.equal(invocation.connectorEnv, "false");
175 assert.equal(invocation.args.includes("--strict-mcp-config"), true);
176 assert.equal(invocation.args.includes("--mcp-config"), false);
177 assert.equal(invocation.mcpConfig, undefined);
178​
179 assert.equal(invocation.args.includes("--setting-sources=user,project,local"), true);
180​
181 const settingsFlagIndex = invocation.args.indexOf("--settings");
182 assert.notEqual(settingsFlagIndex, -1);
183 // @effect-diagnostics-next-line preferSchemaOverJson:off
184 const flagSettings = JSON.parse(invocation.args[settingsFlagIndex + 1] ?? "{}") as {
185 readonly disableAllHooks?: boolean;
186 };
187 assert.equal(flagSettings.disableAllHooks, true);
188 }).pipe(Effect.scoped),
189 );
190});
191​
192it.effect("preserves initialized capabilities when optional usage times out", () =>
193 Effect.gen(function* () {
194 const usageStarted = yield* Deferred.make<void>();
195 let abortSignal: AbortSignal | undefined;
196 const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
197 abortSignal = options?.abortController?.signal;
198 return {
199 initializationResult: async () => ({
200 account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" },
201 commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],
202 }),
203 usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: () => {
204 Deferred.doneUnsafe(usageStarted, Effect.void);
205 return new Promise(() => {});
206 },
207 } as ReturnType<typeof ClaudeSdk.query>;
208 });
209 yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
210 const probe = yield* probeClaudeCapabilities(
211 decodeClaudeSettings({ binaryPath: "claude" }),
212 ).pipe(Effect.forkChild);
213 yield* Deferred.await(usageStarted);
214 yield* TestClock.adjust("4 seconds");
215 const capabilities = yield* Fiber.join(probe);
216 assert.equal(capabilities?.email, "dev@example.com");
217 assert.equal(capabilities?.subscriptionType, "pro");
218 assert.equal(capabilities?.tokenSource, "oauth");
219 assert.deepEqual(capabilities?.slashCommands, [
220 { name: "review", description: "Review changes", input: { hint: "[path]" } },
221 ]);
222 assert.equal(capabilities?.usage, undefined);
223 assert.equal(abortSignal?.aborted, true);
224 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
225);