Skip to content
TypeScript

fix(server): keep queued subagent status in sync (#21487)

Yash Singh3443f02e57c7
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 004f577dc1b..86b54b238a1 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -2229,6 +2229,30 @@ const make = Effect.gen(function* () {
),
),
);
+ const stopped = yield* threadManagement
+ .getThreadRecords(current.childThreadId, ["runs"])
+ .pipe(Effect.mapError(threadManagementFailure));
+ for (const run of stopped.runs) {
+ if (
+ run.status !== "queued" ||
+ (run.delegatedTaskId !== input.taskId && run.id !== current.childRunId)
+ )
+ continue;
+ // Stop preserves the queue for Resume. Cancelling a task must also
+ // remove that task's queued turn, including a previously held one.
+ yield* threadManagement
+ .dispatch({
+ type: "queued-run.cancel",
+ commandId: stableCommandId({
+ scope,
+ requestKey: key,
+ operation: `cancel-task-queued-run:${run.id}`,
+ }),
+ threadId: current.childThreadId,
+ runId: run.id,
+ })
+ .pipe(Effect.mapError(threadManagementFailure));
+ }
});
// Checked above; a user raising one of these threads meanwhile is
// caught again under that thread's lock, which leaves it running.
@@ -2265,7 +2289,12 @@ const make = Effect.gen(function* () {
const child = yield* loadProjection(current.childThreadId);
if (
current.workState !== "waiting_for_children" &&
- ThreadManagementService.latestActiveRun(child) === undefined
+ ThreadManagementService.latestActiveRun(child) === undefined &&
+ !child.runs.some(
+ (run) =>
+ run.status === "queued" &&
+ (run.delegatedTaskId === input.taskId || run.id === current.childRunId),
+ )
) {
return yield* failure(
"task_not_cancellable",
diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
index 7db16a6a954..c7b5fc24509 100644
--- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
@@ -1864,6 +1864,16 @@ describe("orchestrator MCP toolkit", () => {
legacyDelegatedRun,
),
).toBe(false);
+ const heldFollowupCall = yield* invoke("t3_thread_send", {
+ threadId: delegated.childThreadId,
+ message: "This queued follow-up must remain stopped until resumed.",
+ mode: "queue",
+ clientRequestId: "delegated-child-held-followup",
+ });
+ const heldFollowup = yield* decodeThreadSendResult(
+ heldFollowupCall.structuredContent,
+ ).pipe(Effect.orDie);
+ expect(heldFollowup.taskId).toBeDefined();
const completedTaskCancelCall = yield* invoke("task_cancel", {
taskId: delegated.taskId,
reason: "Stop the child's later work too.",
@@ -1904,6 +1914,35 @@ describe("orchestrator MCP toolkit", () => {
latestTerminalStatus: "interrupted",
});
+ yield* waitForProjection(orchestrator, parentThreadId, (projection) =>
+ projection.subagents.some(
+ (task) => task.id === heldFollowup.taskId && task.status === "idle",
+ ),
+ );
+ expect(
+ (yield* orchestrator.getThreadProjection(delegated.childThreadId)).runs.find(
+ (run) => run.id === heldFollowup.runId,
+ ),
+ ).toMatchObject({ status: "queued", queueHeld: true, startedAt: null });
+ const cancelHeldCall = yield* invoke("task_cancel", {
+ taskId: heldFollowup.taskId,
+ clientRequestId: "cancel-held-delegated-followup",
+ });
+ expect(
+ (yield* decodeTaskCancelResult(cancelHeldCall.structuredContent).pipe(Effect.orDie))
+ .status,
+ ).toBe("cancel_requested");
+ yield* waitForProjection(orchestrator, parentThreadId, (projection) =>
+ projection.subagents.some(
+ (task) => task.id === heldFollowup.taskId && task.status === "cancelled",
+ ),
+ );
+ expect(
+ (yield* orchestrator.getThreadProjection(delegated.childThreadId)).runs.find(
+ (run) => run.id === heldFollowup.runId,
+ ),
+ ).toMatchObject({ status: "cancelled", startedAt: null });
+
expect(childFollowup.taskId).toBeDefined();
expect(activeChildFollowup.taskId).toBeDefined();
yield* waitForContinuationOffers(2);
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
index f96c070fbac..f0dabc0260e 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
@@ -92,7 +92,7 @@ const TaskStatusTool = Tool.make("task_status", {
const TaskCancelTool = Tool.make("task_cancel", {
description:
- "Needs an agent running inside a T3 thread. Stop a T3-owned delegated task and dispose its automatic parent delivery. Its child thread stops like a user Stop: the running turn is interrupted, queued turns are held, pull request watches end, and the tasks it delegated stop too. This includes later child-thread runs, even after the task is terminal. A terminal task returns its existing status, and published task results remain available.",
+ "Needs an agent running inside a T3 thread. Stop a T3-owned delegated task and dispose its automatic parent delivery. Its child thread stops like a user Stop: the running turn is interrupted, other queued turns are held, pull request watches end, and the tasks it delegated stop too. The task's own queued turn is cancelled, including when held in a stopped queue. This includes later child-thread runs, even after the task is terminal. A terminal task returns its existing status, and published task results remain available.",
parameters: OrchestratorMcpTaskCancelInput,
success: OrchestratorMcpTaskCancelResult,
failure: OrchestratorMcpFailure,
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
index 2fb707a58f2..5220c4b6799 100644
--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
@@ -924,6 +924,130 @@ const seedRestartCancelledChild = (input: {
it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
"subagent follow-ups",
(it) => {
+ it.effect("pauses queued follow-up cards and resumes them", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const now = yield* DateTime.now;
+ const parentThreadId = ThreadId.make("thread:held-followup-parent");
+ const projectId = ProjectId.make("project:held-followup");
+ const parentRunId = RunId.make("run:held-followup-parent");
+ const rootNodeId = NodeId.make("node:held-followup-parent");
+ yield* seedParentWithTerminalTask({
+ threadId: parentThreadId,
+ projectId,
+ runId: parentRunId,
+ rootNodeId,
+ taskId: NodeId.make("node:held-followup-seed"),
+ deliveryState: "acknowledged",
+ now,
+ });
+ const child = yield* seedRestartCancelledChild({
+ parentThreadId,
+ projectId,
+ parentRunId,
+ rootNodeId,
+ name: "held-followup-child",
+ completionWake: "always",
+ continuationPending: false,
+ runStatus: "completed",
+ now,
+ });
+ yield* orchestrator.recoverDelegatedTasks;
+ const send = (name: string) =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "agent",
+ creationSource: "mcp",
+ commandId: CommandId.make(`command:held-followup:${name}`),
+ threadId: child.childThreadId,
+ senderThreadId: parentThreadId,
+ messageId: MessageId.make(`message:held-followup:${name}`),
+ text: name,
+ attachments: [],
+ dispatchMode: { type: "queue_after_active" },
+ });
+ yield* send("active");
+ yield* send("queued");
+ const before = yield* orchestrator.getThreadProjection(child.childThreadId);
+ const active = before.runs.find((run) => run.ordinal === 2)!;
+ const queued = before.runs.find((run) => run.ordinal === 3)!;
+ assert.equal(queued.status, "queued");
+ const waitForStatus = (afterSequence: number, status: string) =>
+ eventSink.stream({ afterSequence, eventType: "subagent.updated" }).pipe(
+ Stream.filter(
+ (stored) =>
+ stored.event.type === "subagent.updated" &&
+ stored.event.payload.id === queued.delegatedTaskId &&
+ stored.event.payload.status === status,
+ ),
+ Stream.take(1),
+ Stream.runHead,
+ );
+ const afterSequence = yield* eventSink.latestSequence();
+ yield* orchestrator.dispatch({
+ type: "thread.stop",
+ threadId: child.childThreadId,
+ commandId: CommandId.make("command:held-followup:stop"),
+ });
+ yield* waitForStatus(afterSequence, "idle");
+ const paused = yield* orchestrator.getThreadProjection(parentThreadId);
+ const task = paused.subagents.find((row) => row.id === queued.delegatedTaskId)!;
+ assert.equal(task.status, "idle");
+ assert.isNull(task.result);
+ assert.equal(paused.nodes.find((row) => row.id === task.id)?.status, "idle");
+ assert.equal(
+ paused.turnItems.find((row) => row.type === "subagent" && row.subagentId === task.id)
+ ?.status,
+ "idle",
+ );
+ const endedSequence = yield* eventSink.latestSequence();
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make("event:held-followup-active-ended"),
+ type: "run.updated",
+ threadId: child.childThreadId,
+ runId: active.id,
+ occurredAt: now,
+ payload: { ...active, status: "interrupted", startedAt: now, completedAt: now },
+ },
+ ],
+ });
+ const activeTask = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find(
+ (row) => row.id === active.delegatedTaskId,
+ )!;
+ if (activeTask.result === null) {
+ yield* eventSink
+ .stream({ afterSequence: endedSequence, eventType: "subagent.updated" })
+ .pipe(
+ Stream.filter(
+ (stored) =>
+ stored.event.type === "subagent.updated" &&
+ stored.event.payload.id === active.delegatedTaskId &&
+ stored.event.payload.status === "interrupted",
+ ),
+ Stream.take(1),
+ Stream.runHead,
+ );
+ }
+ const shell = (yield* orchestrator.getShellSnapshot()).threads.find(
+ (row) => row.id === parentThreadId,
+ )!;
+ assert.isFalse((shell.pendingBackgroundTasks ?? []).some((row) => row.taskId === task.id));
+ const resumeSequence = yield* eventSink.latestSequence();
+ yield* orchestrator.dispatch({
+ type: "queue.resume",
+ threadId: child.childThreadId,
+ commandId: CommandId.make("command:held-followup:resume"),
+ });
+ yield* waitForStatus(resumeSequence, "running");
+ const resumed = yield* orchestrator.getThreadProjection(parentThreadId);
+ assert.equal(resumed.subagents.find((row) => row.id === task.id)?.status, "running");
+ assert.isNull(resumed.subagents.find((row) => row.id === task.id)?.result);
+ }),
+ );
+
const outcomes = [
"completed",
"failed",
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 29ba67bdf6e..11689485e6e 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -6981,7 +6981,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
title: child.title,
completionWake: "always",
completionDelivery: { state: "pending", observedByRunId: null },
- status: run.status === "queued" ? "pending" : "running",
+ status: run.status === "queued" ? (run.queueHeld === true ? "idle" : "pending") : "running",
progress: undefined,
result: null,
startedAt: now,
@@ -10196,7 +10196,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
>,
options: {
readonly settledContinuationOf?: RunId;
- readonly taskId: NodeId;
+ readonly syncRunId?: RunId;
+ readonly task: OrchestrationV2Subagent;
readonly resultRun?: OrchestrationV2Run;
},
) =>
@@ -10210,10 +10211,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
) {
return;
}
- const taskRuns = childControls.runs.filter((run) => run.delegatedTaskId === options.taskId);
+ const taskRuns = childControls.runs.filter((run) => run.delegatedTaskId === options.task.id);
const childRun =
taskRuns.length === 0
- ? options.taskId === forkedFrom.nodeId
+ ? options.task.id === forkedFrom.nodeId
? options.resultRun
: undefined
: taskRuns.toSorted((a, b) => b.ordinal - a.ordinal)[0];
@@ -10221,6 +10222,59 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const outcome = runOutcome(childRun);
const terminalStatus = delegatedTaskTerminalStatus(outcome);
if (terminalStatus === null) {
+ if (childRun.delegatedTaskId === undefined || childRun.id !== options.syncRunId) return;
+ const task = options.task;
+ const status: OrchestrationV2Subagent["status"] =
+ childRun.status === "queued"
+ ? childRun.queueHeld === true
+ ? "idle"
+ : "pending"
+ : childRun.status === "waiting"
+ ? "waiting"
+ : "running";
+ if (task.result !== null || task.status === status) return;
+ const parent = yield* projectionStore.getThreadRecords(
+ childControls.thread.lineage.parentThreadId,
+ ["nodes", "turnItems"],
+ { turnItemTypes: ["subagent"] },
+ );
+ const now = yield* DateTime.now;
+ const scope = {
+ threadId: parent.thread.id,
+ ...(task.runId === null ? {} : { runId: task.runId }),
+ nodeId: task.id,
+ providerInstanceId: task.providerInstanceId,
+ occurredAt: now,
+ };
+ const node = parent.nodes.find((row) => row.id === task.id);
+ const item = parent.turnItems.find(
+ (row) => row.type === "subagent" && row.subagentId === task.id,
+ );
+ yield* writeSystemEvents([
+ {
+ ...scope,
+ type: "subagent.updated",
+ payload: { ...task, status, completedAt: null, updatedAt: now },
+ },
+ ...(node === undefined
+ ? []
+ : [
+ {
+ ...scope,
+ type: "node.updated" as const,
+ payload: { ...node, status, completedAt: null },
+ },
+ ]),
+ ...(item === undefined
+ ? []
+ : [
+ {
+ ...scope,
+ type: "turn-item.updated" as const,
+ payload: { ...item, status, completedAt: null, updatedAt: now },
+ },
+ ]),
+ ]);
return;
}
if (
@@ -10265,7 +10319,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
);
const task = parentProjection.subagents.find(
(candidate) =>
- candidate.id === options.taskId &&
+ candidate.id === options.task.id &&
candidate.origin === "app_owned" &&
candidate.childThreadId === childThreadId,
);
@@ -10278,7 +10332,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
transfer.sourceThreadId === childThreadId &&
transfer.targetThreadId === parentThreadId &&
(transfer.sourcePoint.runId === childRun.id ||
- (options.taskId === forkedFrom.nodeId && transfer.sourcePoint.runId === undefined)),
+ (options.task.id === forkedFrom.nodeId && transfer.sourcePoint.runId === undefined)),
);
if (existingResultTransfer !== undefined) {
return;
@@ -10493,7 +10547,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const finalizeAppOwnedSubagent = (
childThreadId: ThreadId,
- options?: { readonly settledContinuationOf?: RunId },
+ options?: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId },
) =>
Effect.gen(function* () {
const childControls = yield* projectionStore.getThreadRecords(
@@ -10528,7 +10582,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
continue;
yield* finalizeAppOwnedSubagentTask(childControls, {
...options,
- taskId: task.id,
+ task,
...(progress.resultRun === undefined ? {} : { resultRun: progress.resultRun }),
});
}
@@ -11356,48 +11410,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
: threadDispatch.withLock(parentThreadId, dispatch);
});
- const handleTerminalRun = (stored: OrchestrationV2StoredEvent) =>
+ const handleRunUpdate = (stored: OrchestrationV2StoredEvent) =>
Effect.gen(function* () {
+ if (stored.event.type !== "run.updated") return;
const threadId = stored.event.threadId;
+ const run = stored.event.payload;
// finalize writes the parent thread and startNextQueuedRun writes this
// thread, so each takes its own thread's lock, sequentially and never
// nested: dispatchDelegatedTaskRequest already writes child events
// while holding the parent lock, so nesting the parent lock inside the
// child lock here would invert that order, and the keyed executor's
// semaphores are neither reentrant nor deadlock-aware.
- if (stored.event.type === "run.updated") {
+ if (delegatedTaskTerminalStatus(run.status) !== null) {
yield* threadDispatch.withLock(
threadId,
- finalizeDelegatedCompletionDelivery(threadId, stored.event.payload.id),
+ finalizeDelegatedCompletionDelivery(threadId, run.id),
);
- }
- yield* threadDispatch
- .withLock(
- threadId,
- startNextQueuedRun(
+ yield* threadDispatch
+ .withLock(
threadId,
- stored.event.type === "run.updated"
- ? {
- endedRunId: stored.event.payload.id,
- ...(stored.event.payload.status === "failed"
- ? { failedRunId: stored.event.payload.id }
- : {}),
- }
- : undefined,
- ),
- )
- .pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("Failed to start the next queued V2 run", { threadId, cause }),
- ),
- );
+ startNextQueuedRun(threadId, {
+ endedRunId: run.id,
+ ...(run.status === "failed" ? { failedRunId: run.id } : {}),
+ }),
+ )
+ .pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("Failed to start the next queued V2 run", { threadId, cause }),
+ ),
+ );
+ }
const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId);
if (parentThreadId !== undefined) {
- yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(threadId));
+ yield* threadDispatch.withLock(
+ parentThreadId,
+ finalizeAppOwnedSubagent(threadId, { syncRunId: run.id }),
+ );
}
}).pipe(
Effect.catchCause((cause) =>
- Effect.logWarning("Failed to react to terminal V2 run", {
+ Effect.logWarning("Failed to react to V2 run update", {
threadId: stored.event.threadId,
sequence: stored.sequence,
cause,
@@ -11418,13 +11470,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
(stored) =>
stored.event.type === "run.updated" &&
!String(stored.commandId).startsWith("command:runtime-reconcile:") &&
- (stored.event.payload.status === "completed" ||
+ ((stored.event.payload.delegatedTaskId !== undefined &&
+ (stored.event.payload.status === "queued" ||
+ stored.event.payload.status === "starting")) ||
+ stored.event.payload.status === "completed" ||
stored.event.payload.status === "interrupted" ||
stored.event.payload.status === "failed" ||
stored.event.payload.status === "cancelled" ||
stored.event.payload.status === "rolled_back"),
),
- Stream.runForEach(handleTerminalRun),
+ Stream.runForEach(handleRunUpdate),
Effect.forkDetach,
);
diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts
index 7524f250ba5..961add539fb 100644
--- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts
+++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts
@@ -205,6 +205,13 @@ it("waits for nested work and retains the report across monitor acknowledgements
"result_available",
);
for (const state of ["pending", "claimed"] as const) {
+ assert.equal(
+ delegatedTaskProgress({
+ ...projection,
+ subagents: [{ status: "idle", completionDelivery: { state, observedByRunId: null } }],
+ }).state,
+ "result_available",
+ );
assert.equal(
delegatedTaskProgress({
...projection,
diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts
index cd46d5b0301..8ebdfbceb45 100644
--- a/packages/provider-core/src/server/subagentProjection.ts
+++ b/packages/provider-core/src/server/subagentProjection.ts
@@ -250,8 +250,9 @@ export function delegatedTaskProgress(projection: {
isOrchestrationV2WorkActive(task.status) ||
// Publishing a child's result precedes scheduling its parent's wake.
// The parent still owes that follow-up even between those transactions.
- task.completionDelivery?.state === "pending" ||
- task.completionDelivery?.state === "claimed",
+ (task.status !== "idle" &&
+ (task.completionDelivery?.state === "pending" ||
+ task.completionDelivery?.state === "claimed")),
) ||
projection.providerThreads.some((thread) => (thread.pendingBackgroundTasks?.length ?? 0) > 0);
const resultRun = workRuns