Skip to content

Commit c572cb7

Browse files
authored
fix(server): track resumed subagent follow-ups as separate tasks (pingdotgg#17696)
1 parent fa9f936 commit c572cb7

14 files changed

Lines changed: 954 additions & 122 deletions

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,16 @@ describe("OrchestratorMcpService", () => {
200200
} as unknown as OrchestrationV2ThreadProjection;
201201
const childProjection = {
202202
thread: { id: childThreadId },
203-
runs: [{ id: RunId.make("run:mcp-restart-child"), ordinal: 1, status: "cancelled" }],
203+
runs: [
204+
{
205+
id: RunId.make("run:mcp-restart-child"),
206+
ordinal: 1,
207+
status: "cancelled",
208+
delegatedTaskId: taskId,
209+
},
210+
// An unrelated later run cannot supply this follow-up's result.
211+
{ id: RunId.make("run:mcp-restart-later"), ordinal: 2, status: "running" },
212+
],
204213
contextTransfers: [],
205214
messages: [],
206215
subagents: [],

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

Lines changed: 109 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,8 @@ export function delegatedTaskRun(
351351
childProjection: Pick<OrchestrationV2ThreadProjection, "runs" | "contextTransfers">,
352352
task: OrchestrationV2Subagent,
353353
): OrchestrationV2Run | undefined {
354+
const taskRun = childProjection.runs.find((run) => run.delegatedTaskId === task.id);
355+
if (taskRun !== undefined) return taskRun;
354356
const spawnTransfer = childProjection.contextTransfers.find(
355357
(transfer) =>
356358
transfer.type === "subagent_spawn" &&
@@ -390,22 +392,62 @@ function isTerminalTaskStatus(
390392
);
391393
}
392394

393-
function directAppOwnedChildTask(
395+
function directAppOwnedChildTasks(
394396
parent: Pick<OrchestrationV2ThreadProjection, "thread" | "subagents">,
395-
target: Pick<OrchestrationV2ThreadProjection, "thread">,
396-
): OrchestrationV2Subagent | undefined {
397+
target: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
398+
returnedRunIds: ReadonlySet<RunId | null>,
399+
): ReadonlyArray<OrchestrationV2Subagent> {
397400
if (
398401
target.thread.lineage.parentThreadId !== parent.thread.id ||
399402
target.thread.lineage.relationshipToParent !== "subagent"
400403
) {
401-
return undefined;
404+
return [];
402405
}
403-
return parent.subagents.find(
406+
const original = parent.subagents.find(
404407
(task) =>
405408
task.origin === "app_owned" &&
406409
task.threadId === parent.thread.id &&
410+
task.id ===
411+
(target.thread.forkedFrom?.type === "node" ? target.thread.forkedFrom.nodeId : undefined) &&
407412
task.childThreadId === target.thread.id,
408413
);
414+
const taskIds = new Set(
415+
target.runs
416+
.filter((run) => returnedRunIds.has(run.id))
417+
.map((run) => run.delegatedTaskId ?? original?.id),
418+
);
419+
return parent.subagents.filter(
420+
(task) =>
421+
taskIds.has(task.id) &&
422+
task.origin === "app_owned" &&
423+
task.childThreadId === target.thread.id,
424+
);
425+
}
426+
427+
function taskResultTransfer(
428+
parent: Pick<OrchestrationV2ThreadProjection, "thread" | "contextTransfers">,
429+
child: Pick<OrchestrationV2ThreadProjection, "runs" | "contextTransfers">,
430+
task: OrchestrationV2Subagent,
431+
) {
432+
const originalRun = delegatedTaskRun(child, task);
433+
const resultRunIds = new Set(
434+
child.runs
435+
.filter(
436+
(run) =>
437+
run.delegatedTaskId === task.id ||
438+
(originalRun?.delegatedTaskId === undefined && run.delegatedTaskId === undefined),
439+
)
440+
.map((run) => run.id),
441+
);
442+
if (originalRun !== undefined) resultRunIds.add(originalRun.id);
443+
return parent.contextTransfers.find(
444+
(transfer) =>
445+
transfer.type === "subagent_result" &&
446+
transfer.sourceThreadId === task.childThreadId &&
447+
transfer.targetThreadId === parent.thread.id &&
448+
((transfer.sourcePoint.runId !== undefined && resultRunIds.has(transfer.sourcePoint.runId)) ||
449+
(transfer.sourcePoint.runId === undefined && originalRun?.delegatedTaskId === undefined)),
450+
);
409451
}
410452

411453
function pageIncludesTerminalTaskResult(input: {
@@ -418,12 +460,7 @@ function pageIncludesTerminalTaskResult(input: {
418460
>;
419461
readonly maxChars: number;
420462
}): boolean {
421-
const transfer = input.parent.contextTransfers.find(
422-
(transfer) =>
423-
transfer.type === "subagent_result" &&
424-
transfer.sourceThreadId === input.target.thread.id &&
425-
transfer.targetThreadId === input.parent.thread.id,
426-
);
463+
const transfer = taskResultTransfer(input.parent, input.target, input.task);
427464
if (transfer === undefined) return false;
428465
const run =
429466
transfer.sourcePoint.runId === undefined
@@ -1241,9 +1278,21 @@ const make = Effect.gen(function* () {
12411278
const childRun = delegatedTaskRun(childControls, task);
12421279
const terminalRun = latestTerminalResultRun(childControls, childRun);
12431280
const progress = delegatedTaskProgress(childControls);
1281+
const taskResultRun =
1282+
childRun?.delegatedTaskId === task.id
1283+
? childControls.runs
1284+
.filter((run) => run.delegatedTaskId === task.id)
1285+
.toSorted((a, b) => b.ordinal - a.ordinal)[0]
1286+
: progress.resultRun;
1287+
const taskWorkState =
1288+
childRun?.delegatedTaskId === task.id
1289+
? isTerminalTaskStatus(taskStatusForRun(taskResultRun))
1290+
? "result_available"
1291+
: "working"
1292+
: progress.state;
12441293
const resultRunIds = [
12451294
...new Set(
1246-
[progress.resultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),
1295+
[taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),
12471296
),
12481297
];
12491298
const resultRecords = yield* threadManagement
@@ -1263,12 +1312,12 @@ const make = Effect.gen(function* () {
12631312
// the child started working again after this read.
12641313
const heldForRestart =
12651314
task.result === null &&
1266-
progress.state === "result_available" &&
1315+
taskWorkState === "result_available" &&
12671316
(yield* threadManagement
1268-
.delegatedTaskResultPending(task.childThreadId)
1317+
.delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId)
12691318
.pipe(Effect.mapError(threadManagementFailure)));
12701319
const workState =
1271-
task.result !== null ? "result_available" : heldForRestart ? "working" : progress.state;
1320+
task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState;
12721321
const status =
12731322
task.result !== null
12741323
? taskStatusForRun(
@@ -1280,15 +1329,15 @@ const make = Effect.gen(function* () {
12801329
: childRun,
12811330
)
12821331
: workState === "result_available"
1283-
? taskStatusForRun(progress.resultRun ?? childRun)
1284-
: taskStatusForRun(childRun) === "queued"
1332+
? taskStatusForRun(taskResultRun ?? childRun)
1333+
: taskStatusForRun(taskResultRun ?? childRun) === "queued"
12851334
? "queued"
12861335
: "running";
12871336
const derivedResult =
12881337
task.result !== null
12891338
? task.result
1290-
: progress.resultRun !== undefined && isTerminalTaskStatus(status)
1291-
? subagentResultForRun(childProjection, progress.resultRun).text
1339+
: taskResultRun !== undefined && isTerminalTaskStatus(status)
1340+
? subagentResultForRun(childProjection, taskResultRun).text
12921341
: null;
12931342
const resultTransfers = parentProjection.contextTransfers.filter(
12941343
(transfer) =>
@@ -1304,7 +1353,7 @@ const make = Effect.gen(function* () {
13041353
? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined)
13051354
: undefined) ??
13061355
null);
1307-
const resultTransfer = resultTransfers[0] ?? null;
1356+
const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null;
13081357
const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun);
13091358
const response = {
13101359
taskId: task.id,
@@ -2315,45 +2364,48 @@ const make = Effect.gen(function* () {
23152364
{ concurrency: 1 },
23162365
);
23172366
const messagesByThreadId = new Map(sourceMessages);
2318-
const task = parent === undefined ? undefined : directAppOwnedChildTask(parent, target);
2367+
const returnedRunIds = new Set(
2368+
page
2369+
.filter((row) => row.sourceThreadId === target.thread.id)
2370+
.map((row) => row.item.runId),
2371+
);
2372+
const tasks =
2373+
parent === undefined ? [] : directAppOwnedChildTasks(parent, target, returnedRunIds);
23192374
if (
23202375
parent !== undefined &&
23212376
scope.thread !== undefined &&
2322-
task !== undefined &&
2377+
tasks.length > 0 &&
23232378
(input.textOffset ?? 0) === 0
23242379
) {
2325-
const transfer = parent.contextTransfers.find(
2326-
(transfer) =>
2327-
transfer.type === "subagent_result" &&
2328-
transfer.sourceThreadId === target.thread.id &&
2329-
transfer.targetThreadId === parent.thread.id,
2330-
);
2331-
const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id;
2332-
const resultRunIds = resultRunId === undefined ? [] : [resultRunId];
2333-
const resultRecords = yield* threadManagement
2334-
.getThreadRecords(target.thread.id, ["messages", "turnItems"], {
2335-
messageRoles: ["assistant"],
2336-
messageRunIds: resultRunIds,
2337-
turnItemRunIds: resultRunIds,
2338-
turnItemTypes: ["assistant_message", "error"],
2339-
})
2340-
.pipe(Effect.mapError(threadManagementFailure));
2341-
if (
2342-
pageIncludesTerminalTaskResult({
2343-
parent,
2344-
page,
2345-
task,
2346-
target: { ...target, ...resultRecords },
2347-
maxChars,
2348-
})
2349-
) {
2350-
yield* readTask(
2351-
scope as McpThreadInvocationScope,
2352-
task.id,
2353-
false,
2354-
true,
2355-
"thread-read-acknowledge",
2356-
);
2380+
for (const task of tasks) {
2381+
const transfer = taskResultTransfer(parent, target, task);
2382+
const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id;
2383+
const resultRunIds = resultRunId === undefined ? [] : [resultRunId];
2384+
const resultRecords = yield* threadManagement
2385+
.getThreadRecords(target.thread.id, ["messages", "turnItems"], {
2386+
messageRoles: ["assistant"],
2387+
messageRunIds: resultRunIds,
2388+
turnItemRunIds: resultRunIds,
2389+
turnItemTypes: ["assistant_message", "error"],
2390+
})
2391+
.pipe(Effect.mapError(threadManagementFailure));
2392+
if (
2393+
pageIncludesTerminalTaskResult({
2394+
parent,
2395+
page,
2396+
task,
2397+
target: { ...target, ...resultRecords },
2398+
maxChars,
2399+
})
2400+
) {
2401+
yield* readTask(
2402+
scope as McpThreadInvocationScope,
2403+
task.id,
2404+
false,
2405+
true,
2406+
"thread-read-acknowledge",
2407+
);
2408+
}
23572409
}
23582410
}
23592411
return {
@@ -2419,6 +2471,9 @@ const make = Effect.gen(function* () {
24192471
threadId: input.threadId,
24202472
messageId,
24212473
runId: result.run.id,
2474+
...(result.run.delegatedTaskId === undefined
2475+
? {}
2476+
: { taskId: result.run.delegatedTaskId }),
24222477
status: result.run.status,
24232478
delivery: result.delivery,
24242479
} satisfies OrchestratorMcpThreadSendResult;

‎apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts‎

Lines changed: 75 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1782,6 +1782,9 @@ describe("orchestrator MCP toolkit", () => {
17821782
expect(delegatedStatus.resultContextTransferId).not.toBeNull();
17831783
expect(delegatedStatus.latestTerminalResultContextTransferId).not.toBeNull();
17841784

1785+
// Wait-mode completion already returned its result while the parent was live.
1786+
yield* expectOffersToStay(0);
1787+
17851788
const childFollowupCall = yield* invoke("t3_thread_send", {
17861789
threadId: delegated.childThreadId,
17871790
message: "Confirm the delegated API boundary remains inspected.",
@@ -1924,10 +1927,14 @@ describe("orchestrator MCP toolkit", () => {
19241927
latestTerminalStatus: "interrupted",
19251928
});
19261929

1927-
// A wait-mode child (completionWake settled_only) that completes
1928-
// while the parent run is live does not offer a wake: the
1929-
// blocking delegate_task call above already returned the result.
1930-
yield* expectOffersToStay(0);
1930+
// Later requested work has its own delivery, including an interrupted follow-up.
1931+
expect(childFollowup.taskId).toBeDefined();
1932+
expect(activeChildFollowup.taskId).toBeDefined();
1933+
yield* waitForContinuationOffers(2);
1934+
yield* expectOffersToStay(2);
1935+
yield* invoke("task_status", { taskId: childFollowup.taskId });
1936+
yield* invoke("task_status", { taskId: activeChildFollowup.taskId });
1937+
yield* Ref.set(continuationOffers, []);
19311938

19321939
const repeatedDelegatedCall = yield* invoke("delegate_task", {
19331940
task: delegatedPrompt,
@@ -4007,6 +4014,18 @@ describe("orchestrator MCP toolkit", () => {
40074014
const pendingProjection = yield* orchestrator.getThreadProjection(
40084015
delegated.childThreadId,
40094016
);
4017+
const followupTasks = (yield* orchestrator.getThreadProjection(
4018+
parentThreadId,
4019+
)).subagents.filter(
4020+
(task) =>
4021+
task.childThreadId === delegated.childThreadId && task.id !== delegated.taskId,
4022+
);
4023+
expect(followupTasks).toHaveLength(2);
4024+
expect(followupTasks.every((task) => task.result === null)).toBe(true);
4025+
expect(followupTasks.map((task) => task.id)).toEqual([
4026+
runningFollowup.taskId,
4027+
queuedFollowup.taskId,
4028+
]);
40104029
expect(
40114030
pendingProjection.runs.find((run) => run.id === delegated.childRunId)?.status,
40124031
).toBe("completed");
@@ -4082,6 +4101,47 @@ describe("orchestrator MCP toolkit", () => {
40824101
expect(finalProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe(
40834102
"completed",
40844103
);
4104+
yield* orchestrator
4105+
.streamStoredEventsFrom({
4106+
threadId: parentThreadId,
4107+
afterSequence: finalSequence,
4108+
})
4109+
.pipe(
4110+
Stream.filter(
4111+
(stored) =>
4112+
stored.event.type === "subagent.updated" &&
4113+
stored.event.payload.id === followupTasks[1]!.id &&
4114+
stored.event.payload.status === "completed",
4115+
),
4116+
Stream.runHead,
4117+
Effect.flatMap(
4118+
Option.match({
4119+
onNone: () => Effect.die("Follow-up task did not settle."),
4120+
onSome: () => Effect.void,
4121+
}),
4122+
),
4123+
);
4124+
const finishedParent = yield* orchestrator.getThreadProjection(parentThreadId);
4125+
expect(
4126+
finishedParent.subagents.find((task) => task.id === followupTasks[0]!.id)?.status,
4127+
).toBe("interrupted");
4128+
expect(
4129+
finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id),
4130+
).toMatchObject({
4131+
status: "completed",
4132+
result: queuedFollowupResult,
4133+
});
4134+
expect(
4135+
finishedParent.contextTransfers.filter(
4136+
(transfer) =>
4137+
transfer.type === "subagent_result" &&
4138+
transfer.sourceThreadId === delegated.childThreadId,
4139+
),
4140+
).toHaveLength(3);
4141+
expect(
4142+
finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id)
4143+
?.completionDelivery?.state,
4144+
).toBe("claimed");
40854145
const finalStatusCall = yield* invoke("task_status", {
40864146
taskId: delegated.taskId,
40874147
});
@@ -4097,8 +4157,18 @@ describe("orchestrator MCP toolkit", () => {
40974157
latestTerminalRunId: queuedFollowup.runId,
40984158
latestTerminalStatus: "completed",
40994159
latestTerminalSummary: queuedFollowupResult,
4100-
latestTerminalResultContextTransferId: null,
41014160
});
4161+
expect(finalStatus.latestTerminalResultContextTransferId).not.toBeNull();
4162+
const read = yield* invoke("t3_thread_read", {
4163+
threadId: delegated.childThreadId,
4164+
limit: 100,
4165+
});
4166+
expect(read.isError).not.toBe(true);
4167+
const afterRead = yield* orchestrator.getThreadProjection(parentThreadId);
4168+
expect(
4169+
afterRead.subagents.find((task) => task.id === queuedFollowup.taskId)
4170+
?.completionDelivery?.state,
4171+
).toBe("acknowledged");
41024172
}).pipe(Effect.provide(layerTest));
41034173
}),
41044174
),

‎apps/server/src/mcp/toolkits/orchestrator/tools.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ describe("orchestrator MCP tool guidance", () => {
2222
assert.include(DelegateTaskTool.description ?? "", "childThreadId is backing storage");
2323
assert.include(
2424
OrchestratorToolkit.tools.t3_thread_send.description ?? "",
25-
"Do not use a delegated task's childThreadId to start another review round",
25+
"a requested follow-up creates a fresh task",
2626
);
2727
assert.include(
2828
OrchestratorToolkit.tools.task_cancel.description ?? "",

0 commit comments

Comments
 (0)