TypeScript
fix(server): a Claude agent stops when the server that started it dies (#23389)
shivam5ffe04593166
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex 97ebde00ac2..49b344961b3 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -314,26 +314,41 @@ const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;// subagents to move to the background before it is sent.const BACKGROUND_MOVE_TIMEOUT_MS = 5_000;+const CLAUDE_GROUP_WATCH_SCRIPT = [+ "{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",+ 'exec "$@" 3<&-',+].join("\n");+/*** When the CLI exits it stops the MCP servers it started, but not their children: a plugin's* `bun run start` wrapper dies and its `bun server.ts` keeps running, writing to a pipe nobody* reads (#3089). Those stay in the CLI's group, so the rest of the group gets SIGKILL once the* CLI exits for any reason.+ *+ * That cleanup needs this server alive, and the CLI finishes its turn after its pipes close. A+ * server that crashes or is killed would leave the CLI working next to the session it resumes+ * (#23370), so a watcher in the group reads a pipe only this server holds and stops the group at+ * its end-of-file.*/-function spawnClaudeProcessGroup(options: ClaudeSpawnOptions): ClaudeSpawnedProcess {- const child = NodeChildProcess.spawn(options.command, options.args, {- cwd: options.cwd,- env: options.env,- signal: options.signal,- stdio: ["pipe", "pipe", "ignore"],- detached: true,- });+export function spawnClaudeProcessGroup(options: ClaudeSpawnOptions): ClaudeSpawnedProcess {+ const child = NodeChildProcess.spawn(+ "/bin/sh",+ ["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args],+ {+ cwd: options.cwd,+ env: options.env,+ signal: options.signal,+ stdio: ["pipe", "pipe", "ignore", "pipe"],+ detached: true,+ },+ );child.once("exit", () => {try {signalProcessGroup(child.pid ?? 0, "SIGKILL");} catch {}});- return child;+ // Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.+ return child as ClaudeSpawnedProcess;}export const ClaudeProviderCapabilitiesV2 = {diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.tsindex d5c9686bb8d..248e78a1796 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts@@ -15,7 +15,12 @@ import { vi } from "vite-plus/test";import * as HostProcess from "@t3tools/shared/HostProcess";import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";-import { ClaudeAgentSdkQueryRunner, layerQueryRunner } from "./ClaudeAdapterV2.ts";+import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";+import {+ ClaudeAgentSdkQueryRunner,+ layerQueryRunner,+ spawnClaudeProcessGroup,+} from "./ClaudeAdapterV2.ts";vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });@@ -163,4 +168,38 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI proyield* Effect.promise(() => leftoverStopped);}).pipe(Effect.provide(realQueryRunner)),);++ // The CLI keeps running its turn after its pipes close, so a server that+ // crashed would leave it working next to the session it resumes (#23370).+ it.effect("stops the CLI when the server that started it goes away", () =>+ Effect.gen(function* () {+ const cli = fakeClaudeCli(['dir=$(dirname "$0")', 'sleep 600 > "$dir/alive"'].join("\n"));+ const dir = NodePath.dirname(cli);+ NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);+ const child = spawnClaudeProcessGroup({+ command: cli,+ args: [],+ cwd: dir,+ env: process.env,+ signal: new AbortController().signal,+ }) as NodeChildProcess.ChildProcess;+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => {+ try {+ signalProcessGroup(child.pid ?? 0, "SIGKILL");+ } catch {}+ NodeFS.rmSync(dir, { recursive: true, force: true });+ }),+ );+ const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));+ const turnStarted = new Promise<void>((resolve) => alive.once("open", () => resolve()));+ const turnStopped = new Promise<void>((resolve) => alive.once("close", () => resolve()));+ alive.resume();+ yield* Effect.promise(() => turnStarted);++ // A dying server's descriptors close; the kernel would do this for it.+ for (const pipe of child.stdio) pipe?.destroy();+ yield* Effect.promise(() => turnStopped);+ }),+ );});