Skip to content
TypeScript

fix(server): resumed Claude subagents keep updating their own thread (#20061)

Julius Marminge1550058056ba
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index d5a4d16510b..0e2dcb30931 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -5347,6 +5347,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
completedAt: task.completedAt,
},
});
+ }
+ // Ahead of the child thread's records: the run a resume attributes
+ // the subagent to adopts its child thread from this event.
+ yield* emitProviderEvent({
+ type: "subagent.updated",
+ driver: CLAUDE_PROVIDER,
+ subagent: task,
+ });
+ if (lifecycleChanged) {
yield* emitProviderEvent({
type: "node.updated",
driver: CLAUDE_PROVIDER,
@@ -5389,11 +5398,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
now,
});
}
- yield* emitProviderEvent({
- type: "subagent.updated",
- driver: CLAUDE_PROVIDER,
- subagent: task,
- });
if (workflowWithThreads !== undefined) {
yield* projectClaudeWorkflowMembers({
coordinator: subagent,
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts
index 9ca399357aa..510d18391c9 100644
--- a/apps/server/src/orchestration-v2/RunExecutionService.ts
+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts
@@ -427,12 +427,28 @@ export function routeProviderEvent(
case "subagent.updated": {
const belongs = ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId);
const coordinator = event.subagent;
+ // A provider-native subagent's child thread follows the live run it is
+ // attributed to. A resume reattributes it to the resuming run, which
+ // never saw the child thread created when the subagent was not
+ // completed at its start (e.g. cancelled by a server restart).
+ const adopted =
+ ownsRun(coordinator.runId) &&
+ !state.rootTurnEnded &&
+ isOrchestrationV2WorkActive(coordinator.status) &&
+ coordinator.origin === "provider_native" &&
+ coordinator.childThreadId !== null &&
+ !ownsThread(coordinator.childThreadId)
+ ? {
+ ...state,
+ ownedThreadIds: new Set([...state.ownedThreadIds, coordinator.childThreadId]),
+ }
+ : state;
if (
!ownsRun(coordinator.runId) ||
coordinator.workflow === undefined ||
coordinator.childThreadId === null
) {
- return [belongs, state];
+ return [belongs, adopted];
}
const workflowMemberParents = new Map(state.workflowMemberParents);
for (const member of coordinator.workflow.agents) {
@@ -440,7 +456,7 @@ export function routeProviderEvent(
workflowMemberParents.set(member.childThreadId, coordinator.childThreadId);
}
}
- return [true, { ...state, workflowMemberParents }];
+ return [true, { ...adopted, workflowMemberParents }];
}
case "message.updated":
return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state];
diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts
index 6c1a6757058..3717e604daf 100644
--- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts
@@ -6,7 +6,11 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as CodexReplay from "effect-codex-app-server/replay";
-import { ProviderDriverKind } from "@t3tools/contracts";
+import {
+ type OrchestrationV2ThreadProjection,
+ ProviderDriverKind,
+ type ThreadId,
+} from "@t3tools/contracts";
import {
ClaudeOrchestratorReplayHarness,
@@ -42,6 +46,7 @@ import {
assertUserMessagesInclude,
projectionFor,
} from "./fixtures/shared.ts";
+import type { OrchestratorV2ScenarioResult } from "./OrchestratorScenario.ts";
import { runOrchestratorV2ProviderReplayScenario } from "./ProviderReplayHarness.ts";
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
import { materializeReplayTranscriptRuntimeInstructions } from "./ReplayRuntimeInstructions.ts";
@@ -78,6 +83,66 @@ const readClaudeSubagentResumeTranscript = Effect.fn("readClaudeSubagentResumeTr
);
},
);
+/**
+ * The same session with the math.ts subagent's first run removed: the root
+ * turn settles while the subagent still works, and the server restarts
+ * before it reports, so recovery cancels it. The resumed turn then carries
+ * the restart note, as T3 sends it.
+ */
+const readClaudeCancelledSubagentResumeTranscript = Effect.fn(
+ "readClaudeCancelledSubagentResumeTranscript",
+)(function* () {
+ const recorded = yield* readRawTranscript(
+ new URL(
+ "./fixtures/claude_subagent_resume_after_restart/claude_transcript.ndjson",
+ import.meta.url,
+ ),
+ );
+ const frameField = (index: number, key: string): unknown => {
+ const entry = recorded.entries[index];
+ return entry?.type === "emit_inbound" && typeof entry.frame === "object" && entry.frame !== null
+ ? Reflect.get(entry.frame, key)
+ : undefined;
+ };
+ const indices = recorded.entries.map((_, index) => index);
+ const firstSubagentFrame = indices.find(
+ (index) => typeof frameField(index, "parent_tool_use_id") === "string",
+ );
+ const firstOutcome = indices.find(
+ (index) => frameField(index, "subtype") === "task_notification",
+ );
+ if (firstSubagentFrame === undefined || firstOutcome === undefined) {
+ throw new Error("Expected the recorded subagent's first run.");
+ }
+ const entries = recorded.entries
+ .filter((_, index) => index < firstSubagentFrame || index > firstOutcome)
+ .map((entry) => {
+ if (entry.type !== "expect_outbound" || entry.label !== "prompt.offer:2") return entry;
+ const frame = entry.frame as {
+ readonly message: { readonly message: { readonly content: string } };
+ };
+ return {
+ ...entry,
+ frame: {
+ ...frame,
+ message: {
+ ...frame.message,
+ message: {
+ ...frame.message.message,
+ content: [
+ "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back:",
+ "- subagent: Audit src/math.ts",
+ "",
+ "User message:",
+ frame.message.message.content,
+ ].join("\n"),
+ },
+ },
+ },
+ };
+ });
+ return yield* ClaudeOrchestratorReplayHarness.decodeTranscript({ ...recorded, entries });
+});
const readCursorTranscript = Effect.fn("readCursorRecoveryTranscript")(function* () {
const transcript = yield* readRawTranscript(
new URL("./fixtures/provider_thread_resume/cursor_transcript.ndjson", import.meta.url),
@@ -426,4 +491,109 @@ describe("orchestrator replay recovery", () => {
),
),
);
+ it.effect("reopens the thread of a Claude subagent the restart cancelled when resumed", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const transcript = yield* readClaudeCancelledSubagentResumeTranscript();
+ const [launchPrompt, resumePrompt] = yield* decodePromptPair(transcript.metadata?.prompts);
+ const workspace = yield* checkpointWorkspace(transcript.scenario);
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const tempDir = yield* Effect.acquireRelease(
+ fs.makeTempDirectory({ prefix: "t3-orchestration-v2-claude-recovery-" }),
+ (directory) => fs.remove(directory, { recursive: true, force: true }).pipe(Effect.orDie),
+ );
+ const materialized = yield* materializeFixtureInput({
+ scenario: transcript.scenario,
+ fixtureInput: {
+ steps: [
+ { type: "message", text: launchPrompt },
+ { type: "message", text: resumePrompt },
+ ],
+ },
+ driver: ProviderDriverKind.make("claudeAgent"),
+ modelSelection: CLAUDE_MODEL_SELECTION,
+ });
+ const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
+ splitAfterFirstIdle(materialized);
+ const { harness, assertComplete } = makeClaudeRestartReplayHarness(transcript);
+ const options = {
+ databaseLayer: SqlitePersistence.layerFromPath(path.join(tempDir, "state.sqlite")).pipe(
+ Layer.provide(NodeServices.layer),
+ ),
+ };
+ const childThreadOf = (result: OrchestratorV2ScenarioResult, parentThreadId: ThreadId) =>
+ [...result.projections.values()].find(
+ (candidate) => candidate.thread.lineage.parentThreadId === parentThreadId,
+ );
+ const childRootStatus = (child: OrchestrationV2ThreadProjection | undefined) =>
+ child?.nodes.find((node) => node.kind === "root_turn" && node.runId === null)?.status;
+
+ const before = yield* Effect.scoped(
+ runOrchestratorV2ProviderReplayScenario(
+ {
+ name: `${transcript.scenario}:cancelled-first-runtime`,
+ transcript,
+ commands: phase1Commands,
+ steps: phase1Steps,
+ projectionThreadIds: materialized.projectionThreadIds,
+ runtimePolicyOverride: { cwd: workspace },
+ },
+ harness,
+ options,
+ ),
+ );
+ const settled = projectionFor(before, transcript.scenario);
+ assert.equal(settled.subagents[0]?.status, "running");
+ assert.equal(childRootStatus(childThreadOf(before, settled.thread.id)), "running");
+
+ // The server restarts with the subagent still working. No automatic
+ // continuation: the user's next message resumes it.
+ const result = yield* Effect.scoped(
+ runOrchestratorV2ProviderReplayScenario(
+ {
+ name: `${transcript.scenario}:cancelled-second-runtime`,
+ transcript,
+ commands: phase2Commands,
+ steps: phase2Steps,
+ projectionThreadIds: materialized.projectionThreadIds,
+ runtimePolicyOverride: { cwd: workspace },
+ },
+ harness,
+ { ...options, recoverOnStartup: true, continueThreadsAfterServerUpdate: false },
+ ),
+ );
+ yield* assertComplete;
+
+ const projection = projectionFor(result, transcript.scenario);
+ assertSemanticProjectionIntegrity(projection);
+ assert.equal(projection.subagents[0]?.status, "completed");
+ const child = childThreadOf(result, projection.thread.id);
+ assert.equal(child?.thread.id, projection.subagents[0]?.childThreadId);
+ // Recovery cancelled the child's work; the resume reopened and ended it.
+ assert.equal(childRootStatus(child), "completed");
+ const conversation = (child?.turnItems ?? [])
+ .toSorted((left, right) => left.ordinal - right.ordinal)
+ .flatMap((item) =>
+ item.type === "user_message" || item.type === "assistant_message"
+ ? [`${item.type === "user_message" ? "user" : "assistant"}:${item.text}`]
+ : [],
+ );
+ assert.deepEqual(
+ conversation.map((entry) => entry.slice(0, entry.indexOf(":"))),
+ ["user", "user", "assistant"],
+ );
+ assert.include(conversation[0], "Your job is just the file");
+ assert.include(conversation[1], "Look again at");
+ assert.include(conversation[2], "Bug/edge case found and fixed");
+ assert.lengthOf(
+ (child?.turnItems ?? []).filter((item) => item.type === "command_execution"),
+ 2,
+ );
+ }).pipe(
+ provideDeterministicTestRuntime,
+ Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer)),
+ ),
+ ),
+ );
});