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

ClaudeAgentSdkQueryRunner.test.ts

1,271 lines50.5 KB

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