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

ClaudeAgentSdkQueryRunner.test.ts

248 lines9.3 KB

1// @effect-diagnostics nodeBuiltinImport:off -- the fake CLI and its leftover child are real processes.
2import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFS from "node:fs";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { assert, describe, it } from "@effect/vitest";
9import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import { vi } from "vite-plus/test";
16​
17import * as HostProcess from "@t3tools/shared/HostProcess";
18import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
19import {
20 CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
21 ClaudeAgentSdkQueryRunner,
22 layerQueryRunner,
23} from "./ClaudeAdapterV2.ts";
24​
25vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
26​
27it.effect("logs successful task stops for replay and omits failed stops", () =>
28 Effect.gen(function* () {
29 const writes: unknown[] = [];
30 const stopTask = vi.fn(async (_taskId: string) => {});
31 const query = vi.spyOn(ClaudeSdk, "query").mockReturnValue({
32 stopTask,
33 } as unknown as ClaudeSdk.Query);
34 yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
35 const threadId = ThreadId.make("thread-stop");
36 const providerSessionId = ProviderSessionId.make("session-stop");
37 yield* Effect.gen(function* () {
38 const runner = yield* ClaudeAgentSdkQueryRunner;
39 const session = yield* runner.open({
40 threadId,
41 providerSessionId,
42 options: {
43 sessionId: "native-session-stop",
44 model: "claude-sonnet-4-6",
45 tools: [],
46 permissionMode: "default",
47 },
48 });
49 writes.length = 0;
50 yield* session.stopTask("workflow-task");
51 assert.deepEqual(stopTask.mock.calls, [["workflow-task"]]);
52 assert.deepEqual(writes, [
53 {
54 provider: "claudeAgent",
55 protocol: CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
56 kind: "protocol",
57 providerSessionId,
58 event: {
59 direction: "outgoing",
60 stage: "decoded",
61 payload: { type: "query.stop_task", taskId: "workflow-task" },
62 },
63 },
64 ]);
65 stopTask.mockRejectedValueOnce(new Error("Stop failed"));
66 assert.isTrue(Exit.isFailure(yield* Effect.exit(session.stopTask("failed-task"))));
67 assert.equal(writes.length, 1);
68 }).pipe(
69 Effect.provide(
70 layerQueryRunner.pipe(
71 Layer.provide(
72 Layer.succeed(ProviderEventLoggers, {
73 native: {
74 filePath: "/tmp/events.log",
75 write: (event) =>
76 Effect.sync(() => {
77 writes.push(event);
78 }),
79 close: () => Effect.void,
80 },
81 canonical: undefined,
82 }),
83 ),
84 ),
85 ),
86 );
87 }).pipe(Effect.provide(NodeServices.layer)),
88);
89​
90const FORK_SESSION_ID = "11111111-1111-4111-8111-111111111111";
91​
92const writeClaudeSession = Effect.fnUntraced(function* (configDir: string) {
93 const fileSystem = yield* FileSystem.FileSystem;
94 const path = yield* Path.Path;
95 const projectDir = path.join(configDir, "projects", "-repo");
96 const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({
97 type: parentUuid === null ? "user" : "assistant",
98 uuid,
99 parentUuid,
100 sessionId: FORK_SESSION_ID,
101 cwd: "/repo",
102 isSidechain: false,
103 timestamp: "2026-10-01T00:00:00.000Z",
104 message,
105 });
106 yield* fileSystem.makeDirectory(projectDir, { recursive: true });
107 yield* fileSystem.writeFileString(
108 path.join(projectDir, `${FORK_SESSION_ID}.jsonl`),
109 [
110 entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }),
111 entry("aaaaaaaa-0000-4000-8000-000000000002", "aaaaaaaa-0000-4000-8000-000000000001", {
112 role: "assistant",
113 content: [{ type: "text", text: "hi" }],
114 }),
115 ]
116 .map((line) => JSON.stringify(line))
117 .join("\n"),
118 );
119 return projectDir;
120});
121​
122const forkRunnerLayer = layerQueryRunner.pipe(
123 Layer.provide(Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined })),
124);
125​
126it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", () =>
127 Effect.scoped(
128 Effect.gen(function* () {
129 const fileSystem = yield* FileSystem.FileSystem;
130 const path = yield* Path.Path;
131 const configDir = yield* fileSystem.makeTempDirectoryScoped({
132 prefix: "t3-claude-fork-config-",
133 });
134 const projectDir = yield* writeClaudeSession(configDir);
135 const hostConfigDir = process.env.CLAUDE_CONFIG_DIR;
136 const inProcessFork = vi.spyOn(ClaudeSdk, "forkSession");
137 yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore()));
138​
139 const runner = yield* ClaudeAgentSdkQueryRunner;
140 const forked = yield* runner.forkSession({
141 sessionId: FORK_SESSION_ID,
142 options: { dir: "/repo" },
143 environment: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
144 threadId: ThreadId.make("thread-fork-config-dir"),
145 providerSessionId: ProviderSessionId.make("session-fork-config-dir"),
146 });
147​
148 assert.notEqual(forked.sessionId, FORK_SESSION_ID);
149 const transcript = yield* fileSystem.readFileString(
150 path.join(projectDir, `${forked.sessionId}.jsonl`),
151 );
152 assert.include(transcript, '"content":"hello"');
153 assert.include(transcript, '"text":"hi"');
154 assert.equal(process.env.CLAUDE_CONFIG_DIR, hostConfigDir);
155 assert.equal(inProcessFork.mock.calls.length, 0);
156 }).pipe(Effect.provide(forkRunnerLayer)),
157 ).pipe(Effect.provide(NodeServices.layer)),
158);
159​
160it.effect("forks in-process when the instance shares the server's config dir", () =>
161 Effect.scoped(
162 Effect.gen(function* () {
163 const inProcessFork = vi
164 .spyOn(ClaudeSdk, "forkSession")
165 .mockResolvedValue({ sessionId: "forked-in-process" });
166 yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore()));
167 const runner = yield* ClaudeAgentSdkQueryRunner;
168 const forked = yield* runner.forkSession({
169 sessionId: FORK_SESSION_ID,
170 options: { dir: "/repo" },
171 environment: { ...process.env },
172 threadId: ThreadId.make("thread-fork-shared-config-dir"),
173 providerSessionId: ProviderSessionId.make("session-fork-shared-config-dir"),
174 });
175​
176 assert.equal(forked.sessionId, "forked-in-process");
177 }).pipe(Effect.provide(forkRunnerLayer)),
178 ).pipe(Effect.provide(NodeServices.layer)),
179);
180const realQueryRunner = layerQueryRunner.pipe(
181 Layer.provide(
182 Layer.succeed(ProviderEventLoggers, {
183 native: undefined,
184 canonical: undefined,
185 }),
186 ),
187 Layer.provide(NodeServices.layer),
188);
189​
190function fakeClaudeCli(script: string): string {
191 const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-"));
192 const cli = NodePath.join(dir, "claude");
193 NodeFS.writeFileSync(cli, `#!/bin/sh\n${script}\n`, { mode: 0o755 });
194 return cli;
196​
197const openFakeCli = (cli: string) =>
198 Effect.gen(function* () {
199 const runner = yield* ClaudeAgentSdkQueryRunner;
200 return yield* runner.open({
201 threadId: ThreadId.make("thread-fake-cli"),
202 providerSessionId: ProviderSessionId.make("session-fake-cli"),
203 options: {
204 sessionId: "native-session-fake-cli",
205 model: "claude-sonnet-4-6",
206 tools: [],
207 permissionMode: "default",
208 pathToClaudeCodeExecutable: cli,
209 },
210 });
211 });
212​
213describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI process", () => {
214 // The CLI stops the MCP servers it started, but not their children: a
215 // plugin's `bun server.ts` outlives its `bun run` wrapper (#3089). The child
216 // holds a FIFO open, so its death reads as end-of-file here, with no polling.
217 it.effect("stops what the CLI left running when the session closes", () =>
218 Effect.gen(function* () {
219 const cli = fakeClaudeCli(
220 [
221 'dir=$(dirname "$0")',
222 'sleep 600 > "$dir/alive" &',
223 'echo $! > "$dir/leftover.pid"',
224 "cat > /dev/null",
225 ].join("\n"),
226 );
227 const dir = NodePath.dirname(cli);
228 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
229 yield* Effect.addFinalizer(() =>
230 Effect.sync(() => {
231 try {
232 process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
233 } catch {}
234 NodeFS.rmSync(dir, { recursive: true, force: true });
235 }),
236 );
237 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
238 const leftoverStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
239 const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
240 alive.resume();
241​
242 const session = yield* openFakeCli(cli);
243 yield* Effect.promise(() => leftoverStarted);
244 yield* session.close;
245 yield* Effect.promise(() => leftoverStopped);
246 }).pipe(Effect.provide(realQueryRunner)),
247 );
248});