@devries-cameron20 / t3code-1 / commits / 709cfb3a1f
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): Claude subagents left by a stopped process no longer stay Running (#28356)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 2, 2026 at 18:00 UTC 709cfb3a1f5053b975f983d8fee0515bddf5e93f
2 files changed +398 -35
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+307
@@ -11780,6 +11780,313 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11780 ),
11781 );
11782
11783 + // A Stop closes the first process, and a turn replaces it before its stream ends.
11784 + const stopRacedByReplacementTurn = (label: string) =>
11785 + Effect.gen(function* () {
11786 + const changes = yield* makeChangeSignal;
11787 + const fileSystem = yield* FileSystem.FileSystem;
11788 + const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
11789 + prefix: `t3-claude-v2-${label}-`,
11790 + });
11791 + const processQueues: Array<Queue.Queue<SDKMessage>> = [];
11792 + // The first two processes exit only when the test ends their streams.
11793 + const closeRequested = [yield* Deferred.make<void>(), yield* Deferred.make<void>()];
11794 + const events: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
11795 + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
11796 + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
11797 + settings: DEFAULT_CLAUDE_SETTINGS,
11798 + environment: {},
11799 + attachmentsDir,
11800 + fileSystem,
11801 + path: yield* Path.Path,
11802 + random: yield* SecureRandom.SecureRandom,
11803 + idAllocator: yield* IdAllocator.IdAllocatorV2,
11804 + continuationRequests: { offer: () => Effect.void },
11805 + queryRunner: {
11806 + allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
11807 + open: () =>
11808 + Effect.gen(function* () {
11809 + const sdkMessages = yield* Queue.unbounded<SDKMessage>();
11810 + const closeSignal = closeRequested[processQueues.length];
11811 + processQueues.push(sdkMessages);
11812 + return {
11813 + messages: Stream.fromQueue(sdkMessages),
11814 + offer: () => Effect.void,
11815 + setModel: () => Effect.void,
11816 + applyFlagSettings: () => Effect.void,
11817 + setPermissionMode: () => Effect.void,
11818 + backgroundTasks: () => Effect.succeed(false),
11819 + stopTask: () => Effect.void,
11820 + interrupt: Effect.void,
11821 + close:
11822 + closeSignal === undefined
11823 + ? Queue.shutdown(sdkMessages)
11824 + : Deferred.succeed(closeSignal, undefined).pipe(Effect.asVoid),
11825 + };
11826 + }),
11827 + forkSession: () => Effect.die("unused forkSession"),
11828 + subagentLaunchToolUseId: () => Effect.succeed(null),
11829 + assertComplete: Effect.void,
11830 + },
11831 + });
11832 + const threadId = ThreadId.make(`thread-claude-${label}`);
11833 + const runtime = yield* adapter.openSession({
11834 + threadId,
11835 + providerSessionId: ProviderSessionId.make(`provider-session-claude-${label}`),
11836 + modelSelection: CLAUDE_TEST_MODEL_SELECTION,
11837 + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
11838 + });
11839 + const providerThread = yield* runtime.ensureThread({
11840 + threadId,
11841 + modelSelection: CLAUDE_TEST_MODEL_SELECTION,
11842 + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
11843 + });
11844 + yield* runtime.events.pipe(
11845 + Stream.runForEach((event) =>
11846 + Effect.sync(() => {
11847 + events.push(event);
11848 + }).pipe(Effect.andThen(changes.notify)),
11849 + ),
11850 + Effect.forkScoped,
11851 + );
11852 + const terminals = () => events.filter((event) => event.type === "turn.terminal");
11853 + const subagentStatus = (taskId: string) => {
11854 + const latest = events.findLast(
11855 + (event) =>
11856 + event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === taskId,
11857 + );
11858 + return latest?.type === "subagent.updated" ? latest.subagent.status : undefined;
11859 + };
11860 + const now = yield* DateTime.now;
11861 +
11862 + yield* runtime.startTurn(
11863 + makeClaudeTestTurnInput({
11864 + threadId,
11865 + providerThread,
11866 + now,
11867 + attemptId: RunAttemptId.make(`attempt-claude-${label}-a`),
11868 + text: "Audit the last commits in the background.",
11869 + attachments: [],
11870 + }),
11871 + );
11872 + yield* Queue.offer(
11873 + processQueues[0]!,
11874 + makeSubagentTaskStartedFrame({
11875 + taskId: "raced-agent",
11876 + toolUseId: "toolu-raced-agent",
11877 + uuid: "00000000-0000-4000-8000-000000002801",
11878 + }),
11879 + );
11880 + yield* Queue.offer(
11881 + processQueues[0]!,
11882 + makeResultFrame({
11883 + uuid: "00000000-0000-4000-8000-000000002802",
11884 + result: "Launched the audit.",
11885 + }),
11886 + );
11887 + yield* changes.until(
11888 + () => terminals().length === 1 && subagentStatus("raced-agent") === "running",
11889 + );
11890 +
11891 + const stop = yield* runtime
11892 + .interruptTurn({
11893 + providerThread,
11894 + providerTurnId: terminals()[0]!.providerTurnId,
11895 + requestRuntimeRestart: true,
11896 + })
11897 + .pipe(Effect.forkScoped);
11898 + yield* Deferred.await(closeRequested[0]!);
11899 + yield* runtime.startTurn(
11900 + makeClaudeTestTurnInput({
11901 + threadId,
11902 + providerThread: { ...providerThread, status: "active" },
11903 + now,
11904 + attemptId: RunAttemptId.make(`attempt-claude-${label}-b`),
11905 + text: "Resume after the limit reset.",
11906 + attachments: [],
11907 + providerTurnOrdinal: 2,
11908 + }),
11909 + );
11910 + assert.lengthOf(processQueues, 2);
11911 + yield* Queue.offer(
11912 + processQueues[1]!,
11913 + makeSubagentTaskStartedFrame({
11914 + taskId: "own-agent",
11915 + toolUseId: "toolu-own-agent",
11916 + uuid: "00000000-0000-4000-8000-000000002804",
11917 + }),
11918 + );
11919 + yield* changes.until(() => subagentStatus("own-agent") === "running");
11920 + const exitProcess = <E>(index: number, stopping: Fiber.Fiber<void, E>) =>
11921 + Queue.shutdown(processQueues[index]!).pipe(Effect.andThen(Fiber.join(stopping)));
11922 + return {
11923 + runtime,
11924 + threadId,
11925 + providerThread,
11926 + processQueues,
11927 + closeRequested,
11928 + changes,
11929 + terminals,
11930 + subagentStatus,
11931 + exitFirstProcess: exitProcess(0, stop),
11932 + exitProcess,
11933 + now,
11934 + };
11935 + });
11936 +
11937 + // regression: #28331 a subagent whose process is gone must not stay running forever
11938 + it.effect("ends a subagent whose process a Stop closed while a new turn replaced it", () =>
11939 + Effect.scoped(
11940 + Effect.gen(function* () {
11941 + const { processQueues, changes, terminals, subagentStatus, exitFirstProcess } =
11942 + yield* stopRacedByReplacementTurn("raced-stop-replacement-close");
11943 + yield* exitFirstProcess;
11944 + // The replacement's result follows the stopped process's exit on the event stream.
11945 + yield* Queue.offer(
11946 + processQueues[1]!,
11947 + makeResultFrame({
11948 + uuid: "00000000-0000-4000-8000-000000002803",
11949 + result: "Resumed.",
11950 + }),
11951 + );
11952 + yield* changes.until(() => terminals().length === 2);
11953 +
11954 + assert.strictEqual(
11955 + subagentStatus("raced-agent"),
11956 + "cancelled",
11957 + "the Stop ended the subagent's process, but the subagent is not cancelled",
11958 + );
11959 + assert.strictEqual(
11960 + subagentStatus("own-agent"),
11961 + "running",
11962 + "the replacement process still runs its own subagent",
11963 + );
11964 + }).pipe(
11965 + Effect.provide(
11966 + Layer.mergeAll(
11967 + IdAllocator.layer,
11968 + McpProviderSessions.layer,
11969 + NodeServices.layer,
11970 + NodeCrypto.layer,
11971 + ),
11972 + ),
11973 + ),
11974 + ),
11975 + );
11976 +
11977 + // regression: #28331 Stop must clear a subagent whose process is gone
11978 + it.effect("stops a subagent whose process a Stop closed while a new turn replaced it", () =>
11979 + Effect.scoped(
11980 + Effect.gen(function* () {
11981 + const { runtime, providerThread, exitFirstProcess } = yield* stopRacedByReplacementTurn(
11982 + "raced-stop-replacement-stop-subagent",
11983 + );
11984 + yield* exitFirstProcess;
11985 + const stopped = yield* runtime.stopSubagent!({
11986 + providerThread: { ...providerThread, status: "active" },
11987 + nativeTaskId: "raced-agent",
11988 + }).pipe(
11989 + Effect.map((outcome) => outcome?.status ?? "no outcome"),
11990 + Effect.catch((error) =>
11991 + Effect.succeed(`refused: ${"detail" in error ? error.detail : error.message}`),
11992 + ),
11993 + );
11994 +
11995 + assert.strictEqual(stopped, "cancelled", "Stop of a subagent whose process is gone");
11996 + }).pipe(
11997 + Effect.provide(
11998 + Layer.mergeAll(
11999 + IdAllocator.layer,
12000 + McpProviderSessions.layer,
12001 + NodeServices.layer,
12002 + NodeCrypto.layer,
12003 + ),
12004 + ),
12005 + ),
12006 + ),
12007 + );
12008 +
12009 + // regression: #28331 a process that exits late ends only the subagents it ran
12010 + it.effect("leaves a stopping replacement's subagent to that replacement's exit", () =>
12011 + Effect.scoped(
12012 + Effect.gen(function* () {
12013 + const {
12014 + runtime,
12015 + threadId,
12016 + providerThread,
12017 + processQueues,
12018 + closeRequested,
12019 + changes,
12020 + terminals,
12021 + subagentStatus,
12022 + exitFirstProcess,
12023 + exitProcess,
12024 + now,
12025 + } = yield* stopRacedByReplacementTurn("raced-stop-replacement-chain");
12026 + const activeThread = { ...providerThread, status: "active" as const };
12027 + const finishTurn = (index: number, turns: number, uuid: string) =>
12028 + Queue.offer(processQueues[index]!, makeResultFrame({ uuid, result: "Done." })).pipe(
12029 + Effect.andThen(changes.until(() => terminals().length === turns)),
12030 + );
12031 + const startTurn = (label: string, providerTurnOrdinal: number) =>
12032 + runtime.startTurn(
12033 + makeClaudeTestTurnInput({
12034 + threadId,
12035 + providerThread: activeThread,
12036 + now,
12037 + attemptId: RunAttemptId.make(`attempt-claude-raced-stop-replacement-chain-${label}`),
12038 + text: "Carry on.",
12039 + attachments: [],
12040 + providerTurnOrdinal,
12041 + }),
12042 + );
12043 +
12044 + yield* finishTurn(1, 2, "00000000-0000-4000-8000-000000002805");
12045 + const stopSecond = yield* runtime
12046 + .interruptTurn({
12047 + providerThread: activeThread,
12048 + providerTurnId: terminals()[1]!.providerTurnId,
12049 + requestRuntimeRestart: true,
12050 + })
12051 + .pipe(Effect.forkScoped);
12052 + yield* Deferred.await(closeRequested[1]!);
12053 + yield* startTurn("c", 3);
12054 + assert.lengthOf(processQueues, 3);
12055 +
12056 + yield* exitFirstProcess;
12057 + yield* finishTurn(2, 3, "00000000-0000-4000-8000-000000002806");
12058 + assert.strictEqual(
12059 + subagentStatus("raced-agent"),
12060 + "cancelled",
12061 + "the first process exited after a Stop, but its subagent is not cancelled",
12062 + );
12063 + assert.strictEqual(
12064 + subagentStatus("own-agent"),
12065 + "running",
12066 + "the first process ended a subagent the second process still ran",
12067 + );
12068 +
12069 + yield* exitProcess(1, stopSecond);
12070 + yield* startTurn("d", 4);
12071 + yield* finishTurn(2, 4, "00000000-0000-4000-8000-000000002807");
12072 + assert.strictEqual(
12073 + subagentStatus("own-agent"),
12074 + "cancelled",
12075 + "the second process exited after a Stop, but its subagent is not cancelled",
12076 + );
12077 + }).pipe(
12078 + Effect.provide(
12079 + Layer.mergeAll(
12080 + IdAllocator.layer,
12081 + McpProviderSessions.layer,
12082 + NodeServices.layer,
12083 + NodeCrypto.layer,
12084 + ),
12085 + ),
12086 + ),
12087 + ),
12088 + );
12089 +
12090 it.effect("streams a background subagent's work while the root turn is idle", () =>
12091 Effect.scoped(
12092 Effect.gen(function* () {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+91 -35
@@ -4133,6 +4133,8 @@ interface ClaudeLiveQueryContext {
4133 permissionMode: PermissionMode;
4134 stopping: boolean;
4135 readonly subagentsFromEarlierProcesses: ReadonlySet<ActiveClaudeSubagent>;
4136 + // Subagents this process still ran when a replacement took over; only its exit can end them.
4137 + handedOffSubagents: ReadonlySet<ActiveClaudeSubagent>;
4138 // The SDK's per-process model ledger at the last result; a new process starts at zero.
4139 modelLedger: ClaudeModelLedger | undefined;
4140 // Per process, not per session: a relative temp dir follows the cwd this CLI
@@ -6361,6 +6363,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6363 SDKMessage,
6364 { readonly type: "system"; readonly subtype: "task_notification" }
6365 >;
6366 + // The process that ran it exited, which confirms the outcome as a native one would.
6367 + readonly processExited?: true;
6368 readonly onlyIfRunningInRun?: RunId | null;
6369 }) {
6370 const registeredSubagent = (yield* Ref.get(sessionSubagentsByTaskId)).get(input.taskId);
@@ -6498,7 +6502,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6502 task,
6503 nativeTaskType: input.nativeTaskType ?? existingSubagent?.nativeTaskType,
6504 confirmedOutcome:
6501 - input.nativeOutcome !== undefined
6505 + input.nativeOutcome !== undefined || input.processExited === true
6506 ? confirmedSubagentOutcome(task)
6507 : isReopen
6508 ? undefined
@@ -7787,6 +7791,69 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7791 );
7792 });
7793
7794 + const endSubagentsOfClosedQuery = Effect.fnUntraced(function* (input: {
7795 + readonly closedQuery: ClaudeLiveQueryContext;
7796 + readonly context: ActiveClaudeTurnContext;
7797 + readonly subagents: Iterable<readonly [string, ActiveClaudeSubagent]>;
7798 + readonly buffered: ReadonlyArray<SDKMessage> | undefined;
7799 + readonly interrupted: boolean;
7800 + }) {
7801 + for (const [taskId, subagent] of input.subagents) {
7802 + if (
7803 + subagent.task.status !== "running" ||
7804 + input.closedQuery.subagentsFromEarlierProcesses.has(subagent)
7805 + )
7806 + continue;
7807 + const latestLifecycle = input.buffered?.findLast(
7808 + (
7809 + message,
7810 + ): message is Extract<
7811 + SDKMessage,
7812 + { readonly subtype: "task_started" | "task_notification" }
7813 + > =>
7814 + message.type === "system" &&
7815 + (message.subtype === "task_started" || message.subtype === "task_notification") &&
7816 + message.task_id === taskId,
7817 + );
7818 + const completion =
7819 + latestLifecycle?.subtype === "task_notification" ? latestLifecycle : undefined;
7820 + yield* updateClaudeSubagentNode({
7821 + context: input.context,
7822 + taskId,
7823 + status: completion
7824 + ? claudeTaskOutcome(completion.status)
7825 + : input.interrupted
7826 + ? "cancelled"
7827 + : "failed",
7828 + ...(completion === undefined
7829 + ? {}
7830 + : { workflowFrame: completion, result: completion.summary }),
7831 + processExited: true,
7832 + onlyIfRunningInRun: subagent.task.runId,
7833 + });
7834 + }
7835 + });
7836 +
7837 + // A query opened while this one was closing inherited the subagents it ran, so
7838 + // nothing else ends them. Leave the live query's own turn, roster and subagents alone.
7839 + const endSubagentsOfReplacedQuery = Effect.fnUntraced(function* (
7840 + closedQuery: ClaudeLiveQueryContext,
7841 + ) {
7842 + const context = closedQuery.lastTurn;
7843 + if (context === null) return;
7844 + yield* endSubagentsOfClosedQuery({
7845 + closedQuery,
7846 + context,
7847 + subagents: [...(yield* Ref.get(sessionSubagentsByTaskId))].filter(([, subagent]) =>
7848 + closedQuery.handedOffSubagents.has(subagent),
7849 + ),
7850 + buffered: (yield* Ref.get(wakeBuffers)).get(closedQuery.nativeThreadId)?.messages,
7851 + interrupted:
7852 + closedQuery.stopping ||
7853 + (yield* Ref.get(interruptedTurns)).has(context.providerTurnId),
7854 + });
7855 + });
7856 +
7857 const finalizeActiveTurnAfterQueryExit = Effect.fnUntraced(function* (
7858 closedQuery: ClaudeLiveQueryContext,
7859 cause?: Cause.Cause<ClaudeAgentSdkQueryRunnerError>,
@@ -7818,39 +7885,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7885 yield* resetBackgroundTaskStateForNativeThreadProcess(closedQuery.nativeThreadId);
7886 }
7887 // Preserve buffered outcomes before Stop clears the wake buffer.
7821 - for (const [taskId, subagent] of subagents) {
7822 - if (
7823 - subagent.task.status !== "running" ||
7824 - closedQuery.subagentsFromEarlierProcesses.has(subagent)
7825 - )
7826 - continue;
7827 - const latestLifecycle = buffered?.findLast(
7828 - (
7829 - message,
7830 - ): message is Extract<
7831 - SDKMessage,
7832 - { readonly subtype: "task_started" | "task_notification" }
7833 - > =>
7834 - message.type === "system" &&
7835 - (message.subtype === "task_started" || message.subtype === "task_notification") &&
7836 - message.task_id === taskId,
7837 - );
7838 - const completion =
7839 - latestLifecycle?.subtype === "task_notification" ? latestLifecycle : undefined;
7840 - yield* updateClaudeSubagentNode({
7841 - context,
7842 - taskId,
7843 - status: completion
7844 - ? claudeTaskOutcome(completion.status)
7845 - : interrupted
7846 - ? "cancelled"
7847 - : "failed",
7848 - ...(completion === undefined
7849 - ? {}
7850 - : { workflowFrame: completion, result: completion.summary }),
7851 - onlyIfRunningInRun: subagent.task.runId,
7852 - });
7853 - }
7888 + yield* endSubagentsOfClosedQuery({
7889 + closedQuery,
7890 + context,
7891 + subagents,
7892 + buffered,
7893 + interrupted,
7894 + });
7895 yield* Ref.update(interruptedTurns, (current) => {
7896 const next = new Set(current);
7897 next.delete(context.providerTurnId);
@@ -10434,6 +10475,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10475 receivedInit: false,
10476 permissionMode: queryOptions.permissionMode,
10477 stopping: false,
10478 + handedOffSubagents: new Set(),
10479 subagentsFromEarlierProcesses: new Set(
10480 [...(yield* Ref.get(sessionSubagentsByTaskId)).values()].filter(
10481 (subagent) => subagent.task.status === "running",
@@ -10447,7 +10489,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10489 hostPlatform,
10490 ),
10491 };
10450 - yield* Ref.set(queryContext, context);
10492 + // One step, so the replaced process cannot exit between the install and the handoff.
10493 + yield* Ref.update(queryContext, (replaced) => {
10494 + if (replaced !== null) {
10495 + replaced.handedOffSubagents = new Set(
10496 + [...context.subagentsFromEarlierProcesses].filter(
10497 + (subagent) => !replaced.subagentsFromEarlierProcesses.has(subagent),
10498 + ),
10499 + );
10500 + }
10501 + return context;
10502 + });
10503 yield* querySession.messages.pipe(
10504 Stream.runForEach((message) =>
10505 sdkMessageLock.withPermits(1)(
@@ -10505,6 +10557,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10557 context.nativeThreadId,
10558 context.stopping ? "interrupted" : "failed",
10559 );
10560 + } else {
10561 + yield* endSubagentsOfReplacedQuery(context);
10562 }
10563 }),
10564 ),
@@ -11120,6 +11174,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
11174 if (ownedLiveQuery) {
11175 yield* finalizeActiveTurnAfterQueryExit(existing);
11176 yield* endSubagentCallsOfClosedQuery(nativeThreadId, "interrupted");
11177 + } else {
11178 + yield* endSubagentsOfReplacedQuery(existing);
11179 }
11180 yield* Deferred.succeed(existing.closed, undefined);
11181 });