Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 76 additions & 2 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2826,6 +2826,10 @@ function makeFakeClaudeCli(answerSetServers = true) {
const spawns: Array<SpawnOptions> = [];
const controlRequests: Array<object> = [];
const stdins: Array<NodeStream.PassThrough> = [];
const processes: Array<{
readonly stdout: NodeStream.PassThrough;
readonly exit: (code: number, endStdout: boolean) => void;
}> = [];
const spawn = (options: SpawnOptions): SpawnedProcess => {
spawns.push(options);
const stdin = new NodeStream.PassThrough();
Expand All @@ -2842,6 +2846,14 @@ function makeFakeClaudeCli(answerSetServers = true) {
return true;
},
});
processes.push({
stdout,
exit: (code, endStdout) => {
child.exitCode = code;
child.emit("exit", code, null);
if (endStdout) stdout.end();
},
});
let pending = "";
stdin.on("data", (chunk: Buffer) => {
pending += chunk.toString("utf8");
Expand All @@ -2867,10 +2879,10 @@ function makeFakeClaudeCli(answerSetServers = true) {
return child;
};
const closed = () => stdins.length > 0 && stdins.every((stdin) => stdin.writableEnded);
return { spawn, spawns, controlRequests, closed };
return { spawn, spawns, controlRequests, closed, processes };
}

describe("ClaudeAdapterV2 MCP credential channel", () => {
describe("ClaudeAdapterV2 SDK query runner", () => {
const t3McpServer = {
type: "http" as const,
url: "http://127.0.0.1:43123/mcp",
Expand Down Expand Up @@ -2908,6 +2920,68 @@ describe("ClaudeAdapterV2 MCP credential channel", () => {
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
);

it.effect.each([0, 1])(
"fails the message stream when the child exits %s but stdout stays open",
(code) =>
Effect.gen(function* () {
const cli = makeFakeClaudeCli();
const session = yield* openWith(cli);
const completed =
yield* Deferred.make<Exit.Exit<void, ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError>>();
yield* session.messages.pipe(
Stream.runDrain,
Effect.exit,
Effect.flatMap((exit) => Deferred.succeed(completed, exit)),
Effect.forkChild,
);
cli.processes[0]!.exit(code, false);
yield* TestClock.adjust("2 seconds");

assert.isTrue(yield* Deferred.isDone(completed));
const exit = yield* Deferred.await(completed);
assert.isTrue(Exit.isFailure(exit));
if (Exit.isFailure(exit)) {
assert.equal(
makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message,
"Claude Code exited before its message stream closed. Retry the turn.",
);
}
yield* session.close;
}),
);

it.effect.each([false, true])("drains messages written after process exit: %s", (afterExit) =>
Effect.gen(function* () {
const cli = makeFakeClaudeCli();
const session = yield* openWith(cli);
const message: SDKMessage = {
type: "system",
subtype: "status",
status: null,
uuid: "00000000-0000-4000-8000-000000000001",
session_id: "native-thread-claude-mcp-channel",
};
const collected = afterExit
? yield* session.messages.pipe(Stream.runCollect, Effect.forkChild)
: undefined;
if (afterExit) {
cli.processes[0]!.exit(0, false);
yield* TestClock.adjust("500 millis");
}
cli.processes[0]!.stdout.write(`${JSON.stringify(message)}\n`);
if (afterExit) cli.processes[0]!.stdout.end();
else cli.processes[0]!.exit(0, true);

assert.deepEqual(
collected === undefined
? yield* session.messages.pipe(Stream.runCollect)
: yield* Fiber.join(collected),
[message],
);
yield* session.close;
}),
);

it.effect("commits queued delivery before interruptible protocol logging", () =>
Effect.gen(function* () {
const logging = yield* Deferred.make<void>();
Expand Down
48 changes: 36 additions & 12 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,8 @@ const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
// The process group is killed on exit, so its stderr closes promptly.
const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
// Process exit can precede buffered SDK messages, but descendants can keep stdout open forever.
const CLAUDE_QUERY_EXIT_DRAIN_TIMEOUT = Duration.seconds(1);
// How often the CLI's process tree is recorded when no agent scope will stop what it leaves.
const CLAUDE_DESCENDANT_POLL = "1 second";
// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
Expand Down Expand Up @@ -675,6 +677,15 @@ export class ClaudeCodeRootRefusalError extends Schema.TaggedError<ClaudeCodeRoo
}
}

class ClaudeProcessExitError extends Schema.TaggedError<ClaudeProcessExitError>()(
"ClaudeProcessExitError",
{},
) {
override get message(): string {
return "Claude Code exited before its message stream closed. Retry the turn.";
}
}

class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError<ClaudeMcpRegistrationTimeoutError>()(
"ClaudeMcpRegistrationTimeoutError",
{ phase: Schema.Literals(["initialize", "setMcpServers"]) },
Expand Down Expand Up @@ -1391,23 +1402,28 @@ export const layerQueryRunner: Layer.Layer<
});
let spawnedProcess: ClaudeSpawnedProcess | undefined;
let processExited = false;
let processExit: Promise<void> | undefined;
const processExit = Promise.withResolvers<void>();
const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
const child = spawnProcess(spawnOptions);
spawnedProcess = child;
// A spawn that fails emits only "error".
const releaseAgent = portDiscovery.trackAgent();
child.once("exit", releaseAgent);
child.on("error", releaseAgent);
processExited = child.exitCode !== null || child.signalCode != null;
processExit = new Promise<void>((resolve) => {
if (processExited) resolve();
else
child.once("exit", () => {
processExited = true;
resolve();
});
child.once("error", () => {
// A failed spawn emits no exit event and never receives a pid.
if ("pid" in child && child.pid === undefined) {
processExited = true;
processExit.resolve();
}
});
processExited = child.exitCode !== null || child.signalCode != null;
if (processExited) processExit.resolve();
else
child.once("exit", () => {
processExited = true;
processExit.resolve();
Comment thread
maria-rcks marked this conversation as resolved.
Resolved
});
return child;
};
const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
Expand Down Expand Up @@ -1486,10 +1502,10 @@ export const layerQueryRunner: Layer.Layer<
Effect.andThen(
Effect.tryPromise({
try: async () => {
if (spawnedProcess !== undefined && !processExited) {
spawnedProcess.kill("SIGKILL");
if (spawnedProcess !== undefined) {
if (!processExited) spawnedProcess.kill("SIGKILL");
await processExit.promise;
}
await processExit;
},
catch: (cause) => queryRunnerError(cause, "close"),
}).pipe(Effect.timeout("10 seconds")),
Expand All @@ -1513,6 +1529,14 @@ export const layerQueryRunner: Layer.Layer<
claudeQueryMessages(queryRuntime),
(cause) => cause,
).pipe(
Stream.interruptWhen(
Effect.promise(() => processExit.promise).pipe(
Effect.andThen(Effect.sleep(CLAUDE_QUERY_EXIT_DRAIN_TIMEOUT)),
Effect.andThen(
Effect.fail(queryRunnerError(new ClaudeProcessExitError(), "processExit")),
),
),
),
Stream.catch((cause) =>
Stream.fromEffect(
Effect.gen(function* () {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,7 @@ it.effect.each([true, false])("only retries after confirmed process exit: %s", (
const child = {
stdin,
stdout,
pid: 1234,
killed: false,
exitCode: null,
kill: vi.fn(() => {
Expand All @@ -350,7 +351,7 @@ it.effect.each([true, false])("only retries after confirmed process exit: %s", (
on: events.on.bind(events),
once: events.once.bind(events),
off: events.off.bind(events),
} satisfies ClaudeSdk.SpawnedProcess;
} satisfies ClaudeSdk.SpawnedProcess & { readonly pid: number };
const signal = yield* Effect.abortSignal;
const disposed = vi.fn(async () => {});
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
Expand Down Expand Up @@ -387,6 +388,7 @@ it.effect.each([true, false])("only retries after confirmed process exit: %s", (
})
.pipe(Effect.exit, Effect.forkChild);
yield* Effect.promise(() => registrationStarted.promise);
events.emit("error", new Error("running child error"));
yield* TestClock.adjust("90 seconds");

assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill");
Expand All @@ -403,46 +405,71 @@ it.effect.each([true, false])("only retries after confirmed process exit: %s", (
),
);

it.effect("stops retrying MCP registration after two timeouts and reports the cause", () =>
Effect.scoped(
Effect.gen(function* () {
const firstRegistration = Promise.withResolvers<void>();
const secondRegistration = Promise.withResolvers<void>();
const disposed = vi.fn(async () => {});
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration;
return {
initializationResult: async () => ({}),
setMcpServers: () => {
started.resolve();
return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
},
[Symbol.asyncDispose]: disposed,
} as unknown as ClaudeSdk.Query;
});
yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
const runner = yield* ClaudeAgentSdkQueryRunner;
const opening = yield* runner
.open(resumedMcpQueryInput)
.pipe(Effect.result, Effect.forkChild);
yield* Effect.promise(() => firstRegistration.promise);
yield* TestClock.adjust("90 seconds");
yield* Effect.promise(() => secondRegistration.promise);
yield* TestClock.adjust("90 seconds");
const result = yield* Fiber.join(opening);

assert.equal(result._tag, "Failure");
if (result._tag !== "Failure") return;
assert.equal(querySpy.mock.calls.length, 2);
assert.equal(disposed.mock.calls.length, 2);
assert.equal(
makeProviderFailure({
cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
}).message,
"Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.",
);
}).pipe(Effect.provide(realQueryRunner)),
),
it.effect.each([false, true])(
"reports MCP registration timeouts even when spawning fails: %s",
(spawnFails) =>
Effect.scoped(
Effect.gen(function* () {
const firstRegistration = Promise.withResolvers<void>();
const secondRegistration = Promise.withResolvers<void>();
const disposed = vi.fn(async () => {});
const signal = yield* Effect.abortSignal;
const kill = vi.fn(() => false);
let spawnedChild: ClaudeSdk.SpawnedProcess;
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
const child = Object.assign(new NodeEvents.EventEmitter(), {
stdin: new NodeStream.PassThrough(),
stdout: new NodeStream.PassThrough(),
pid: undefined,
killed: false,
exitCode: null,
kill,
});
spawnedChild = child;
if (spawnFails) {
options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal });
}
const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration;
return {
initializationResult: async () => ({}),
setMcpServers: () => {
if (spawnFails) child.emit("error", new Error("spawn ENOENT"));
started.resolve();
return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
},
[Symbol.asyncDispose]: disposed,
} as unknown as ClaudeSdk.Query;
});
yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
const runner = yield* ClaudeAgentSdkQueryRunner;
const opening = yield* runner
.open({
...resumedMcpQueryInput,
options: {
...resumedMcpQueryInput.options,
spawnClaudeCodeProcess: () => spawnedChild,
},
})
.pipe(Effect.result, Effect.forkChild);
yield* Effect.promise(() => firstRegistration.promise);
yield* TestClock.adjust("90 seconds");
yield* Effect.promise(() => secondRegistration.promise);
yield* TestClock.adjust("90 seconds");
const result = yield* Fiber.join(opening);

assert.equal(result._tag, "Failure");
if (result._tag !== "Failure") return;
assert.equal(querySpy.mock.calls.length, 2);
assert.equal(disposed.mock.calls.length, 2);
assert.equal(kill.mock.calls.length, 0);
assert.equal(
makeProviderFailure({
cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
}).message,
"Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.",
);
}).pipe(Effect.provide(realQueryRunner)),
),
);

it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () =>
Expand Down
1 change: 1 addition & 0 deletions packages/provider-core/src/server/failure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ function curatedCauseMessages(cause: unknown): {
case "ClaudeSettingsLaunchArgError":
case "ClaudeMcpRegistrationTimeoutError":
case "ClaudeCodeRootRefusalError":
case "ClaudeProcessExitError":
case "CursorModelUnavailableError":
case "CodexGoalObjectiveTooLongError":
case "ProviderSetupError":
Expand Down
Loading