Skip to content

Commit a21dfeb

Browse files
committed
fix(server): settle Claude turns when the CLI exits
1 parent bb4afa5 commit a21dfeb

3 files changed

Lines changed: 93 additions & 14 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2585,6 +2585,10 @@ function makeFakeClaudeCli(answerSetServers = true) {
25852585
const spawns: Array<SpawnOptions> = [];
25862586
const controlRequests: Array<object> = [];
25872587
const stdins: Array<NodeStream.PassThrough> = [];
2588+
const processes: Array<{
2589+
readonly stdout: NodeStream.PassThrough;
2590+
readonly exit: (code: number, endStdout: boolean) => void;
2591+
}> = [];
25882592
const spawn = (options: SpawnOptions): SpawnedProcess => {
25892593
spawns.push(options);
25902594
const stdin = new NodeStream.PassThrough();
@@ -2601,6 +2605,14 @@ function makeFakeClaudeCli(answerSetServers = true) {
26012605
return true;
26022606
},
26032607
});
2608+
processes.push({
2609+
stdout,
2610+
exit: (code, endStdout) => {
2611+
child.exitCode = code;
2612+
child.emit("exit", code, null);
2613+
if (endStdout) stdout.end();
2614+
},
2615+
});
26042616
let pending = "";
26052617
stdin.on("data", (chunk: Buffer) => {
26062618
pending += chunk.toString("utf8");
@@ -2626,10 +2638,10 @@ function makeFakeClaudeCli(answerSetServers = true) {
26262638
return child;
26272639
};
26282640
const closed = () => stdins.length > 0 && stdins.every((stdin) => stdin.writableEnded);
2629-
return { spawn, spawns, controlRequests, closed };
2641+
return { spawn, spawns, controlRequests, closed, processes };
26302642
}
26312643

2632-
describe("ClaudeAdapterV2 MCP credential channel", () => {
2644+
describe("ClaudeAdapterV2 SDK query runner", () => {
26332645
const t3McpServer = {
26342646
type: "http" as const,
26352647
url: "http://127.0.0.1:43123/mcp",
@@ -2667,6 +2679,55 @@ describe("ClaudeAdapterV2 MCP credential channel", () => {
26672679
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
26682680
);
26692681

2682+
it.effect.each([0, 1])(
2683+
"fails the message stream when the child exits %s but stdout stays open",
2684+
(code) =>
2685+
Effect.gen(function* () {
2686+
const cli = makeFakeClaudeCli();
2687+
const session = yield* openWith(cli);
2688+
const completed =
2689+
yield* Deferred.make<Exit.Exit<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>>();
2690+
yield* session.messages.pipe(
2691+
Stream.runDrain,
2692+
Effect.exit,
2693+
Effect.flatMap((exit) => Deferred.succeed(completed, exit)),
2694+
Effect.forkChild,
2695+
);
2696+
cli.processes[0]!.exit(code, false);
2697+
yield* TestClock.adjust("2 seconds");
2698+
2699+
assert.isTrue(yield* Deferred.isDone(completed));
2700+
const exit = yield* Deferred.await(completed);
2701+
assert.isTrue(Exit.isFailure(exit));
2702+
if (Exit.isFailure(exit)) {
2703+
assert.equal(
2704+
makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message,
2705+
"Claude Code exited before its message stream closed. Retry the turn.",
2706+
);
2707+
}
2708+
yield* session.close;
2709+
}),
2710+
);
2711+
2712+
it.effect("drains buffered messages when the child exits before stream consumption", () =>
2713+
Effect.gen(function* () {
2714+
const cli = makeFakeClaudeCli();
2715+
const session = yield* openWith(cli);
2716+
const message: SDKMessage = {
2717+
type: "system",
2718+
subtype: "status",
2719+
status: null,
2720+
uuid: "00000000-0000-4000-8000-000000000001",
2721+
session_id: "native-thread-claude-mcp-channel",
2722+
};
2723+
cli.processes[0]!.stdout.write(`${JSON.stringify(message)}\n`);
2724+
cli.processes[0]!.exit(0, true);
2725+
2726+
assert.deepEqual(yield* session.messages.pipe(Stream.runCollect), [message]);
2727+
yield* session.close;
2728+
}),
2729+
);
2730+
26702731
it.effect("commits queued delivery before interruptible protocol logging", () =>
26712732
Effect.gen(function* () {
26722733
const logging = yield* Deferred.make<void>();

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,8 @@ const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
338338
const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
339339
// The process group is killed on exit, so its stderr closes promptly.
340340
const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
341+
// Process exit can precede buffered SDK messages, but descendants can keep stdout open forever.
342+
const CLAUDE_QUERY_EXIT_DRAIN_TIMEOUT = Duration.seconds(1);
341343
// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
342344
const CLAUDE_ROOT_REFUSAL =
343345
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
@@ -576,6 +578,15 @@ export class ClaudeCodeRootRefusalError extends Schema.TaggedError<ClaudeCodeRoo
576578
}
577579
}
578580

581+
class ClaudeProcessExitError extends Schema.TaggedError<ClaudeProcessExitError>()(
582+
"ClaudeProcessExitError",
583+
{},
584+
) {
585+
override get message(): string {
586+
return "Claude Code exited before its message stream closed. Retry the turn.";
587+
}
588+
}
589+
579590
class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError<ClaudeMcpRegistrationTimeoutError>()(
580591
"ClaudeMcpRegistrationTimeoutError",
581592
{},
@@ -1060,7 +1071,7 @@ export const layerQueryRunner: Layer.Layer<
10601071
});
10611072
let spawnedProcess: ClaudeSpawnedProcess | undefined;
10621073
let processExited = false;
1063-
let processExit: Promise<void> | undefined;
1074+
const processExit = Promise.withResolvers<void>();
10641075
const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
10651076
const child = spawnProcess(spawnOptions);
10661077
spawnedProcess = child;
@@ -1069,14 +1080,12 @@ export const layerQueryRunner: Layer.Layer<
10691080
child.once("exit", releaseAgent);
10701081
child.on("error", releaseAgent);
10711082
processExited = child.exitCode !== null || child.signalCode != null;
1072-
processExit = new Promise<void>((resolve) => {
1073-
if (processExited) resolve();
1074-
else
1075-
child.once("exit", () => {
1076-
processExited = true;
1077-
resolve();
1078-
});
1079-
});
1083+
if (processExited) processExit.resolve();
1084+
else
1085+
child.once("exit", () => {
1086+
processExited = true;
1087+
processExit.resolve();
1088+
});
10801089
return child;
10811090
};
10821091
const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
@@ -1142,10 +1151,10 @@ export const layerQueryRunner: Layer.Layer<
11421151
Effect.andThen(
11431152
Effect.tryPromise({
11441153
try: async () => {
1145-
if (spawnedProcess !== undefined && !processExited) {
1146-
spawnedProcess.kill("SIGKILL");
1154+
if (spawnedProcess !== undefined) {
1155+
if (!processExited) spawnedProcess.kill("SIGKILL");
1156+
await processExit.promise;
11471157
}
1148-
await processExit;
11491158
},
11501159
catch: (cause) => queryRunnerError(cause, "close"),
11511160
}).pipe(Effect.timeout("10 seconds")),
@@ -1169,6 +1178,14 @@ export const layerQueryRunner: Layer.Layer<
11691178
claudeQueryMessages(queryRuntime),
11701179
(cause) => cause,
11711180
).pipe(
1181+
Stream.interruptWhen(
1182+
Effect.promise(() => processExit.promise).pipe(
1183+
Effect.andThen(Effect.sleep(CLAUDE_QUERY_EXIT_DRAIN_TIMEOUT)),
1184+
Effect.andThen(
1185+
Effect.fail(queryRunnerError(new ClaudeProcessExitError(), "processExit")),
1186+
),
1187+
),
1188+
),
11721189
Stream.catch((cause) =>
11731190
Stream.fromEffect(
11741191
Effect.gen(function* () {

‎packages/provider-core/src/server/failure.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ function curatedCauseMessages(cause: unknown): {
112112
case "ClaudeSettingsLaunchArgError":
113113
case "ClaudeMcpRegistrationTimeoutError":
114114
case "ClaudeCodeRootRefusalError":
115+
case "ClaudeProcessExitError":
115116
case "CursorModelUnavailableError":
116117
case "CodexGoalObjectiveTooLongError":
117118
case "ProviderSetupError":

0 commit comments

Comments
 (0)