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 leftover child holds a FIFO open; its death produces EOF without polling.
140 it.effect("stops what the CLI left running when the session closes", () =>
141 Effect.gen(function* () {
142 const cli = fakeClaudeCli(
143 [
144 'dir=$(dirname "$0")',
145 'sleep 600 > "$dir/alive" &',
146 'echo $! > "$dir/leftover.pid"',
147 "cat > /dev/null",
148 ].join("\n"),
149 );
150 const dir = NodePath.dirname(cli);
151 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
152 yield* Effect.addFinalizer(() =>
153 Effect.sync(() => {
154 try {
155 process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
156 } catch {}
157 NodeFS.rmSync(dir, { recursive: true, force: true });
158 }),
159 );
160 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
161 const leftoverStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
162 const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
163 alive.resume();
164
165 const stopped = yield* Deferred.make<string>();
166 const session = yield* openFakeCli(cli).pipe(
167 Effect.provide(
168 realQueryRunner.pipe(
169 Layer.provide(
170 Layer.succeed(AgentScope, {
171 ...AgentScope.defaultValue(),
172 wrap: ({ command, args }) =>
173 Effect.succeed({ command, args, unit: "t3code-claude-test.scope" }),
174 stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid),
175 }),
176 ),
177 ),
178 ),
179 );
180 yield* Effect.promise(() => leftoverStarted);
181 yield* session.close;
182 yield* Effect.promise(() => leftoverStopped);
183 assert.strictEqual(yield* Deferred.await(stopped), "t3code-claude-test.scope");
184 }),
185 );
186
187 // The CLI keeps running its turn after its pipes close, so a server that
188 // crashed would leave it working next to the session it resumes.
189 it.effect("stops the CLI when the server that started it goes away", () =>
190 Effect.gen(function* () {
191 const cli = fakeClaudeCli(['dir=$(dirname "$0")', 'sleep 600 > "$dir/alive"'].join("\n"));
192 const dir = NodePath.dirname(cli);
193 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
194 const child = spawnClaudeProcessGroup({
195 command: cli,
196 args: [],
197 cwd: dir,
198 env: process.env,
199 signal: new AbortController().signal,
200 }) as NodeChildProcess.ChildProcess;
201 yield* Effect.addFinalizer(() =>
202 Effect.sync(() => {
203 try {
204 signalProcessGroup(child.pid ?? 0, "SIGKILL");
205 } catch {}
206 NodeFS.rmSync(dir, { recursive: true, force: true });
207 }),
208 );
209 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
210 const turnStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
211 const turnStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
212 alive.resume();
213 yield* Effect.promise(() => turnStarted);
214
215 // A dying server's descriptors close; the kernel would do this for it.
216 for (const pipe of child.stdio) pipe?.destroy();
217 yield* Effect.promise(() => turnStopped);
218 }),
219 );
220});