Skip to content

Commit 9b0e0fe

Browse files
committed
fix(server): track resumed subagent follow-ups as separate tasks
1 parent d1e56e7 commit 9b0e0fe

14 files changed

Lines changed: 865 additions & 101 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: "completed" },
212+
],
204213
contextTransfers: [],
205214
messages: [],
206215
subagents: [],

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

Lines changed: 97 additions & 50 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,60 @@ 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 &&
407410
task.childThreadId === target.thread.id,
408411
);
412+
const taskIds = new Set(
413+
target.runs
414+
.filter((run) => returnedRunIds.has(run.id))
415+
.map((run) => run.delegatedTaskId ?? original?.id),
416+
);
417+
return parent.subagents.filter(
418+
(task) =>
419+
taskIds.has(task.id) &&
420+
task.origin === "app_owned" &&
421+
task.childThreadId === target.thread.id,
422+
);
423+
}
424+
425+
function taskResultTransfer(
426+
parent: Pick<OrchestrationV2ThreadProjection, "thread" | "contextTransfers">,
427+
child: Pick<OrchestrationV2ThreadProjection, "runs" | "contextTransfers">,
428+
task: OrchestrationV2Subagent,
429+
) {
430+
const originalRun = delegatedTaskRun(child, task);
431+
const resultRunIds = new Set(
432+
child.runs
433+
.filter(
434+
(run) =>
435+
run.delegatedTaskId === task.id ||
436+
(originalRun?.delegatedTaskId === undefined && run.delegatedTaskId === undefined),
437+
)
438+
.map((run) => run.id),
439+
);
440+
if (originalRun !== undefined) resultRunIds.add(originalRun.id);
441+
return parent.contextTransfers.find(
442+
(transfer) =>
443+
transfer.type === "subagent_result" &&
444+
transfer.sourceThreadId === task.childThreadId &&
445+
transfer.targetThreadId === parent.thread.id &&
446+
((transfer.sourcePoint.runId !== undefined && resultRunIds.has(transfer.sourcePoint.runId)) ||
447+
(transfer.sourcePoint.runId === undefined && originalRun?.delegatedTaskId === undefined)),
448+
);
409449
}
410450

