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