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

ClaudeAgentSdkQueryRunner.test.ts

675 lines27.0 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 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 = process.env.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(process.env.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.scoped(
236 Effect.gen(function* () {
237 const registrationStarted = Promise.withResolvers<void>();
238 const disposalStarted = Promise.withResolvers<void>();
239 const finishDisposal = Promise.withResolvers<void>();
240 const prompts: AsyncIterable<ClaudeSdk.SDKUserMessage>[] = [];
241 const firstClose = vi.fn();
242 const secondClose = vi.fn();
243 const firstRegistration = vi.fn(() => {
244 registrationStarted.resolve();
245 return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
246 });
247 const secondRegistration = vi.fn(async () => ({
248 added: ["t3-code"],
249 removed: [],
250 errors: {},
251 }));
252 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ prompt }) => {
253 assert.notTypeOf(prompt, "string");
254 if (typeof prompt === "string") throw new Error("Expected streaming input");
255 prompts.push(prompt);
256 return {
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);
299​
300it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) =>
301 Effect.scoped(
302 Effect.gen(function* () {
303 const registrationStarted = Promise.withResolvers<void>();
304 const cleanupProgress = Promise.withResolvers<"kill" | "retry">();
305 const events = new NodeEvents.EventEmitter();
306 const stdin = new NodeStream.PassThrough();
307 const stdout = new NodeStream.PassThrough();
308 const child = {
309 stdin,
310 stdout,
311 killed: false,
312 exitCode: null,
313 kill: vi.fn(() => {
314 cleanupProgress.resolve("kill");
315 return true;
316 }),
317 on: events.on.bind(events),
318 once: events.once.bind(events),
319 off: events.off.bind(events),
320 } satisfies ClaudeSdk.SpawnedProcess;
321 const signal = yield* Effect.abortSignal;
322 const disposed = vi.fn(async () => {});
323 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
324 const first = querySpy.mock.calls.length === 1;
325 if (first) {
326 options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal });
327 } else {
328 cleanupProgress.resolve("retry");
329 }
330 return {
331 setMcpServers: () => {
332 registrationStarted.resolve();
333 return first
334 ? new Promise<ClaudeSdk.McpSetServersResult>(() => {})
335 : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} });
336 },
337 close: vi.fn(),
338 [Symbol.asyncDispose]: disposed,
339 } as unknown as ClaudeSdk.Query;
340 });
341 yield* Effect.addFinalizer(() =>
342 Effect.sync(() => {
343 querySpy.mockRestore();
344 stdin.destroy();
345 stdout.destroy();
346 }),
347 );
348 const runner = yield* ClaudeAgentSdkQueryRunner;
349 const opening = yield* runner
350 .open({
351 ...resumedMcpQueryInput,
352 options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child },
353 })
354 .pipe(Effect.exit, Effect.forkChild);
355 yield* Effect.promise(() => registrationStarted.promise);
356 yield* TestClock.adjust("90 seconds");
357​
358 assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill");
359 assert.equal(querySpy.mock.calls.length, 1);
360 assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]);
361 if (exits) events.emit("exit", null, "SIGKILL");
362 else yield* TestClock.adjust("10 seconds");
363 const result = yield* Fiber.join(opening);
364 assert.equal(Exit.isSuccess(result), exits);
365 if (Exit.isSuccess(result)) yield* result.value.close;
366 assert.equal(querySpy.mock.calls.length, exits ? 2 : 1);
367 assert.equal(disposed.mock.calls.length, 1);
368 }).pipe(Effect.provide(realQueryRunner)),
369 ),
370);
371​
372it.effect("stops retrying MCP registration after two timeouts and reports the cause", () =>
373 Effect.scoped(
374 Effect.gen(function* () {
375 const firstRegistration = Promise.withResolvers<void>();
376 const secondRegistration = Promise.withResolvers<void>();
377 const disposed = vi.fn(async () => {});
378 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
379 const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration;
380 return {
381 setMcpServers: () => {
382 started.resolve();
383 return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
384 },
385 [Symbol.asyncDispose]: disposed,
386 } as unknown as ClaudeSdk.Query;
387 });
388 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
389 const runner = yield* ClaudeAgentSdkQueryRunner;
390 const opening = yield* runner
391 .open(resumedMcpQueryInput)
392 .pipe(Effect.result, Effect.forkChild);
393 yield* Effect.promise(() => firstRegistration.promise);
394 yield* TestClock.adjust("90 seconds");
395 yield* Effect.promise(() => secondRegistration.promise);
396 yield* TestClock.adjust("90 seconds");
397 const result = yield* Fiber.join(opening);
398​
399 assert.equal(result._tag, "Failure");
400 if (result._tag !== "Failure") return;
401 assert.equal(querySpy.mock.calls.length, 2);
402 assert.equal(disposed.mock.calls.length, 2);
403 assert.equal(
404 makeProviderFailure({
405 cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
406 }).message,
407 "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.",
408 );
409 }).pipe(Effect.provide(realQueryRunner)),
410 ),
411);
412​
413it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () =>
414 Effect.scoped(
415 Effect.gen(function* () {
416 const registrationStarted = Promise.withResolvers<void>();
417 const disposed = vi.fn(async () => {});
418 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
419 () =>
420 ({
421 setMcpServers: () => {
422 registrationStarted.resolve();
423 return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
424 },
425 [Symbol.asyncDispose]: disposed,
426 }) as unknown as ClaudeSdk.Query,
427 );
428 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
429 const runner = yield* ClaudeAgentSdkQueryRunner;
430 const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild);
431 yield* Effect.promise(() => registrationStarted.promise);
432 yield* Fiber.interrupt(opening);
433​
434 assert.equal(querySpy.mock.calls.length, 1);
435 assert.equal(disposed.mock.calls.length, 1);
436 const prompt = querySpy.mock.calls[0]![0].prompt;
437 if (typeof prompt === "string") throw new Error("Expected streaming input");
438 assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done);
439 }).pipe(Effect.provide(realQueryRunner)),
440 ),
441);
442​
443it.effect("does not reuse a fresh session ID after MCP registration times out", () =>
444 Effect.scoped(
445 Effect.gen(function* () {
446 const registrationStarted = Promise.withResolvers<void>();
447 const disposed = vi.fn(async () => {});
448 const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
449 () =>
450 ({
451 setMcpServers: () => {
452 registrationStarted.resolve();
453 return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
454 },
455 [Symbol.asyncDispose]: disposed,
456 }) as unknown as ClaudeSdk.Query,
457 );
458 yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
459 const runner = yield* ClaudeAgentSdkQueryRunner;
460 const { resume, ...options } = resumedMcpQueryInput.options;
461 const opening = yield* runner
462 .open({
463 ...resumedMcpQueryInput,
464 options: { ...options, sessionId: resume },
465 })
466 .pipe(Effect.result, Effect.forkChild);
467 yield* Effect.promise(() => registrationStarted.promise);
468 yield* TestClock.adjust("90 seconds");
469 const result = yield* Fiber.join(opening);
470​
471 assert.equal(result._tag, "Failure");
472 assert.equal(querySpy.mock.calls.length, 1);
473 assert.equal(disposed.mock.calls.length, 1);
474 }).pipe(Effect.provide(realQueryRunner)),
475 ),
476);
477​
478function fakeClaudeCli(script: string): string {
479 const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-"));
480 const cli = NodePath.join(dir, "claude");
481 NodeFS.writeFileSync(cli, `#!/bin/sh\n${script}\n`, { mode: 0o755 });
482 return cli;
484​
485const openFakeCli = (cli: string) =>
486 Effect.gen(function* () {
487 const runner = yield* ClaudeAgentSdkQueryRunner;
488 return yield* runner.open({
489 threadId: ThreadId.make("thread-fake-cli"),
490 providerSessionId: ProviderSessionId.make("session-fake-cli"),
491 options: {
492 sessionId: "native-session-fake-cli",
493 model: "claude-sonnet-4-6",
494 tools: [],
495 permissionMode: "default",
496 pathToClaudeCodeExecutable: cli,
497 },
498 });
499 });
500​
501describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI process", () => {
502 // The leftover child holds a FIFO open; its death produces EOF without polling.
503 it.effect("stops what the CLI left running when the session closes", () =>
504 Effect.gen(function* () {
505 const cli = fakeClaudeCli(
506 [
507 'dir=$(dirname "$0")',
508 'sleep 600 > "$dir/alive" &',
509 'echo $! > "$dir/leftover.pid"',
510 "cat > /dev/null",
511 ].join("\n"),
512 );
513 const dir = NodePath.dirname(cli);
514 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
515 yield* Effect.addFinalizer(() =>
516 Effect.sync(() => {
517 try {
518 process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
519 } catch {}
520 NodeFS.rmSync(dir, { recursive: true, force: true });
521 }),
522 );
523 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
524 const leftoverStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
525 const leftoverStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
526 alive.resume();
527​
528 const stopped = yield* Deferred.make<string>();
529 const session = yield* openFakeCli(cli).pipe(
530 Effect.provide(
531 realQueryRunner.pipe(
532 Layer.provide(
533 Layer.succeed(AgentScope, {
534 ...AgentScope.defaultValue(),
535 wrap: ({ command, args }) =>
536 Effect.succeed({ command, args, unit: "t3code-claude-test.scope" }),
537 stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid),
538 }),
539 ),
540 ),
541 ),
542 );
543 yield* Effect.promise(() => leftoverStarted);
544 yield* session.close;
545 yield* Effect.promise(() => leftoverStopped);
546 assert.strictEqual(yield* Deferred.await(stopped), "t3code-claude-test.scope");
547 }),
548 );
549​
550 const rootRefusal =
551 "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
552​
553 const startupFailureMessage = (stderr: string) =>
554 Effect.gen(function* () {
555 const cli = fakeClaudeCli(`printf '%s\\n' '${stderr}' >&2\nexit 1`);
556 yield* Effect.addFinalizer(() =>
557 Effect.sync(() => NodeFS.rmSync(NodePath.dirname(cli), { recursive: true, force: true })),
558 );
559 const session = yield* openFakeCli(cli);
560 const exit = yield* Stream.runDrain(session.messages).pipe(Effect.exit);
561 assert.isTrue(Exit.isFailure(exit));
562 return Exit.isFailure(exit)
563 ? makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message
564 : "";
565 });
566​
567 // Claude Code refuses bypassPermissions as root and explains why only on
568 // stderr, so the turn failure has to carry that line.
569 it.effect("reports the CLI's root refusal when it exits before answering", () =>
570 Effect.gen(function* () {
571 assert.include(yield* startupFailureMessage(rootRefusal), rootRefusal);
572 }).pipe(Effect.provide(realQueryRunner)),
573 );
574​
575 // Startup stderr can carry paths, tokens, or settings, so only the known
576 // refusal reaches the failure the client shows.
577 it.effect("keeps other startup stderr out of the turn failure", () =>
578 Effect.gen(function* () {
579 const surrounded = yield* startupFailureMessage(
580 `token=sk-private-123\n${rootRefusal}\nat /home/private/settings.json`,
581 );
582 assert.include(surrounded, rootRefusal);
583 assert.notInclude(surrounded, "sk-private-123");
584 assert.notInclude(surrounded, "/home/private");
585​
586 const unknown = yield* startupFailureMessage("token=sk-private-123");
587 assert.notInclude(unknown, "sk-private-123");
588 }).pipe(Effect.provide(realQueryRunner)),
589 );
590​
591 // The CLI keeps running its turn after its pipes close, so a server that
592 // crashed would leave it working next to the session it resumes.
593 it.effect("stops the CLI when the server that started it goes away", () =>
594 Effect.gen(function* () {
595 const cli = fakeClaudeCli(['dir=$(dirname "$0")', 'sleep 600 > "$dir/alive"'].join("\n"));
596 const dir = NodePath.dirname(cli);
597 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
598 const child = spawnClaudeProcessGroup({
599 command: cli,
600 args: [],
601 cwd: dir,
602 env: process.env,
603 // @effect-diagnostics-next-line abortControllerInEffect:off - This crash fixture closes pipes itself; aborting on test teardown raises an unrelated process error.
604 signal: new AbortController().signal,
605 }) as NodeChildProcess.ChildProcess;
606 yield* Effect.addFinalizer(() =>
607 Effect.sync(() => {
608 try {
609 signalProcessGroup(child.pid ?? 0, "SIGKILL");
610 } catch {}
611 NodeFS.rmSync(dir, { recursive: true, force: true });
612 }),
613 );
614 const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
615 const turnStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));
616 const turnStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));
617 alive.resume();
618 yield* Effect.promise(() => turnStarted);
619​
620 // A dying server's descriptors close; the kernel would do this for it.
621 for (const pipe of child.stdio) pipe?.destroy();
622 yield* Effect.promise(() => turnStopped);
623 }),
624 );
625​
626 it.effect("marks the CLI's jobs with its thread and counts it as an agent until it exits", () => {
627 let runningAgents = 0;
628 let releaseAgent!: () => void;
629 const agentReleased = new Promise<void>((resolve) => (releaseAgent = resolve));
630 const runner = layerQueryRunner.pipe(
631 Layer.provide(
632 Layer.mock(PortScanner.PortDiscovery)({
633 trackAgent: () => {
634 runningAgents += 1;
635 return () => {
636 runningAgents -= 1;
637 releaseAgent();
638 };
639 },
640 }),
641 ),
642 Layer.provide(
643 Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined }),
644 ),
645 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
646 );
647 return Effect.gen(function* () {
648 const cli = fakeClaudeCli(
649 [
650 'dir=$(dirname "$0")',
651 `printf '%s' "$${PortScanner.AGENT_THREAD_ENV}" > "$dir/thread"`,
652 "cat > /dev/null",
653 ].join("\n"),
654 );
655 const dir = NodePath.dirname(cli);
656 NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "thread")]);
657 yield* Effect.addFinalizer(() =>
658 Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })),
659 );
660 const threadRead = new Promise<string>((resolve) => {
661 let thread = "";
662 NodeFS.createReadStream(NodePath.join(dir, "thread"), "utf8")
663 .on("data", (chunk) => (thread += chunk))
664 .once("end", () => resolve(thread));
665 });
666​
667 const session = yield* openFakeCli(cli);
668 assert.equal(yield* Effect.promise(() => threadRead), "thread-fake-cli");
669 assert.equal(runningAgents, 1);
670 yield* session.close;
671 yield* Effect.promise(() => agentReleased);
672 assert.equal(runningAgents, 0);
673 }).pipe(Effect.provide(runner));
674 });
675});