411451
function pageIncludesTerminalTaskResult(input: {
@@ -418,12 +458,7 @@ function pageIncludesTerminalTaskResult(input: {
418458
>;
419459
readonly maxChars: number;
420460
}): 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-
);
461+
const transfer = taskResultTransfer(input.parent, input.target, input.task);
427462
if (transfer === undefined) return false;
428463
const run =
429464
transfer.sourcePoint.runId === undefined
@@ -1241,9 +1276,15 @@ const make = Effect.gen(function* () {
12411276
const childRun = delegatedTaskRun(childControls, task);
12421277
const terminalRun = latestTerminalResultRun(childControls, childRun);
12431278
const progress = delegatedTaskProgress(childControls);
1279+
const taskResultRun =
1280+
childRun?.delegatedTaskId === task.id
1281+
? childControls.runs
1282+
.filter((run) => run.delegatedTaskId === task.id)
1283+
.toSorted((a, b) => b.ordinal - a.ordinal)[0]
1284+
: progress.resultRun;
12441285
const resultRunIds = [
12451286
...new Set(
1246-
[progress.resultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),
1287+
[taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined),
12471288
),
12481289
];
12491290
const resultRecords = yield* threadManagement
@@ -1280,15 +1321,15 @@ const make = Effect.gen(function* () {
12801321
: childRun,
12811322
)
12821323
: workState === "result_available"
1283-
? taskStatusForRun(progress.resultRun ?? childRun)
1324+
? taskStatusForRun(taskResultRun ?? childRun)
12841325
: taskStatusForRun(childRun) === "queued"
12851326
? "queued"
12861327
: "running";
12871328
const derivedResult =
12881329
task.result !== null
12891330
? task.result
1290-
: progress.resultRun !== undefined && isTerminalTaskStatus(status)
1291-
? subagentResultForRun(childProjection, progress.resultRun).text
1331+
: taskResultRun !== undefined && isTerminalTaskStatus(status)
1332+
? subagentResultForRun(childProjection, taskResultRun).text
12921333
: null;
12931334
const resultTransfers = parentProjection.contextTransfers.filter(
12941335
(transfer) =>
@@ -1304,7 +1345,7 @@ const make = Effect.gen(function* () {
13041345
? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined)
13051346
: undefined) ??
13061347
null);
1307-
const resultTransfer = resultTransfers[0] ?? null;
1348+
const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null;
13081349
const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun);
13091350
const response = {
13101351
taskId: task.id,
@@ -2315,45 +2356,48 @@ const make = Effect.gen(function* () {
23152356
{ concurrency: 1 },
23162357
);
23172358
const messagesByThreadId = new Map(sourceMessages);
2318-
const task = parent === undefined ? undefined : directAppOwnedChildTask(parent, target);
2359+
const returnedRunIds = new Set(
2360+
page
2361+
.filter((row) => row.sourceThreadId === target.thread.id)
2362+
.map((row) => row.item.runId),
2363+
);
2364+
const tasks =
2365+
parent === undefined ? [] : directAppOwnedChildTasks(parent, target, returnedRunIds);
23192366
if (
23202367
parent !== undefined &&
23212368
scope.thread !== undefined &&
2322-
task !== undefined &&
2369+
tasks.length > 0 &&
23232370
(input.textOffset ?? 0) === 0
23242371
) {
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-
);
2372+
for (const task of tasks) {
2373+
const transfer = taskResultTransfer(parent, target, task);
2374+
const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id;
2375+
const resultRunIds = resultRunId === undefined ? [] : [resultRunId];
2376+
const resultRecords = yield* threadManagement
2377+
.getThreadRecords(target.thread.id, ["messages", "turnItems"], {
2378+
messageRoles: ["assistant"],
2379+
messageRunIds: resultRunIds,
2380+
turnItemRunIds: resultRunIds,
2381+
turnItemTypes: ["assistant_message", "error"],
2382+
})
2383+
.pipe(Effect.mapError(threadManagementFailure));
2384+
if (
2385+
pageIncludesTerminalTaskResult({
2386+
parent,
2387+
page,
2388+
task,
2389+
target: { ...target, ...resultRecords },
2390+
maxChars,
2391+
})
2392+
) {
2393+
yield* readTask(
2394+
scope as McpThreadInvocationScope,
2395+
task.id,
2396+
false,
2397+
true,
2398+
"thread-read-acknowledge",
2399+
);
2400+
}
23572401
}
23582402
}
23592403
return {
@@ -2419,6 +2463,9 @@ const make = Effect.gen(function* () {
24192463
threadId: input.threadId,
24202464
messageId,
24212465
runId: result.run.id,
2466+
...(result.run.delegatedTaskId === undefined
2467+
? {}
2468+
: { taskId: result.run.delegatedTaskId }),
24222469
status: result.run.status,
24232470
delivery: result.delivery,
24242471
} 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 ?? "",

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ export const ThreadUpdateTool = Tool.make("t3_thread_update", {
219219

220220
const ThreadSendTool = Tool.make("t3_thread_send", {
221221
description:
222-
"Send a message to any T3 thread in this environment. The target cannot have broader permission modes than the caller. Do not use a delegated task's childThreadId to start another review round here; use delegate_task with the full review context and a new clientRequestId for that round. Thread messages do not create a new delegated task or reopen a completed task. mode='auto' starts an idle thread, steers a fully active turn, or queues behind a turn that is not yet steerable. Use queue for a separate follow-up turn, steer for an in-flight update, or restart to interrupt-and-restart the active turn. clientRequestId makes retries idempotent.",
222+
"Send a message to any T3 thread in this environment. The target cannot have broader permission modes than the caller. Use delegate_task with the full review context and a new clientRequestId for independent review rounds. For a follow-up that needs the same child's conversation, send to its childThreadId. After the original task completes, a requested follow-up creates a fresh task in that child thread and returns taskId; its completion notifies the parent, and the original result stays unchanged. mode='auto' starts an idle thread, steers a fully active turn, or queues behind a turn that is not yet steerable. Use queue for a separate follow-up turn, steer for an in-flight update, or restart to interrupt-and-restart the active turn. clientRequestId makes retries idempotent.",
223223
parameters: OrchestratorMcpThreadSendInput,
224224
success: OrchestratorMcpThreadSendResult,
225225
failure: OrchestratorMcpFailure,

0 commit comments

Comments
 (0)