@devries-cameron20 / t3code Mirror · read-only / commits / 1550058056
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 08:00 UTC

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

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

Julius Marminge committed Oct 15, 2026 at 18:22 UTC 1550058056ba660b8581c8eda990c9d40c493a4b
3 files changed +198 -8
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+9 -5
@@ -5347,6 +5347,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5347 completedAt: task.completedAt,
5348 },
5349 });
5350 + }
5351 + // Ahead of the child thread's records: the run a resume attributes
5352 + // the subagent to adopts its child thread from this event.
5353 + yield* emitProviderEvent({
5354 + type: "subagent.updated",
5355 + driver: CLAUDE_PROVIDER,
5356 + subagent: task,
5357 + });
5358 + if (lifecycleChanged) {
5359 yield* emitProviderEvent({
5360 type: "node.updated",
5361 driver: CLAUDE_PROVIDER,
@@ -5389,11 +5398,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5398 now,
5399 });
5400 }
5392 - yield* emitProviderEvent({
5393 - type: "subagent.updated",
5394 - driver: CLAUDE_PROVIDER,
5395 - subagent: task,
5396 - });
5401 if (workflowWithThreads !== undefined) {
5402 yield* projectClaudeWorkflowMembers({
5403 coordinator: subagent,
apps/server/src/orchestration-v2/RunExecutionService.ts
+18 -2
@@ -427,12 +427,28 @@ export function routeProviderEvent(
427 case "subagent.updated": {
428 const belongs = ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId);
429 const coordinator = event.subagent;
430 + // A provider-native subagent's child thread follows the live run it is
431 + // attributed to. A resume reattributes it to the resuming run, which
432 + // never saw the child thread created when the subagent was not
433 + // completed at its start (e.g. cancelled by a server restart).
434 + const adopted =
435 + ownsRun(coordinator.runId) &&
436 + !state.rootTurnEnded &&
437 + isOrchestrationV2WorkActive(coordinator.status) &&
438 + coordinator.origin === "provider_native" &&
439 + coordinator.childThreadId !== null &&
440 + !ownsThread(coordinator.childThreadId)
441 + ? {
442 + ...state,
443 + ownedThreadIds: new Set([...state.ownedThreadIds, coordinator.childThreadId]),
444 + }
445 + : state;
446 if (
447 !ownsRun(coordinator.runId) ||
448 coordinator.workflow === undefined ||
449 coordinator.childThreadId === null
450 ) {
435 - return [belongs, state];
451 + return [belongs, adopted];
452 }
453 const workflowMemberParents = new Map(state.workflowMemberParents);
454 for (const member of coordinator.workflow.agents) {
@@ -440,7 +456,7 @@ export function routeProviderEvent(
456 workflowMemberParents.set(member.childThreadId, coordinator.childThreadId);
457 }
458 }
443 - return [true, { ...state, workflowMemberParents }];
459 + return [true, { ...adopted, workflowMemberParents }];
460 }
461 case "message.updated":
462 return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state];
apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts
+171 -1
@@ -6,7 +6,11 @@ import * as Layer from "effect/Layer";
6 import * as Path from "effect/Path";
7 import * as Schema from "effect/Schema";
8 import * as CodexReplay from "effect-codex-app-server/replay";
9 -import { ProviderDriverKind } from "@t3tools/contracts";
9 +import {
10 + type OrchestrationV2ThreadProjection,
11 + ProviderDriverKind,
12 + type ThreadId,
13 +} from "@t3tools/contracts";
14
15 import {
16 ClaudeOrchestratorReplayHarness,
@@ -42,6 +46,7 @@ import {
46 assertUserMessagesInclude,
47 projectionFor,
48 } from "./fixtures/shared.ts";
49 +import type { OrchestratorV2ScenarioResult } from "./OrchestratorScenario.ts";
50 import { runOrchestratorV2ProviderReplayScenario } from "./ProviderReplayHarness.ts";
51 import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
52 import { materializeReplayTranscriptRuntimeInstructions } from "./ReplayRuntimeInstructions.ts";
@@ -78,6 +83,66 @@ const readClaudeSubagentResumeTranscript = Effect.fn("readClaudeSubagentResumeTr
83 );
84 },
85 );
86 +/**
87 + * The same session with the math.ts subagent's first run removed: the root
88 + * turn settles while the subagent still works, and the server restarts
89 + * before it reports, so recovery cancels it. The resumed turn then carries
90 + * the restart note, as T3 sends it.
91 + */
92 +const readClaudeCancelledSubagentResumeTranscript = Effect.fn(
93 + "readClaudeCancelledSubagentResumeTranscript",
94 +)(function* () {
95 + const recorded = yield* readRawTranscript(
96 + new URL(
97 + "./fixtures/claude_subagent_resume_after_restart/claude_transcript.ndjson",
98 + import.meta.url,
99 + ),
100 + );
101 + const frameField = (index: number, key: string): unknown => {
102 + const entry = recorded.entries[index];
103 + return entry?.type === "emit_inbound" && typeof entry.frame === "object" && entry.frame !== null
104 + ? Reflect.get(entry.frame, key)
105 + : undefined;
106 + };
107 + const indices = recorded.entries.map((_, index) => index);
108 + const firstSubagentFrame = indices.find(
109 + (index) => typeof frameField(index, "parent_tool_use_id") === "string",
110 + );
111 + const firstOutcome = indices.find(
112 + (index) => frameField(index, "subtype") === "task_notification",
113 + );
114 + if (firstSubagentFrame === undefined || firstOutcome === undefined) {
115 + throw new Error("Expected the recorded subagent's first run.");
116 + }
117 + const entries = recorded.entries
118 + .filter((_, index) => index < firstSubagentFrame || index > firstOutcome)
119 + .map((entry) => {
120 + if (entry.type !== "expect_outbound" || entry.label !== "prompt.offer:2") return entry;
121 + const frame = entry.frame as {
122 + readonly message: { readonly message: { readonly content: string } };
123 + };
124 + return {
125 + ...entry,
126 + frame: {
127 + ...frame,
128 + message: {
129 + ...frame.message,
130 + message: {
131 + ...frame.message.message,
132 + content: [
133 + "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back:",
134 + "- subagent: Audit src/math.ts",
135 + "",
136 + "User message:",
137 + frame.message.message.content,
138 + ].join("\n"),
139 + },
140 + },
141 + },
142 + };
143 + });
144 + return yield* ClaudeOrchestratorReplayHarness.decodeTranscript({ ...recorded, entries });
145 +});
146 const readCursorTranscript = Effect.fn("readCursorRecoveryTranscript")(function* () {
147 const transcript = yield* readRawTranscript(
148 new URL("./fixtures/provider_thread_resume/cursor_transcript.ndjson", import.meta.url),
@@ -426,4 +491,109 @@ describe("orchestrator replay recovery", () => {
491 ),
492 ),
493 );
494 + it.effect("reopens the thread of a Claude subagent the restart cancelled when resumed", () =>
495 + Effect.scoped(
496 + Effect.gen(function* () {
497 + const transcript = yield* readClaudeCancelledSubagentResumeTranscript();
498 + const [launchPrompt, resumePrompt] = yield* decodePromptPair(transcript.metadata?.prompts);
499 + const workspace = yield* checkpointWorkspace(transcript.scenario);
500 + const fs = yield* FileSystem.FileSystem;
501 + const path = yield* Path.Path;
502 + const tempDir = yield* Effect.acquireRelease(
503 + fs.makeTempDirectory({ prefix: "t3-orchestration-v2-claude-recovery-" }),
504 + (directory) => fs.remove(directory, { recursive: true, force: true }).pipe(Effect.orDie),
505 + );
506 + const materialized = yield* materializeFixtureInput({
507 + scenario: transcript.scenario,
508 + fixtureInput: {
509 + steps: [
510 + { type: "message", text: launchPrompt },
511 + { type: "message", text: resumePrompt },
512 + ],
513 + },
514 + driver: ProviderDriverKind.make("claudeAgent"),
515 + modelSelection: CLAUDE_MODEL_SELECTION,
516 + });
517 + const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
518 + splitAfterFirstIdle(materialized);
519 + const { harness, assertComplete } = makeClaudeRestartReplayHarness(transcript);
520 + const options = {
521 + databaseLayer: SqlitePersistence.layerFromPath(path.join(tempDir, "state.sqlite")).pipe(
522 + Layer.provide(NodeServices.layer),
523 + ),
524 + };
525 + const childThreadOf = (result: OrchestratorV2ScenarioResult, parentThreadId: ThreadId) =>
526 + [...result.projections.values()].find(
527 + (candidate) => candidate.thread.lineage.parentThreadId === parentThreadId,
528 + );
529 + const childRootStatus = (child: OrchestrationV2ThreadProjection | undefined) =>
530 + child?.nodes.find((node) => node.kind === "root_turn" && node.runId === null)?.status;
531 +
532 + const before = yield* Effect.scoped(
533 + runOrchestratorV2ProviderReplayScenario(
534 + {
535 + name: `${transcript.scenario}:cancelled-first-runtime`,
536 + transcript,
537 + commands: phase1Commands,
538 + steps: phase1Steps,
539 + projectionThreadIds: materialized.projectionThreadIds,
540 + runtimePolicyOverride: { cwd: workspace },
541 + },
542 + harness,
543 + options,
544 + ),
545 + );
546 + const settled = projectionFor(before, transcript.scenario);
547 + assert.equal(settled.subagents[0]?.status, "running");
548 + assert.equal(childRootStatus(childThreadOf(before, settled.thread.id)), "running");
549 +
550 + // The server restarts with the subagent still working. No automatic
551 + // continuation: the user's next message resumes it.
552 + const result = yield* Effect.scoped(
553 + runOrchestratorV2ProviderReplayScenario(
554 + {
555 + name: `${transcript.scenario}:cancelled-second-runtime`,
556 + transcript,
557 + commands: phase2Commands,
558 + steps: phase2Steps,
559 + projectionThreadIds: materialized.projectionThreadIds,
560 + runtimePolicyOverride: { cwd: workspace },
561 + },
562 + harness,
563 + { ...options, recoverOnStartup: true, continueThreadsAfterServerUpdate: false },
564 + ),
565 + );
566 + yield* assertComplete;
567 +
568 + const projection = projectionFor(result, transcript.scenario);
569 + assertSemanticProjectionIntegrity(projection);
570 + assert.equal(projection.subagents[0]?.status, "completed");
571 + const child = childThreadOf(result, projection.thread.id);
572 + assert.equal(child?.thread.id, projection.subagents[0]?.childThreadId);
573 + // Recovery cancelled the child's work; the resume reopened and ended it.
574 + assert.equal(childRootStatus(child), "completed");
575 + const conversation = (child?.turnItems ?? [])
576 + .toSorted((left, right) => left.ordinal - right.ordinal)
577 + .flatMap((item) =>
578 + item.type === "user_message" || item.type === "assistant_message"
579 + ? [`${item.type === "user_message" ? "user" : "assistant"}:${item.text}`]
580 + : [],
581 + );
582 + assert.deepEqual(
583 + conversation.map((entry) => entry.slice(0, entry.indexOf(":"))),
584 + ["user", "user", "assistant"],
585 + );
586 + assert.include(conversation[0], "Your job is just the file");
587 + assert.include(conversation[1], "Look again at");
588 + assert.include(conversation[2], "Bug/edge case found and fixed");
589 + assert.lengthOf(
590 + (child?.turnItems ?? []).filter((item) => item.type === "command_execution"),
591 + 2,
592 + );
593 + }).pipe(
594 + provideDeterministicTestRuntime,
595 + Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer)),
596 + ),
597 + ),
598 + );
599 });