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 NodeEvents from "node:events";
5import * as NodeFS from "node:fs";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import * as NodeStream from "node:stream";
9import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
10import * as NodeServices from "@effect/platform-node/NodeServices";
11import { assert, describe, it } from "@effect/vitest";
12import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Deferred from "effect/Deferred";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Path from "effect/Path";
20import * as Stream from "effect/Stream";
21import * as TestClock from "effect/testing/TestClock";
22import { vi } from "vite-plus/test";
23
24import * as HostProcess from "@t3tools/shared/HostProcess";
25import { AgentScope } from "@t3tools/shared/AgentScope";
26import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
27import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
28import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
29import * as PortScanner from "../../preview/PortScanner.ts";
30import {
31 ClaudeAgentSdkQueryRunner,
32 type ClaudeAgentSdkQueryOpenInput,
33 layerQueryRunner,
34 spawnClaudeProcessGroup,
35} from "./ClaudeAdapterV2.ts";
36
37vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
38
39const FORK_SESSION_ID = "11111111-1111-4111-8111-111111111111";
40
41const sessionEntry = (uuid: string, parentUuid: string | null, message: unknown) => ({
42 type: parentUuid === null ? "user" : "assistant",
43 uuid,
44 parentUuid,
45 sessionId: FORK_SESSION_ID,
46 cwd: "/repo",
47 isSidechain: false,
48 timestamp: "2026-10-01T00:00:00.000Z",
49 message,
50});
51
52const writeClaudeSession = Effect.fnUntraced(function* (
53 configDir: string,
54 entries: ReadonlyArray<unknown> = [
55 sessionEntry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }),
56 sessionEntry("aaaaaaaa-0000-4000-8000-000000000002", "aaaaaaaa-0000-4000-8000-000000000001", {
57 role: "assistant",
58 content: [{ type: "text", text: "hi" }],
59 }),
60 ],
61) {
62 const fileSystem = yield* FileSystem.FileSystem;
63 const path = yield* Path.Path;
64 const projectDir = path.join(configDir, "projects", "-repo");
65 yield* fileSystem.makeDirectory(projectDir, { recursive: true });
66 yield* fileSystem.writeFileString(
67 path.join(projectDir, `${FORK_SESSION_ID}.jsonl`),
68 entries.map((line) => JSON.stringify(line)).join("\n"),
69 );
70 return projectDir;
71});
72
73const forkRunnerLayer = layerQueryRunner.pipe(
74 Layer.provide(PortScanner.layerTest),
75 Layer.provide(Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined })),
76);
77
78it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", () =>
79 Effect.scoped(
80 Effect.gen(function* () {
81 const fileSystem = yield* FileSystem.FileSystem;
82 const path = yield* Path.Path;
83 const configDir = yield* fileSystem.makeTempDirectoryScoped({
84 prefix: "t3-claude-fork-config-",
85 });
86 const projectDir = yield* writeClaudeSession(configDir);
87 const hostConfigDir = (yield* HostProcess.Environment).CLAUDE_CONFIG_DIR;
88 const inProcessFork = vi.spyOn(ClaudeSdk, "forkSession");
89 yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore()));
90
91 const runner = yield* ClaudeAgentSdkQueryRunner;
92 const forked = yield* runner.forkSession({
93 sessionId: FORK_SESSION_ID,
94 options: { dir: "/repo" },
95 environment: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
96 threadId: ThreadId.make("thread-fork-config-dir"),
97 providerSessionId: ProviderSessionId.make("session-fork-config-dir"),
98 });
99
100 assert.notEqual(forked.sessionId, FORK_SESSION_ID);
101 const transcript = yield* fileSystem.readFileString(
102 path.join(projectDir, `${forked.sessionId}.jsonl`),
103 );
104 assert.include(transcript, '"content":"hello"');
105 assert.include(transcript, '"text":"hi"');
106 const inheritedHead = transcript
107 .trim()
108 .split("\n")
109 .findLast((line) => line.includes('"type":"assistant"'))
110 ?.match(/"uuid"\s*:\s*"([^"]+)"/)?.[1];
111 assert.isString(inheritedHead);
112 assert.equal(forked.headMessageId, inheritedHead);
113 assert.equal((yield* HostProcess.Environment).CLAUDE_CONFIG_DIR, hostConfigDir);
114 assert.equal(inProcessFork.mock.calls.length, 0);
115 }).pipe(Effect.provide(forkRunnerLayer)),
116 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
117);
118it.effect("forked Claude sessions keep their compaction chain", () =>
119 Effect.scoped(
120 Effect.gen(function* () {
121 const fileSystem = yield* FileSystem.FileSystem;
122 const path = yield* Path.Path;
123 const configDir = yield* fileSystem.makeTempDirectoryScoped({
124 prefix: "t3-claude-fork-compact-",
125 });
126 const uuid = (n: number) => `bbbbbbbb-0000-4000-8000-00000000000${n}`;
127 const turn = (id: number, parent: string | null, role: "user" | "assistant") => ({
128 ...sessionEntry(uuid(id), parent, {
129 role,
130 content: role === "user" ? `question ${id}` : [{ type: "text", text: `answer ${id}` }],
131 }),
132 type: role,
133 });
134 const projectDir = yield* writeClaudeSession(configDir, [
135 turn(1, null, "user"),
136 turn(2, uuid(1), "assistant"),
137 turn(3, uuid(2), "user"),
138 turn(4, uuid(3), "assistant"),
139 {
140 ...sessionEntry(uuid(5), null, undefined),
141 type: "system",
142 subtype: "compact_boundary",
143 content: "Conversation compacted",
144 logicalParentUuid: uuid(4),
145 compactMetadata: {
146 trigger: "manual",
147 preTokens: 19979,
148 preservedSegment: { headUuid: uuid(3), anchorUuid: uuid(6), tailUuid: uuid(4) },
149 preservedMessages: {
150 anchorUuid: uuid(6),
151 uuids: [uuid(3), uuid(4)],
152 allUuids: [uuid(3), uuid(4)],
153 },
154 postTokens: 3589,
155 },
156 },
157 {
158 ...turn(6, uuid(5), "user"),
159 isCompactSummary: true,
160 isVisibleInTranscriptOnly: true,
161 },
162 turn(7, uuid(4), "user"),
163 turn(8, uuid(7), "assistant"),
164 ]);
165
166 const runner = yield* ClaudeAgentSdkQueryRunner;
167 const forked = yield* runner.forkSession({
168 sessionId: FORK_SESSION_ID,
169 options: { dir: "/repo" },
170 environment: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
171 threadId: ThreadId.make("thread-fork-compaction"),
172 providerSessionId: ProviderSessionId.make("session-fork-compaction"),
173 });
174
175 const entries: ReadonlyArray<{
176 readonly uuid?: string;
177 readonly subtype?: string;
178 readonly compactMetadata?: {
179 readonly preservedSegment: Record<"headUuid" | "anchorUuid" | "tailUuid", string>;
180 readonly preservedMessages: {
181 readonly anchorUuid: string;
182 readonly uuids: string[];
183 readonly allUuids: string[];
184 };
185 };
186 }> = (yield* fileSystem.readFileString(path.join(projectDir, `${forked.sessionId}.jsonl`)))
187 .trim()
188 .split("\n")
189 .map((line) => JSON.parse(line));
190 const forkedUuids = new Set(entries.map((entry) => entry.uuid));
191 const boundary = entries.find((entry) => entry.subtype === "compact_boundary");
192 assert.isDefined(boundary?.compactMetadata);
193 const { preservedSegment, preservedMessages } = boundary!.compactMetadata!;
194 const danglingRefs = [
195 ...Object.values(preservedSegment),
196 preservedMessages.anchorUuid,
197 ...preservedMessages.uuids,
198 ...preservedMessages.allUuids,
199 ].filter((ref) => !forkedUuids.has(ref));
200 assert.deepEqual(danglingRefs, [], "compaction refs missing from the forked transcript");
201 }).pipe(Effect.provide(forkRunnerLayer)),
202 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
203);
204
205const realQueryRunner = layerQueryRunner.pipe(
206 Layer.provide(PortScanner.layerTest),
207 Layer.provide(
208 Layer.succeed(ProviderEventLoggers, {
209 native: undefined,
210 canonical: undefined,
211 }),
212 ),
213 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
214);
215
216const resumedMcpQueryInput = {
217 threadId: ThreadId.make("thread-restart-registration"),
218 providerSessionId: ProviderSessionId.make("session-restart-registration"),
219 options: {
220 resume: FORK_SESSION_ID,
221 model: "claude-sonnet-4-6",
222 tools: [],
223 permissionMode: "default",
224 mcpServers: {
225 "t3-code": {
226 type: "http",
227 url: "http://localhost:3773/mcp",
228 headers: { Authorization: "Bearer test-mcp-credential" },
229 },
230 },
231 },
232} satisfies ClaudeAgentSdkQueryOpenInput;
233
234it.effect("reopens a stalled MCP registration before delivering the resumed prompt", () =>
235 Effect.gen(function* () {
236 const registrationStarted = Promise.withResolvers<void>();
237 const disposalStarted = Promise.withResolvers<void>();
238 const finishDisposal = Promise.withResolvers<void>();
239 const prompts: AsyncIterable<ClaudeSdk.SDKUserMessage>[] = [];
240 const firstClose = vi.fn();
241 const secondClose = vi.fn();
242 const firstRegistration = vi.fn(() => {
243 registrationStarted.resolve();
244 return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
245 });
246 const secondRegistration = vi.fn(async () => ({
247 added: ["t3-code"],
248 removed: [],
249 errors: {},
250 }));
251 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ prompt }) => {
252 assert.notTypeOf(prompt, "string");
253 if (typeof prompt === "string") throw new Error("Expected streaming input");
254 prompts.push(prompt);
255 return {
256 initializationResult: async () => ({}),
257 setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration,
258 close: prompts.length === 1 ? firstClose : secondClose,
259 [Symbol.asyncDispose]: async () => {
260 firstClose();
261 disposalStarted.resolve();
262 await finishDisposal.promise;
263 },
264 } as unknown as ClaudeSdk.Query;
265 });
266 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
267 const runner = yield* ClaudeAgentSdkQueryRunner;
268 const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild);
269 yield* Effect.promise(() => registrationStarted.promise);
270 yield* TestClock.adjust("90 seconds");
271 yield* Effect.promise(() => disposalStarted.promise);
272 assert.equal(querySpy.mock.calls.length, 1);
273 finishDisposal.resolve();
274 const session = yield* Fiber.join(opening);
275 yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie));
276
277 assert.equal(firstClose.mock.calls.length, 1);
278 assert.equal(secondClose.mock.calls.length, 0);
279 assert.equal(querySpy.mock.calls.length, 2);
280 for (const [call] of querySpy.mock.calls) {
281 assert.equal(call.options?.resume, FORK_SESSION_ID);
282 assert.isUndefined(call.options?.mcpServers);
283 }
284 assert.deepEqual(secondRegistration.mock.calls, [[resumedMcpQueryInput.options.mcpServers]]);
285 const message = {
286 type: "user",
287 message: { role: "user", content: "Continue where you left off." },
288 parent_tool_use_id: null,
289 session_id: FORK_SESSION_ID,
290 } satisfies ClaudeSdk.SDKUserMessage;
291 yield* session.offer(message);
292 assert.isTrue((yield* Effect.promise(() => prompts[0]![Symbol.asyncIterator]().next())).done);
293 const delivered = yield* Effect.promise(() => prompts[1]![Symbol.asyncIterator]().next());
294 assert.deepEqual(delivered.value, message);
295 assert.isFalse(delivered.done);
296 }).pipe(Effect.provide(realQueryRunner)),
297);
298
299it.effect.each([
300 { case: "a readable rule list", errors: undefined, readable: true },
301 { case: "a settings file Claude skipped", errors: [{ file: "settings.json" }], readable: false },
302 { case: "a reply without a rule list", response: {}, readable: false },
303])("reads Claude's permission rules only when no settings file was skipped: $case", (testCase) =>
304 Effect.gen(function* () {
305 const rules = [{ behavior: "deny" as const, rule: "mcp__probe__redeploy" }];
306 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
307 () =>
308 ({
309 close: vi.fn(),
310 request: async () => ({
311 response:
312 "response" in testCase
313 ? testCase.response
314 : { state: { rules, errors: testCase.errors } },
315 }),
316 }) as unknown as ClaudeSdk.Query,
317 );
318 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
319 const runner = yield* ClaudeAgentSdkQueryRunner;
320 const { mcpServers: _mcpServers, ...options } = resumedMcpQueryInput.options;
321 const session = yield* runner.open({ ...resumedMcpQueryInput, options });
322 yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie));
323 const exit = yield* Effect.exit(session.listPermissionRules);
324 if (testCase.readable) assert.deepEqual(exit, Exit.succeed(rules));
325 else assert.isTrue(Exit.isFailure(exit));
326 }).pipe(Effect.provide(realQueryRunner)),
327);
328
329it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) =>
330 Effect.gen(function* () {
331 const registrationStarted = Promise.withResolvers<void>();
332 const cleanupProgress = Promise.withResolvers<"kill" | "retry">();
333 const events = new NodeEvents.EventEmitter();
334 const stdin = new NodeStream.PassThrough();
335 const stdout = new NodeStream.PassThrough();
336 const child = {
337 stdin,
338 stdout,
339 killed: false,
340 exitCode: null,
341 kill: vi.fn(() => {
342 cleanupProgress.resolve("kill");
343 return true;
344 }),
345 on: events.on.bind(events),
346 once: events.once.bind(events),
347 off: events.off.bind(events),
348 } satisfies ClaudeSdk.SpawnedProcess;
349 const signal = yield* Effect.abortSignal;
350 const disposed = vi.fn(async () => {});
351 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
352 const first = querySpy.mock.calls.length === 1;
353 if (first) {
354 options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal });
355 } else {
356 cleanupProgress.resolve("retry");
357 }
358 return {
359 initializationResult: async () => ({}),
360 setMcpServers: () => {
361 registrationStarted.resolve();
362 return first
363 ? new Promise<ClaudeSdk.McpSetServersResult>(() => {})
364 : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} });
365 },
366 close: vi.fn(),
367 [Symbol.asyncDispose]: disposed,
368 } as unknown as ClaudeSdk.Query;
369 });
370 yield* Effect.addFinalizer(() =>
371 Effect.sync(() => {
372 querySpy.mockRestore();
373 stdin.destroy();
374 stdout.destroy();
375 }),
376 );
377 const runner = yield* ClaudeAgentSdkQueryRunner;
378 const opening = yield* runner
379 .open({
380 ...resumedMcpQueryInput,
381 options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child },
382 })
383 .pipe(Effect.exit, Effect.forkChild);
384 yield* Effect.promise(() => registrationStarted.promise);
385 yield* TestClock.adjust("90 seconds");
386
387 assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill");
388 assert.equal(querySpy.mock.calls.length, 1);
389 assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]);
390 if (exits) events.emit("exit", null, "SIGKILL");
391 else yield* TestClock.adjust("10 seconds");
392 const result = yield* Fiber.join(opening);
393 assert.equal(Exit.isSuccess(result), exits);
394 if (Exit.isSuccess(result)) yield* result.value.close;
395 assert.equal(querySpy.mock.calls.length, exits ? 2 : 1);
396 assert.equal(disposed.mock.calls.length, 1);
397 }).pipe(Effect.provide(realQueryRunner)),
398);
399
400it.effect("stops retrying MCP registration after two timeouts and reports the cause", () =>
401 Effect.gen(function* () {
402 const firstRegistration = Promise.withResolvers<void>();
403 const secondRegistration = Promise.withResolvers<void>();
404 const disposed = vi.fn(async () => {});
405 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
406 const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration;
407 return {
408 initializationResult: async () => ({}),
409 setMcpServers: () => {
410 started.resolve();
411 return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
412 },
413 [Symbol.asyncDispose]: disposed,
414 } as unknown as ClaudeSdk.Query;
415 });
416 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
417 const runner = yield* ClaudeAgentSdkQueryRunner;
418 const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.result, Effect.forkChild);
419 yield* Effect.promise(() => firstRegistration.promise);
420 yield* TestClock.adjust("90 seconds");
421 yield* Effect.promise(() => secondRegistration.promise);
422 yield* TestClock.adjust("90 seconds");
423 const result = yield* Fiber.join(opening);
424
425 assert.equal(result._tag, "Failure");
426 if (result._tag !== "Failure") return;
427 assert.equal(querySpy.mock.calls.length, 2);
428 assert.equal(disposed.mock.calls.length, 2);
429 assert.equal(
430 makeProviderFailure({
431 cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
432 }).message,
433 "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.",
434 );
435 }).pipe(Effect.provide(realQueryRunner)),
436);
437
438it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () =>
439 Effect.gen(function* () {
440 const registrationStarted = Promise.withResolvers<void>();
441 const disposed = vi.fn(async () => {});
442 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
443 () =>
444 ({
445 initializationResult: async () => ({}),
446 setMcpServers: () => {
447 registrationStarted.resolve();
448 return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
449 },
450 [Symbol.asyncDispose]: disposed,
451 }) as unknown as ClaudeSdk.Query,
452 );
453 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
454 const runner = yield* ClaudeAgentSdkQueryRunner;
455 const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild);
456 yield* Effect.promise(() => registrationStarted.promise);
457 yield* Fiber.interrupt(opening);
458
459 assert.equal(querySpy.mock.calls.length, 1);
460 assert.equal(disposed.mock.calls.length, 1);
461 const prompt = querySpy.mock.calls[0]![0].prompt;
462 if (typeof prompt === "string") throw new Error("Expected streaming input");
463 assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done);
464 }).pipe(Effect.provide(realQueryRunner)),
465);
466
467it.effect("does not reuse a fresh session ID after MCP registration times out", () =>
468 Effect.gen(function* () {
469 const registrationStarted = Promise.withResolvers<void>();
470 const disposed = vi.fn(async () => {});
471 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
472 () =>
473 ({
474 initializationResult: async () => ({}),
475 setMcpServers: () => {
476 registrationStarted.resolve();
477 return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
478 },
479 [Symbol.asyncDispose]: disposed,
480 }) as unknown as ClaudeSdk.Query,
481 );
482 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
483 const runner = yield* ClaudeAgentSdkQueryRunner;
484 const { resume, ...options } = resumedMcpQueryInput.options;
485 const opening = yield* runner
486 .open({
487 ...resumedMcpQueryInput,
488 options: { ...options, sessionId: resume },
489 })
490 .pipe(Effect.result, Effect.forkChild);
491 yield* Effect.promise(() => registrationStarted.promise);
492 yield* TestClock.adjust("90 seconds");
493 const result = yield* Fiber.join(opening);
494
495 assert.equal(result._tag, "Failure");
496 assert.equal(querySpy.mock.calls.length, 1);
497 assert.equal(disposed.mock.calls.length, 1);
498 }).pipe(Effect.provide(realQueryRunner)),
499);
500
501it.effect.each([
502 ["opens after a slow CLI boot", "120 seconds", true],
503 ["times out a CLI that never boots", "5 minutes", false],
504] as const)("%s", ([, bootWait, boots]) =>
505 Effect.gen(function* () {
506 const waiting = Promise.withResolvers<void>();
507 const booted = Promise.withResolvers<void>();
508 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
509 () =>
510 ({
511 initializationResult: () => {
512 waiting.resolve();
513 return booted.promise;
514 },
515 // The CLI answers control requests only after it has booted.
516 setMcpServers: async () => {
517 waiting.resolve();
518 await booted.promise;
519 return { added: ["t3-code"], removed: [], errors: {} };
520 },
521 close: vi.fn(),
522 [Symbol.asyncDispose]: async () => {},
523 }) as unknown as ClaudeSdk.Query,
524 );
525 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
526 const runner = yield* ClaudeAgentSdkQueryRunner;
527 const { resume, ...options } = resumedMcpQueryInput.options;
528 const opening = yield* runner
529 .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } })
530 .pipe(Effect.result, Effect.forkChild);
531 yield* Effect.promise(() => waiting.promise);
532 yield* TestClock.adjust(bootWait);
533 if (boots) booted.resolve();
534 const result = yield* Fiber.join(opening);
535
536 assert.equal(result._tag, boots ? "Success" : "Failure");
537 if (result._tag === "Success") yield* result.success.close;
538 else
539 assert.equal(
540 makeProviderFailure({
541 cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
542 }).message,
543 "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs.",
544 );
545 }).pipe(Effect.provide(realQueryRunner)),
546);
547
548function fakeClaudeCli(script: string): string {
549 const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-"));
550 const cli = NodePath.join(dir, "claude");
551 NodeFS.writeFileSync(cli, `#!/bin/sh\n${script}\n`, { mode: 0o755 });
552 return cli;
553}
554
555const openFakeCli = (cli: string) =>
556 Effect.gen(function* () {
557 const runner = yield* ClaudeAgentSdkQueryRunner;
558 return yield* runner.open({
559 threadId: ThreadId.make("thread-fake-cli"),
560 providerSessionId: ProviderSessionId.make("session-fake-cli"),
561 options: {
562 sessionId: "native-session-fake-cli",
563 model: "claude-sonnet-4-6",
564 tools: [],
565 permissionMode: "default",
566 pathToClaudeCodeExecutable: cli,
567 },
568 });
569 });
570
571describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI process", () => {
572 // The leftover child holds a FIFO open; its death produces EOF without polling.
573 it.effect("stops what the CLI left running when the session closes", () =>
574 Effect.gen(function* () {
575 const cli = fakeClaudeCli(
576 [
577 'dir=$(dirname "$0")',
578 'sleep 600 > "$dir/alive" &',
579 'echo $! > "$dir/leftover.pid"',
580 "cat > /dev/null",
581 ].join("\n"),
582 );
583 const dir = NodePath.dirname(cli);
584 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
585 yield* Effect.addFinalizer(() =>
586 Effect.sync(() => {
587 try {
588 process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
589 } catch {}
590 NodeFS.rmSync(dir, { recursive: true, force: true });
591 }),
592 );
593 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
594 const leftoverStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
595 const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
596 alive.resume();
597
598 const stopped = yield* Deferred.make<string>();
599 const session = yield* openFakeCli(cli).pipe(
600 Effect.provide(
601 realQueryRunner.pipe(
602 Layer.provide(
603 Layer.succeed(AgentScope, {
604 ...AgentScope.defaultValue(),
605 wrap: ({ command, args }) =>
606 Effect.succeed({ command, args, unit: "t3code-claude-test.scope" }),
607 stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid),
608 }),
609 ),
610 ),
611 ),
612 );
613 yield* Effect.promise(() => leftoverStarted);
614 yield* session.close;
615 yield* Effect.promise(() => leftoverStopped);
616 assert.strictEqual(yield* Deferred.await(stopped), "t3code-claude-test.scope");
617 }),
618 );
619
620 // The default AgentScope is what macOS gets: no systemd scope to catch a job outside the CLI's group.
621 it.effect("stops a job the CLI started in its own process group when the session closes", () =>
622 Effect.gen(function* () {
623 const cli = fakeClaudeCli(
624 [
625 'dir=$(dirname "$0")',
626 `perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`,
627 'echo $! > "$dir/leftover.pid"',
628 "cat > /dev/null",
629 ].join("\n"),
630 );
631 const dir = NodePath.dirname(cli);
632 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
633 yield* Effect.addFinalizer(() =>
634 Effect.sync(() => {
635 try {
636 process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
637 } catch {}
638 NodeFS.rmSync(dir, { recursive: true, force: true });
639 }),
640 );
641 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
642 const leftoverStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
643 const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
644 alive.resume();
645
646 const session = yield* openFakeCli(cli).pipe(Effect.provide(realQueryRunner));
647 yield* Effect.promise(() => leftoverStarted);
648 yield* session.close;
649 yield* Effect.promise(() => leftoverStopped);
650 }),
651 );
652
653 // Live clock: the job is found by polling while the CLI runs, and the CLI exits on its own.
654 it.live("stops a job the CLI started in its own process group when the CLI exits", () =>
655 Effect.gen(function* () {
656 const cli = fakeClaudeCli(
657 [
658 'dir=$(dirname "$0")',
659 `perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`,
660 'echo $! > "$dir/leftover.pid"',
661 "sleep 3",
662 ].join("\n"),
663 );
664 const dir = NodePath.dirname(cli);
665 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
666 yield* Effect.addFinalizer(() =>
667 Effect.sync(() => {
668 try {
669 process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
670 } catch {}
671 NodeFS.rmSync(dir, { recursive: true, force: true });
672 }),
673 );
674 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
675 const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
676 alive.resume();
677
678 yield* openFakeCli(cli).pipe(Effect.provide(realQueryRunner));
679 yield* Effect.promise(() => leftoverStopped);
680 }),
681 );
682
683 const rootRefusal =
684 "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
685
686 const startupFailureMessage = (stderr: string) =>
687 Effect.gen(function* () {
688 const cli = fakeClaudeCli(`printf '%s\\n' '${stderr}' >&2\nexit 1`);
689 yield* Effect.addFinalizer(() =>
690 Effect.sync(() => NodeFS.rmSync(NodePath.dirname(cli), { recursive: true, force: true })),
691 );
692 const session = yield* openFakeCli(cli);
693 const exit = yield* Stream.runDrain(session.messages).pipe(Effect.exit);
694 assert.isTrue(Exit.isFailure(exit));
695 return Exit.isFailure(exit)
696 ? makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message
697 : "";
698 });
699
700 // Startup stderr can carry paths, tokens, or settings, so only the known
701 // refusal reaches the failure the client shows.
702 it.effect("keeps other startup stderr out of the turn failure", () =>
703 Effect.gen(function* () {
704 const surrounded = yield* startupFailureMessage(
705 `token=sk-private-123\n${rootRefusal}\nat /home/private/settings.json`,
706 );
707 assert.include(surrounded, rootRefusal);
708 assert.notInclude(surrounded, "sk-private-123");
709 assert.notInclude(surrounded, "/home/private");
710
711 const unknown = yield* startupFailureMessage("token=sk-private-123");
712 assert.notInclude(unknown, "sk-private-123");
713 }).pipe(Effect.provide(realQueryRunner)),
714 );
715
716 // The CLI keeps running its turn after its pipes close, so a server that
717 // crashed would leave it working next to the session it resumes.
718 it.effect("stops the CLI when the server that started it goes away", () =>
719 Effect.gen(function* () {
720 const cli = fakeClaudeCli(['dir=$(dirname "$0")', 'sleep 600 > "$dir/alive"'].join("\n"));
721 const dir = NodePath.dirname(cli);
722 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
723 const child = spawnClaudeProcessGroup({
724 command: cli,
725 args: [],
726 cwd: dir,
727 env: process.env,
728 // @effect-diagnostics-next-line abortControllerInEffect:off - This crash fixture closes pipes itself; aborting on test teardown raises an unrelated process error.
729 signal: new AbortController().signal,
730 }) as NodeChildProcess.ChildProcess;
731 yield* Effect.addFinalizer(() =>
732 Effect.sync(() => {
733 try {
734 signalProcessGroup(child.pid ?? 0, "SIGKILL");
735 } catch {}
736 NodeFS.rmSync(dir, { recursive: true, force: true });
737 }),
738 );
739 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
740 const turnStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
741 const turnStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
742 alive.resume();
743 yield* Effect.promise(() => turnStarted);
744
745 // A dying server's descriptors close; the kernel would do this for it.
746 for (const pipe of child.stdio) pipe?.destroy();
747 yield* Effect.promise(() => turnStopped);
748 }),
749 );
750
751 // A native cwd makes libuv wait for chdir, which a hung mount stalls with the whole server.
752 it.effect("enters the cwd in the child, so a missing one fails the CLI and not the spawn", () =>
753 Effect.gen(function* () {
754 const cli = fakeClaudeCli('pwd -P > "$(dirname "$0")/cwd"');
755 const dir = NodePath.dirname(cli);
756 const workspace = NodePath.join(dir, "work space");
757 NodeFS.mkdirSync(workspace);
758 yield* Effect.addFinalizer(() =>
759 Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
760 );
761 const exitCode = (cwd: string) =>
762 Effect.promise(
763 () =>
764 new Promise<number | null>((resolve) =>
765 spawnClaudeProcessGroup({
766 command: cli,
767 args: [],
768 cwd,
769 env: process.env,
770 signal: new AbortController().signal,
771 }).once("exit", resolve),
772 ),
773 );
774 assert.equal(yield* exitCode(workspace), 0);
775 assert.equal(
776 NodeFS.readFileSync(NodePath.join(dir, "cwd"), "utf8"),
777 `${NodeFS.realpathSync(workspace)}\n`,
778 );
779 assert.equal(yield* exitCode(NodePath.join(dir, "missing")), 125);
780 }),
781 );
782
783 // A restarted server reaps recorded CLIs, so a CLI must never run before its record exists.
784 it.effect("records the CLI before it runs and forgets it once it exits", () =>
785 Effect.gen(function* () {
786 const cli = fakeClaudeCli(
787 ['dir=$(dirname "$0")', 'printf \'%s %s\' "$$" "$(cat "$dir/record")" > "$dir/seen"'].join(
788 "\n",
789 ),
790 );
791 const dir = NodePath.dirname(cli);
792 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "seen")]);
793 yield* Effect.addFinalizer(() =>
794 Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
795 );
796 const forgotten = yield* Deferred.make<void>();
797 let registered = 0;
798 spawnClaudeProcessGroup(
799 {
800 command: cli,
801 args: [],
802 cwd: dir,
803 env: process.env,
804 // @effect-diagnostics-next-line abortControllerInEffect:off - The CLI exits on its own.
805 signal: new AbortController().signal,
806 },
807 undefined,
808 undefined,
809 undefined,
810 (pid) => {
811 registered = pid;
812 NodeFS.writeFileSync(NodePath.join(dir, "record"), String(pid));
813 return () => Deferred.doneUnsafe(forgotten, Effect.void);
814 },
815 );
816 const seen = yield* Effect.promise(() =>
817 NodeFS.promises.readFile(NodePath.join(dir, "seen"), "utf8"),
818 );
819 assert.equal(seen, `${registered} ${registered}`);
820 yield* Deferred.await(forgotten);
821 }),
822 );
823
824 it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => {
825 let runningAgents = 0;
826 let releaseAgent!: () => void;
827 const agentReleased = new Promise<void>((resolve) => (releaseAgent = resolve));
828 const runner = layerQueryRunner.pipe(
829 Layer.provide(
830 Layer.mock(PortScanner.PortDiscovery)({
831 trackAgent: () => {
832 runningAgents += 1;
833 return () => {
834 runningAgents -= 1;
835 releaseAgent();
836 };
837 },
838 }),
839 ),
840 Layer.provide(
841 Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined }),
842 ),
843 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
844 );
845 return Effect.gen(function* () {
846 const cli = fakeClaudeCli(
847 [
848 'dir=$(dirname "$0")',
849 `printf '%s' "$${PortScanner.AGENT_THREAD_ENV}" > "$dir/thread"`,
850 "cat > /dev/null",
851 ].join("\n"),
852 );
853 const dir = NodePath.dirname(cli);
854 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "thread")]);
855 yield* Effect.addFinalizer(() =>
856 Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
857 );
858 const threadRead = new Promise<string>((resolve) => {
859 let thread = "";
860 NodeFS.createReadStream(NodePath.join(dir, "thread"), "utf8")
861 .on("data", (chunk) => (thread += chunk))
862 .once("end", () => resolve(thread));
863 });
864
865 const session = yield* openFakeCli(cli);
866 assert.equal(yield* Effect.promise(() => threadRead), "thread-fake-cli");
867 assert.equal(runningAgents, 1);
868 yield* session.close;
869 yield* Effect.promise(() => agentReleased);
870 assert.equal(runningAgents, 0);
871 }).pipe(Effect.provide(runner));
872 });
873});