@devries-cameron20 / t3code Mirror · read-only / commits / 3a60d0996a
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 21, 04:45 UTC

fix(server): background subagents can delegate after their parent's turn ends (#38869)

Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Bilal Bakr committed Nov 20, 2026 at 04:02 UTC 3a60d0996ae483952aec13a1ec0d8654f17c1421
7 files changed +127 -15
apps/server/src/mcp/OrchestratorMcpService.ts
+24 -3
@@ -1502,6 +1502,27 @@ const make = Effect.gen(function* () {
1502 : Effect.void;
1503 };
1504
1505 + // A background subagent keeps calling tools after the run that started it settles. Its
1506 + // delegations join that latest run, whose completion cohort wakes the thread once they finish.
1507 + const backgroundSubagentRun = Effect.fn("OrchestratorMcpService.backgroundSubagentRun")(
1508 + function* (scope: McpInvocationScope, threadId: ThreadId) {
1509 + const shell = yield* threadManagement
1510 + .getThreadShell(threadId)
1511 + .pipe(Effect.mapError(threadManagementFailure));
1512 + if (
1513 + shell?.activeRunId !== null ||
1514 + shell.latestRunId === null ||
1515 + !isLiveCallerShell(shell, scope.thread?.providerInstanceId)
1516 + ) {
1517 + return undefined;
1518 + }
1519 + const { runs } = yield* loadThreadRecords(threadId, ["runs"], {
1520 + runIds: [shell.latestRunId],
1521 + });
1522 + return runs[0];
1523 + },
1524 + );
1525 +
1526 const loadReadableThread = Effect.fn("OrchestratorMcpService.loadReadableThread")(function* (
1527 scope: McpInvocationScope,
1528 threadId: ThreadId,
@@ -2798,9 +2819,9 @@ const make = Effect.gen(function* () {
2819 "A local task runs in this thread's project. Omit target.projectId, or pass target.environmentId to run it in that environment's project.",
2820 );
2821 }
2801 - const parentRun = parent.runs
2802 - .filter(ThreadManagementService.isActiveRun)
2803 - .toSorted((left, right) => right.ordinal - left.ordinal)[0];
2822 + const parentRun =
2823 + ThreadManagementService.latestActiveRun(parent) ??
2824 + (yield* backgroundSubagentRun(scope, parent.thread.id));
2825 if (
2826 parentRun === undefined ||
2827 parentRun.rootNodeId === null ||
apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts
+35 -2
@@ -17,6 +17,7 @@ import {
17 ThreadId,
18 TurnItemId,
19 type OrchestrationV2DomainEvent,
20 + type ServerProvider,
21 } from "@t3tools/contracts";
22 import * as DateTime from "effect/DateTime";
23 import * as Effect from "effect/Effect";
@@ -57,6 +58,15 @@ const layerOrchestratorService = OrchestratorMcpService.layer.pipe(
58 const driver = ProviderDriverKind.make("claudeAgent");
59 const instanceId = ProviderInstanceId.make("claudeAgent");
60 const modelSelection = { instanceId, model: "claude-test" };
61 +const provider = {
62 + instanceId,
63 + driver,
64 + enabled: true,
65 + installed: true,
66 + status: "ready",
67 + auth: { status: "authenticated" },
68 + models: [{ slug: modelSelection.model, name: modelSelection.model, isCustom: false }],
69 +} as unknown as ServerProvider;
70
71 // Cancellation races with turn completion and checkpoint capture; "recorded" restarts before the Stop outbox runs.
72 const cancelBackgroundOnlyTask = (
@@ -66,7 +76,14 @@ const cancelBackgroundOnlyTask = (
76 remote = false,
77 }: {
78 readonly remote?: boolean;
69 - readonly cancelAt?: "settled" | "checkpoint" | "turn" | "recorded" | "monitor" | "refused";
79 + readonly cancelAt?:
80 + | "settled"
81 + | "checkpoint"
82 + | "turn"
83 + | "recorded"
84 + | "monitor"
85 + | "refused"
86 + | "delegate";
87 } = {},
88 ) =>
89 Effect.scoped(
@@ -214,7 +231,9 @@ const cancelBackgroundOnlyTask = (
231 Layer.provide(
232 Layer.mergeAll(
233 layerAdapters,
217 - Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
234 + Layer.mock(ProviderRegistry.ProviderRegistry)({
235 + getProviders: Effect.succeed([provider]),
236 + }),
237 Layer.mock(ProjectService.ProjectService)({}),
238 Layer.mock(SecretRequests.SecretRequests)({}),
239 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
@@ -529,6 +548,16 @@ const cancelBackgroundOnlyTask = (
548 capabilities: new Set(["orchestration"]),
549 issuedAt: 1,
550 };
551 + if (cancelAt === "delegate") {
552 + // The child's run settled while its native subagent still runs, and that subagent delegates.
553 + const childScope: McpInvocationScope = {
554 + ...scope,
555 + thread: { ...scope.thread!, threadId: task.childThreadId! },
556 + };
557 + const delegated = yield* service.delegateTask(childScope, { task: "Reply OK." });
558 + assert.equal(delegated.status, "starting");
559 + return undefined;
560 + }
561 const before = yield* service.taskStatus(scope, task.id);
562 assert.equal(before.status, "running");
563 assert.equal(before.workState, turnSettled ? "waiting_for_children" : "working");
@@ -694,3 +723,7 @@ it.effect("a refused descendant stop does not settle or dispose its parent task"
723 it.effect("task_cancel stops a remote descendant without reacquiring its parent lock", () =>
724 cancelBackgroundOnlyTask("command", { remote: true }),
725 );
726 +
727 +it.effect("a native background subagent delegates after its parent's run completes", () =>
728 + cancelBackgroundOnlyTask("subagent", { cancelAt: "delegate" }),
729 +);
apps/server/src/mcp/threadAccess.ts
+2 -4
@@ -19,6 +19,7 @@ import {
19 threadLinkCandidates,
20 threadLinkRefs,
21 } from "@t3tools/shared/threadLinks";
22 +import { hasPendingBackgroundSubagent } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
23 import * as SecureRandom from "effect/crypto/SecureRandom";
24 import * as Effect from "effect/Effect";
25
@@ -199,10 +200,7 @@ export const isLiveCallerShell = (
200 shell.archivedAt === null &&
201 shell.providerInstanceId === providerInstanceId &&
202 (shell.activeRunId !== null ||
202 - (shell.pendingBackgroundTasks?.some(
203 - (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId,
204 - ) ??
205 - false));
203 + hasPendingBackgroundSubagent(shell.pendingBackgroundTasks, providerInstanceId));
204
205 /** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */
206 export function assertLiveCaller({ caller, scope }: Caller) {
apps/server/src/orchestration-v2/Orchestrator.ts
+21 -1
@@ -93,6 +93,7 @@ import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
93 import {
94 backgroundWorkHoldsCompletion,
95 derivePendingBackgroundWork,
96 + hasPendingBackgroundSubagent,
97 pendingBackgroundTurnItems,
98 } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
99 import * as Context from "effect/Context";
@@ -9767,6 +9768,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9768 yield* Ref.update(effects, (existing) => [...existing, pendingEffect]);
9769 });
9770
9771 + // A native background subagent keeps working, and delegating, after the latest run settles.
9772 + const backgroundSubagentOutlivesRun = (run: OrchestrationV2Run) =>
9773 + projectionStore.getThreadShell(run.threadId).pipe(
9774 + Effect.map(
9775 + (shell) =>
9776 + shell !== null &&
9777 + shell.archivedAt === null &&
9778 + shell.activeRunId === null &&
9779 + shell.latestRunId === run.id &&
9780 + hasPendingBackgroundSubagent(shell.pendingBackgroundTasks, run.providerInstanceId),
9781 + ),
9782 + Effect.mapError(
9783 + (cause) => new OrchestratorProjectionError({ threadId: run.threadId, cause }),
9784 + ),
9785 + );
9786 +
9787 const dispatchDelegatedTaskRequest = Effect.fn("orchestrationV2.dispatch.delegatedTaskRequest")(
9788 function* (
9789 command: Extract<OrchestrationV2Command, { readonly type: "delegated_task.request" }>,
@@ -9783,7 +9800,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9800 const parentRun = parentProjection.runs.find(
9801 (candidate) => candidate.id === command.parentRunId,
9802 );
9786 - if (parentRun === undefined || !isActiveRun(parentRun)) {
9803 + if (
9804 + parentRun === undefined ||
9805 + !(isActiveRun(parentRun) || (yield* backgroundSubagentOutlivesRun(parentRun)))
9806 + ) {
9807 return yield* new OrchestratorDispatchError({
9808 commandId: command.commandId,
9809 commandType: command.type,
apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+15 -1
@@ -1603,8 +1603,20 @@ describe("deriveMessagesTimelineRows", () => {
1603 message("steer", 10, "user", "steer"),
1604 work("work-after-steer", 15),
1605 message("final", 30, "assistant"),
1606 + {
1607 + kind: "event",
1608 + id: "late-subagent",
1609 + createdAt: time(50),
1610 + projectedItem: { item: { type: "subagent", status: "completed", runId } } as never,
1611 + },
1612 ],
1607 - latestRun: { runId, status: "completed", startedAt: time(0), completedAt: time(30) },
1613 + // A later wake run is the latest, so this turn's times come from its entries.
1614 + latestRun: {
1615 + runId: RunId.make("wake-run"),
1616 + status: "completed",
1617 + startedAt: time(55),
1618 + completedAt: time(58),
1619 + },
1620 isWorking: false,
1621 expandedRunIds,
1622 turnDiffSummaries: [],
@@ -1619,6 +1631,7 @@ describe("deriveMessagesTimelineRows", () => {
1631 "steer",
1632 `turn-fold:${segmentKey}`,
1633 "final",
1634 + "late-subagent",
1635 ]);
1636 expect(collapsed[1]).toMatchObject({ label: "Worked for 30s" });
1637 expect(collapsed[3]).toMatchObject({ label: "Continued for 20s", createdAt: time(10) });
@@ -1630,6 +1643,7 @@ describe("deriveMessagesTimelineRows", () => {
1643 `turn-fold:${segmentKey}`,
1644 "work-after-steer",
1645 "final",
1646 + "late-subagent",
1647 ]);
1648 });
1649
apps/web/src/components/chat/MessagesTimeline.logic.ts
+18 -4
@@ -1236,8 +1236,20 @@ function deriveTurnFolds(input: {
1236 const isLatestInterruptedTurn =
1237 input.latestRun?.runId === runId && input.latestRun.status === "interrupted";
1238 // A turn cut short by a steer leaves trailing work entries behind its
1239 - // terminal message — take whichever ended last.
1240 - const lastEntryEnd = timelineEntryEnd(lastEntry);
1239 + // terminal message — take whichever ended last. A subagent card after it was
1240 + // spawned by background work once the turn settled, so it adds no turn time.
1241 + const lateSubagentIds = new Set(
1242 + group.entries.flatMap((entry, index) =>
1243 + index > terminalEntryIndex &&
1244 + entry.kind === "event" &&
1245 + entry.projectedItem.item.type === "subagent"
1246 + ? [entry.id]
1247 + : [],
1248 + ),
1249 + );
1250 + const lastTurnEntry =
1251 + group.entries.findLast((entry) => !lateSubagentIds.has(entry.id)) ?? lastEntry;
1252 + const lastEntryEnd = timelineEntryEnd(lastTurnEntry);
1253 const elapsedMs =
1254 input.latestRun?.runId === runId && input.latestRun.startedAt && input.latestRun.completedAt
1255 ? computeElapsedMs(input.latestRun.startedAt, input.latestRun.completedAt)
@@ -1276,8 +1288,10 @@ function deriveTurnFolds(input: {
1288 if (anchorEntry === undefined || !hidesNonCompactionWork(entries)) continue;
1289 const segmentMs = computeElapsedMs(
1290 steer.createdAt,
1279 - entries.map(timelineEntryEnd).reduce<string | null>(maxIsoTimestamp, null) ??
1280 - steer.createdAt,
1291 + entries
1292 + .filter((entry) => !lateSubagentIds.has(entry.id))
1293 + .map(timelineEntryEnd)
1294 + .reduce<string | null>(maxIsoTimestamp, null) ?? steer.createdAt,
1295 );
1296 foldsByAnchorEntryId.set(anchorEntry.id, {
1297 runId: RunId.make(`${runId}:steer:${steer.id}`),
packages/shared/src/orchestrationV2PendingBackgroundWork.ts
+12
@@ -87,6 +87,18 @@ export function deriveBlockedOnThreadWait(input: {
87 return hasWait;
88 }
89
90 +/** A provider instance's background subagent outlives its run and still calls tools. */
91 +export function hasPendingBackgroundSubagent(
92 + tasks: ReadonlyArray<PendingBackgroundWorkTask> | undefined,
93 + providerInstanceId: OrchestrationV2ProviderThread["providerInstanceId"] | undefined,
94 +): boolean {
95 + return (
96 + tasks?.some(
97 + (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId,
98 + ) ?? false
99 + );
100 +}
101 +
102 export function backgroundWorkHoldsCompletion(
103 tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind" | "awaited">>,
104 ): boolean {