Skip to content

Commit ef86c2e

Browse files
fix(server): a follow-up to a delegated child waits for its awaited background work
A follow-up task closed as soon as its run ended, with the child's interim reply, even while the child still awaited a background command. When the command finished, its wake opened a second task and woke the parent again. A follow-up now also waits on the child's awaited background work, as the original delegated task does, and a provider wake joins the latest follow-up while it is still open instead of opening a new task. Fixes #36403 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 7c3e7d2 commit ef86c2e

4 files changed

Lines changed: 154 additions & 13 deletions

File tree

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ import type {
102102
ProjectionRecordFilter,
103103
} from "../orchestration-v2/ProjectionStore.ts";
104104
import {
105-
delegatedTaskAwaitsSubagents,
105+
delegatedTaskAwaitsWork,
106106
delegatedTaskResultRun,
107107
delegatedTaskRuns,
108108
runOutcome,
@@ -1640,7 +1640,7 @@ const make = Effect.gen(function* () {
16401640
? progress.state
16411641
: !isTerminalTaskStatus(taskStatusForRun(taskResultRun))
16421642
? "working"
1643-
: delegatedTaskAwaitsSubagents(followupRuns, childControls.subagents)
1643+
: delegatedTaskAwaitsWork(followupRuns, childControls)
16441644
? "waiting_for_children"
16451645
: "result_available";
16461646
const resultRunIds = [

‎apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3301,6 +3301,90 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
33013301
"the follow-up closed with its interim reply while the awaited command still ran",
33023302
);
33033303
assert.equal(held?.status, "running");
3304+
3305+
// The finished command wakes the child; that turn continues the same follow-up.
3306+
const wakeMessageId = MessageId.make("message:followup-command-wake");
3307+
yield* orchestrator.dispatch({
3308+
type: "message.dispatch",
3309+
createdBy: "agent",
3310+
creationSource: "server",
3311+
commandId: CommandId.make("command:followup-command-wake"),
3312+
threadId: child.childThreadId,
3313+
messageId: wakeMessageId,
3314+
text: "Background activity updated",
3315+
notification: {
3316+
source: { kind: "command" },
3317+
outcome: "completed",
3318+
summary: 'Command "sleep 90" finished',
3319+
},
3320+
attachments: [],
3321+
dispatchMode: { type: "queue_after_active" },
3322+
});
3323+
const wakeRun = (yield* orchestrator.getThreadProjection(child.childThreadId)).runs.find(
3324+
(run) => run.userMessageId === wakeMessageId,
3325+
)!;
3326+
assert.equal(wakeRun.delegatedTaskId, followupTaskId);
3327+
yield* eventSink.write({
3328+
commandId: reconcileCommandId("followup-command-wake-ended"),
3329+
events: [
3330+
{
3331+
id: EventId.make("event:followup-command-settled"),
3332+
type: "provider-thread.updated",
3333+
threadId: child.childThreadId,
3334+
driver,
3335+
providerInstanceId: modelSelection.instanceId,
3336+
occurredAt: now,
3337+
payload: {
3338+
...parent.providerThreads[0]!,
3339+
id: ProviderThreadId.make("provider-thread:followup-command-child"),
3340+
appThreadId: child.childThreadId,
3341+
pendingBackgroundTasks: [],
3342+
},
3343+
},
3344+
{
3345+
id: EventId.make("event:followup-command-final"),
3346+
type: "message.updated",
3347+
threadId: child.childThreadId,
3348+
runId: wakeRun.id,
3349+
occurredAt: now,
3350+
payload: {
3351+
id: MessageId.make("message:followup-command-final"),
3352+
threadId: child.childThreadId,
3353+
runId: wakeRun.id,
3354+
nodeId: null,
3355+
role: "assistant",
3356+
text: "FINAL CHECK-OK",
3357+
attachments: [],
3358+
streaming: false,
3359+
createdBy: "agent",
3360+
creationSource: "server",
3361+
createdAt: now,
3362+
updatedAt: now,
3363+
},
3364+
},
3365+
{
3366+
id: EventId.make("event:followup-command-wake-completed"),
3367+
type: "run.updated",
3368+
threadId: child.childThreadId,
3369+
runId: wakeRun.id,
3370+
occurredAt: now,
3371+
payload: { ...wakeRun, status: "completed", startedAt: now, completedAt: now },
3372+
},
3373+
],
3374+
});
3375+
yield* orchestrator.recoverDelegatedTasks;
3376+
3377+
const finished = yield* orchestrator.getThreadProjection(parentThreadId);
3378+
const childTasks = finished.subagents.filter(
3379+
(task) => task.childThreadId === child.childThreadId,
3380+
);
3381+
assert.deepEqual(
3382+
childTasks.map((task) => task.id).toSorted(),
3383+
[child.taskId, followupTaskId].toSorted(),
3384+
);
3385+
const followup = childTasks.find((task) => task.id === followupTaskId);
3386+
assert.equal(followup?.status, "completed");
3387+
assert.equal(followup?.result, "FINAL CHECK-OK");
33043388
}),
33053389
);
33063390

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ import {
128128
cancelledBeforeStart,
129129
continuationFailedBeforePrompt,
130130
continuationStartRetryDelayMs,
131-
delegatedTaskAwaitsSubagents,
131+
delegatedTaskAwaitsWork,
132132
delegatedTaskResultRun,
133133
delegatedTaskRuns,
134134
isRestartContinuationSource,
@@ -9489,9 +9489,21 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
94899489
(row) => row.id === message.runId,
94909490
);
94919491
if (run === undefined || run.delegatedTaskId !== undefined) return;
9492+
// A wake continues the latest follow-up while it is open, as it continues the original task.
9493+
const latestFollowupId =
9494+
command.notification === undefined
9495+
? undefined
9496+
: (yield* projectionStore
9497+
.getThreadRecords(command.threadId, ["runs"])
9498+
.pipe(mapDispatchError(command))).runs
9499+
.filter((row) => row.id !== run.id && row.delegatedTaskId !== undefined)
9500+
.toSorted((a, b) => b.ordinal - a.ordinal)[0]?.delegatedTaskId;
94929501
const parent = yield* projectionStore
94939502
.getThreadRecords(parentThreadId, ["runs", "subagents", "providerTurns", "attempts"], {
9494-
subagentIds: child.forkedFrom?.type === "node" ? [child.forkedFrom.nodeId] : [],
9503+
subagentIds: [
9504+
...(child.forkedFrom?.type === "node" ? [child.forkedFrom.nodeId] : []),
9505+
...(latestFollowupId === undefined ? [] : [latestFollowupId]),
9506+
],
94959507
})
94969508
.pipe(mapDispatchError(command));
94979509
const original = parent.subagents.find(
@@ -9501,6 +9513,27 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
95019513
task.id === (child.forkedFrom?.type === "node" ? child.forkedFrom.nodeId : undefined),
95029514
);
95039515
if (original === undefined || original.result === null) return;
9516+
const openFollowup = parent.subagents.find(
9517+
(task) =>
9518+
task.id === latestFollowupId &&
9519+
task.origin === "app_owned" &&
9520+
task.childThreadId === child.id &&
9521+
task.cancelledRunId === undefined &&
9522+
task.result === null,
9523+
);
9524+
if (openFollowup !== undefined) {
9525+
yield* emit(
9526+
events,
9527+
command,
9528+
)({
9529+
type: "run.updated",
9530+
threadId: child.id,
9531+
runId: run.id,
9532+
occurredAt: message.createdAt,
9533+
payload: { ...run, delegatedTaskId: openFollowup.id },
9534+
});
9535+
return;
9536+
}
95049537
const owner = followUpOwnerRun(parent.runs);
95059538
if (owner === null || owner.rootNodeId === null) return;
95069539
const now = message.createdAt;
@@ -14115,8 +14148,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1411514148
]);
1411614149
return;
1411714150
}
14118-
// A follow-up ends with the subagents its turns started, as the original task does.
14119-
if (delegatedTaskAwaitsSubagents(taskRuns, childControls.subagents)) return;
14151+
// A follow-up ends with the work it awaits, as the original task does. A cancelled task
14152+
// does not wait for the background work its cancel is stopping.
14153+
if (
14154+
delegatedTaskAwaitsWork(
14155+
taskRuns,
14156+
options.task.cancelledRunId === undefined
14157+
? childControls
14158+
: { subagents: childControls.subagents, providerThreads: [] },
14159+
)
14160+
)
14161+
return;
1412014162
if (
1412114163
yield* childAwaitsRestartContinuation(
1412214164
taskRuns.length === 0 ? childControls.runs : taskRuns,
@@ -15691,7 +15733,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1569115733
if (
1569215734
run === undefined ||
1569315735
delegatedTaskTerminalStatus(run.status) === null ||
15694-
delegatedTaskAwaitsSubagents(runs, child.subagents)
15736+
delegatedTaskAwaitsWork(runs, child)
1569515737
)
1569615738
return true;
1569715739
return yield* childAwaitsRestartContinuation(runs, run);

‎apps/server/src/orchestration-v2/RestartBackgroundNote.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type {
22
NodeId,
33
OrchestrationV2ConversationMessage,
44
OrchestrationV2PendingBackgroundTask,
5+
OrchestrationV2ProviderThread,
56
OrchestrationV2ProviderTurn,
67
OrchestrationV2RestartCancelledBackgroundWork,
78
OrchestrationV2Run,
@@ -10,6 +11,7 @@ import type {
1011
OrchestrationV2TurnItem,
1112
} from "@t3tools/contracts";
1213
import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection";
14+
import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
1315
import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
1416

1517
type Work = OrchestrationV2RestartCancelledBackgroundWork;
@@ -224,15 +226,28 @@ export function delegatedTaskRuns(
224226
return projection.runs.filter((run) => owned.has(run.id));
225227
}
226228

227-
/** A follow-up task's runs still owe a subagent they started its result. */
228-
export function delegatedTaskAwaitsSubagents(
229+
/**
230+
* A follow-up task's runs still owe a subagent they started its result, or the child still
231+
* awaits background work, as the original task waits on both.
232+
*/
233+
export function delegatedTaskAwaitsWork(
229234
runs: ReadonlyArray<OrchestrationV2Run>,
230-
subagents: ReadonlyArray<
231-
Pick<OrchestrationV2Subagent, "runId" | "status" | "completionDelivery">
232-
>,
235+
child: {
236+
readonly subagents: ReadonlyArray<
237+
Pick<OrchestrationV2Subagent, "runId" | "status" | "completionDelivery">
238+
>;
239+
readonly providerThreads: ReadonlyArray<
240+
Pick<OrchestrationV2ProviderThread, "pendingBackgroundTasks">
241+
>;
242+
},
233243
): boolean {
234244
const runIds = new Set<string | null>(runs.map((run) => run.id));
235-
return subagents.some((task) => runIds.has(task.runId) && subagentHoldsCompletion(task));
245+
return (
246+
child.subagents.some((task) => runIds.has(task.runId) && subagentHoldsCompletion(task)) ||
247+
child.providerThreads.some((thread) =>
248+
backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []),
249+
)
250+
);
236251
}
237252

238253
/** A follow-up task's latest run, passing over queued work it no longer waits on, as the original task does. */

0 commit comments

Comments
 (0)