Open History to see the last commit
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 Deferred from "effect/Deferred";
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 { AgentScope } from "@t3tools/shared/AgentScope";
19import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
20import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
21import {
22 ClaudeAgentSdkQueryRunner,
23 layerQueryRunner,
24 spawnClaudeProcessGroup,
25} from "./ClaudeAdapterV2.ts";
26
27vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
28
29const FORK_SESSION_ID = "11111111-1111-4111-8111-111111111111";
30
31const writeClaudeSession = Effect.fnUntraced(function* (configDir: string) {
32 const fileSystem = yield* FileSystem.FileSystem;
33 const path = yield* Path.Path;
34 const projectDir = path.join(configDir, "projects", "-repo");
35 const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({
36 type: parentUuid === null ? "user" : "assistant",
37 uuid,
38 parentUuid,
39 sessionId: FORK_SESSION_ID,
40 cwd: "/repo",
41 isSidechain: false,
42 timestamp: "2026-10-01T00:00:00.000Z",
43 message,
44 });
45 yield* fileSystem.makeDirectory(projectDir, { recursive: true });
46 yield* fileSystem.writeFileString(
47 path.join(projectDir, `${FORK_SESSION_ID}.jsonl`),
48 [
49 entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }),
50 entry("aaaaaaaa-0000-4000-8000-000000000002", "aaaaaaaa-0000-4000-8000-000000000001", {
51 role: "assistant",
52 content: [{ type: "text", text: "hi" }],
53 }),
54 ]
55 .map((line) => JSON.stringify(line))
56 .join("\n"),
57 );
58 return projectDir;
59});
60
61const forkRunnerLayer = layerQueryRunner.pipe(
62 Layer.provide(Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined })),
63);
64
65it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", () =>
66 Effect.scoped(
67 Effect.gen(function* () {
68 const fileSystem = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 const configDir = yield* fileSystem.makeTempDirectoryScoped({
71 prefix: "t3-claude-fork-config-",
72 });
73 const projectDir = yield* writeClaudeSession(configDir);
74 const hostConfigDir = process.env.CLAUDE_CONFIG_DIR;
75 const inProcessFork = vi.spyOn(ClaudeSdk, "forkSession");
76 yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore()));
77
78 const runner = yield* ClaudeAgentSdkQueryRunner;
79 const forked = yield* runner.forkSession({
80 sessionId: FORK_SESSION_ID,
81 options: { dir: "/repo" },
82 environment: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
83 threadId: ThreadId.make("thread-fork-config-dir"),
84 providerSessionId: ProviderSessionId.make("session-fork-config-dir"),
85 });
86
87 assert.notEqual(forked.sessionId, FORK_SESSION_ID);
88 const transcript = yield* fileSystem.readFileString(
89 path.join(projectDir, `${forked.sessionId}.jsonl`),
90 );
91 assert.include(transcript, '"content":"hello"');
92 assert.include(transcript, '"text":"hi"');
93 const inheritedHead = transcript
94 .trim()
95 .split("\n")
96 .findLast((line) => line.includes('"type":"assistant"'))
97 ?.match(/"uuid"\s*:\s*"([^"]+)"/)?.[1];
98 assert.isString(inheritedHead);
99 assert.equal(forked.headMessageId, inheritedHead);
100 assert.equal(process.env.CLAUDE_CONFIG_DIR, hostConfigDir);
101 assert.equal(inProcessFork.mock.calls.length, 0);
102 }).pipe(Effect.provide(forkRunnerLayer)),
103 ).pipe(Effect.provide(NodeServices.layer)),
104);
105const realQueryRunner = layerQueryRunner.pipe(
106 Layer.provide(
107 Layer.succeed(ProviderEventLoggers, {
108 native: undefined,
109 canonical: undefined,
110 }),
111 ),
112 Layer.provide(NodeServices.layer),
113);
114
115function fakeClaudeCli(script: string): string {
116 const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-"));
117 const cli = NodePath.join(dir, "claude");
118 NodeFS.writeFileSync(cli, `#!/bin/sh\n${script}\n`, { mode: 0o755 });
119 return cli;
120}
121
122const openFakeCli = (cli: string) =>
123 Effect.gen(function* () {
124 const runner = yield* ClaudeAgentSdkQueryRunner;
125 return yield* runner.open({
126 threadId: ThreadId.make("thread-fake-cli"),
127 providerSessionId: ProviderSessionId.make("session-fake-cli"),
128 options: {
129 sessionId: "native-session-fake-cli",
130 model: "claude-sonnet-4-6",
131 tools: [],
132 permissionMode: "default",
133 pathToClaudeCodeExecutable: cli,
134 },
135 });
136 });
137
138describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI process", () => {
139 // The CLI stops the MCP servers it started, but not their children: a
140 // plugin's `bun server.ts` outlives its `bun run` wrapper (#3089). The child
141 // holds a FIFO open, so its death reads as end-of-file here, with no polling.
142 it.effect("stops what the CLI left running when the session closes", () =>
143 Effect.gen(function* () {
144 const cli = fakeClaudeCli(
145 [
146 'dir=$(dirname "$0")',
147 'sleep 600 > "$dir/alive" &',
148 'echo $! > "$dir/leftover.pid"',
149 "cat > /dev/null",
150 ].join("\n"),
151 );
152 const dir = NodePath.dirname(cli);
153 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
154 yield* Effect.addFinalizer(() =>
155 Effect.sync(() => {
156 try {
157 process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
158 } catch {}
159 NodeFS.rmSync(dir, { recursive: true, force: true });
160 }),
161 );
162 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
163 const leftoverStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
164 const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
165 alive.resume();
166
167 const stopped = yield* Deferred.make<string>();
168 const session = yield* openFakeCli(cli).pipe(
169 Effect.provide(
170 realQueryRunner.pipe(
171 Layer.provide(
172 Layer.succeed(AgentScope, {
173 ...AgentScope.defaultValue(),
174 wrap: ({ command, args }) =>
175 Effect.succeed({ command, args, unit: "t3code-claude-test.scope" }),
176 stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid),
177 }),
178 ),
179 ),
180 ),
181 );
182 yield* Effect.promise(() => leftoverStarted);
183 yield* session.close;
184 yield* Effect.promise(() => leftoverStopped);
185 assert.strictEqual(yield* Deferred.await(stopped), "t3code-claude-test.scope");
186 }),
187 );
188
189 // The CLI keeps running its turn after its pipes close, so a server that
190 // crashed would leave it working next to the session it resumes (#23370).
191 it.effect("stops the CLI when the server that started it goes away", () =>
192 Effect.gen(function* () {
193 const cli = fakeClaudeCli(['dir=$(dirname "$0")', 'sleep 600 > "$dir/alive"'].join("\n"));
194 const dir = NodePath.dirname(cli);
195 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
196 const child = spawnClaudeProcessGroup({
197 command: cli,
198 args: [],
199 cwd: dir,
200 env: process.env,
201 signal: new AbortController().signal,
202 }) as NodeChildProcess.ChildProcess;
203 yield* Effect.addFinalizer(() =>
204 Effect.sync(() => {
205 try {
206 signalProcessGroup(child.pid ?? 0, "SIGKILL");
207 } catch {}
208 NodeFS.rmSync(dir, { recursive: true, force: true });
209 }),
210 );
211 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
212 const turnStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
213 const turnStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
214 alive.resume();
215 yield* Effect.promise(() => turnStarted);
216
217 // A dying server's descriptors close; the kernel would do this for it.
218 for (const pipe of child.stdio) pipe?.destroy();
219 yield* Effect.promise(() => turnStopped);
220 }),
221 );
222});