@devries-cameron20 / t3code-1 / commits / 3443f02e57
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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

Yash Singh committed Oct 18, 2026 at 23:25 UTC 3443f02e57c7b91804dc57f4ba374b64c246ecb2
7 files changed +294 -39
apps/server/src/mcp/OrchestratorMcpService.ts
+30 -1
@@ -2229,6 +2229,30 @@ const make = Effect.gen(function* () {
2229 ),
2230 ),
2231 );
2232 + const stopped = yield* threadManagement
2233 + .getThreadRecords(current.childThreadId, ["runs"])
2234 + .pipe(Effect.mapError(threadManagementFailure));
2235 + for (const run of stopped.runs) {
2236 + if (
2237 + run.status !== "queued" ||
2238 + (run.delegatedTaskId !== input.taskId && run.id !== current.childRunId)
2239 + )
2240 + continue;
2241 + // Stop preserves the queue for Resume. Cancelling a task must also
2242 + // remove that task's queued turn, including a previously held one.
2243 + yield* threadManagement
2244 + .dispatch({
2245 + type: "queued-run.cancel",
2246 + commandId: stableCommandId({
2247 + scope,
2248 + requestKey: key,
2249 + operation: `cancel-task-queued-run:${run.id}`,
2250 + }),
2251 + threadId: current.childThreadId,
2252 + runId: run.id,
2253 + })
2254 + .pipe(Effect.mapError(threadManagementFailure));
2255 + }
2256 });
2257 // Checked above; a user raising one of these threads meanwhile is
2258 // caught again under that thread's lock, which leaves it running.
@@ -2265,7 +2289,12 @@ const make = Effect.gen(function* () {
2289 const child = yield* loadProjection(current.childThreadId);
2290 if (
2291 current.workState !== "waiting_for_children" &&
2268 - ThreadManagementService.latestActiveRun(child) === undefined
2292 + ThreadManagementService.latestActiveRun(child) === undefined &&
2293 + !child.runs.some(
2294 + (run) =>
2295 + run.status === "queued" &&
2296 + (run.delegatedTaskId === input.taskId || run.id === current.childRunId),
2297 + )
2298 ) {
2299 return yield* failure(
2300 "task_not_cancellable",
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+39
@@ -1864,6 +1864,16 @@ describe("orchestrator MCP toolkit", () => {
1864 legacyDelegatedRun,
1865 ),
1866 ).toBe(false);
1867 + const heldFollowupCall = yield* invoke("t3_thread_send", {
1868 + threadId: delegated.childThreadId,
1869 + message: "This queued follow-up must remain stopped until resumed.",
1870 + mode: "queue",
1871 + clientRequestId: "delegated-child-held-followup",
1872 + });
1873 + const heldFollowup = yield* decodeThreadSendResult(
1874 + heldFollowupCall.structuredContent,
1875 + ).pipe(Effect.orDie);
1876 + expect(heldFollowup.taskId).toBeDefined();
1877 const completedTaskCancelCall = yield* invoke("task_cancel", {
1878 taskId: delegated.taskId,
1879 reason: "Stop the child's later work too.",
@@ -1904,6 +1914,35 @@ describe("orchestrator MCP toolkit", () => {
1914 latestTerminalStatus: "interrupted",
1915 });
1916
1917 + yield* waitForProjection(orchestrator, parentThreadId, (projection) =>
1918 + projection.subagents.some(
1919 + (task) => task.id === heldFollowup.taskId && task.status === "idle",
1920 + ),
1921 + );
1922 + expect(
1923 + (yield* orchestrator.getThreadProjection(delegated.childThreadId)).runs.find(
1924 + (run) => run.id === heldFollowup.runId,
1925 + ),
1926 + ).toMatchObject({ status: "queued", queueHeld: true, startedAt: null });
1927 + const cancelHeldCall = yield* invoke("task_cancel", {
1928 + taskId: heldFollowup.taskId,
1929 + clientRequestId: "cancel-held-delegated-followup",
1930 + });
1931 + expect(
1932 + (yield* decodeTaskCancelResult(cancelHeldCall.structuredContent).pipe(Effect.orDie))
1933 + .status,
1934 + ).toBe("cancel_requested");
1935 + yield* waitForProjection(orchestrator, parentThreadId, (projection) =>
1936 + projection.subagents.some(
1937 + (task) => task.id === heldFollowup.taskId && task.status === "cancelled",
1938 + ),
1939 + );
1940 + expect(
1941 + (yield* orchestrator.getThreadProjection(delegated.childThreadId)).runs.find(
1942 + (run) => run.id === heldFollowup.runId,
1943 + ),
1944 + ).toMatchObject({ status: "cancelled", startedAt: null });
1945 +
1946 expect(childFollowup.taskId).toBeDefined();
1947 expect(activeChildFollowup.taskId).toBeDefined();
1948 yield* waitForContinuationOffers(2);
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+1 -1
@@ -92,7 +92,7 @@ const TaskStatusTool = Tool.make("task_status", {
92
93 const TaskCancelTool = Tool.make("task_cancel", {
94 description:
95 - "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.",
95 + "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.",
96 parameters: OrchestratorMcpTaskCancelInput,
97 success: OrchestratorMcpTaskCancelResult,
98 failure: OrchestratorMcpFailure,
apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+124
@@ -924,6 +924,130 @@ const seedRestartCancelledChild = (input: {
924 it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
925 "subagent follow-ups",
926 (it) => {
927 + it.effect("pauses queued follow-up cards and resumes them", () =>
928 + Effect.gen(function* () {
929 + const orchestrator = yield* Orchestrator.OrchestratorV2;
930 + const eventSink = yield* EventSink.EventSinkV2;
931 + const now = yield* DateTime.now;
932 + const parentThreadId = ThreadId.make("thread:held-followup-parent");
933 + const projectId = ProjectId.make("project:held-followup");
934 + const parentRunId = RunId.make("run:held-followup-parent");
935 + const rootNodeId = NodeId.make("node:held-followup-parent");
936 + yield* seedParentWithTerminalTask({
937 + threadId: parentThreadId,
938 + projectId,
939 + runId: parentRunId,
940 + rootNodeId,
941 + taskId: NodeId.make("node:held-followup-seed"),
942 + deliveryState: "acknowledged",
943 + now,
944 + });
945 + const child = yield* seedRestartCancelledChild({
946 + parentThreadId,
947 + projectId,
948 + parentRunId,
949 + rootNodeId,
950 + name: "held-followup-child",
951 + completionWake: "always",
952 + continuationPending: false,
953 + runStatus: "completed",
954 + now,
955 + });
956 + yield* orchestrator.recoverDelegatedTasks;
957 + const send = (name: string) =>
958 + orchestrator.dispatch({
959 + type: "message.dispatch",
960 + createdBy: "agent",
961 + creationSource: "mcp",
962 + commandId: CommandId.make(`command:held-followup:${name}`),
963 + threadId: child.childThreadId,
964 + senderThreadId: parentThreadId,
965 + messageId: MessageId.make(`message:held-followup:${name}`),
966 + text: name,
967 + attachments: [],
968 + dispatchMode: { type: "queue_after_active" },
969 + });
970 + yield* send("active");
971 + yield* send("queued");
972 + const before = yield* orchestrator.getThreadProjection(child.childThreadId);
973 + const active = before.runs.find((run) => run.ordinal === 2)!;
974 + const queued = before.runs.find((run) => run.ordinal === 3)!;
975 + assert.equal(queued.status, "queued");
976 + const waitForStatus = (afterSequence: number, status: string) =>
977 + eventSink.stream({ afterSequence, eventType: "subagent.updated" }).pipe(
978 + Stream.filter(
979 + (stored) =>
980 + stored.event.type === "subagent.updated" &&
981 + stored.event.payload.id === queued.delegatedTaskId &&
982 + stored.event.payload.status === status,
983 + ),
984 + Stream.take(1),
985 + Stream.runHead,
986 + );
987 + const afterSequence = yield* eventSink.latestSequence();
988 + yield* orchestrator.dispatch({
989 + type: "thread.stop",
990 + threadId: child.childThreadId,
991 + commandId: CommandId.make("command:held-followup:stop"),
992 + });
993 + yield* waitForStatus(afterSequence, "idle");
994 + const paused = yield* orchestrator.getThreadProjection(parentThreadId);
995 + const task = paused.subagents.find((row) => row.id === queued.delegatedTaskId)!;
996 + assert.equal(task.status, "idle");
997 + assert.isNull(task.result);
998 + assert.equal(paused.nodes.find((row) => row.id === task.id)?.status, "idle");
999 + assert.equal(
1000 + paused.turnItems.find((row) => row.type === "subagent" && row.subagentId === task.id)
1001 + ?.status,
1002 + "idle",
1003 + );
1004 + const endedSequence = yield* eventSink.latestSequence();
1005 + yield* eventSink.write({
1006 + events: [
1007 + {
1008 + id: EventId.make("event:held-followup-active-ended"),
1009 + type: "run.updated",
1010 + threadId: child.childThreadId,
1011 + runId: active.id,
1012 + occurredAt: now,
1013 + payload: { ...active, status: "interrupted", startedAt: now, completedAt: now },
1014 + },
1015 + ],
1016 + });
1017 + const activeTask = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find(
1018 + (row) => row.id === active.delegatedTaskId,
1019 + )!;
1020 + if (activeTask.result === null) {
1021 + yield* eventSink
1022 + .stream({ afterSequence: endedSequence, eventType: "subagent.updated" })
1023 + .pipe(
1024 + Stream.filter(
1025 + (stored) =>
1026 + stored.event.type === "subagent.updated" &&
1027 + stored.event.payload.id === active.delegatedTaskId &&
1028 + stored.event.payload.status === "interrupted",
1029 + ),
1030 + Stream.take(1),
1031 + Stream.runHead,
1032 + );
1033 + }
1034 + const shell = (yield* orchestrator.getShellSnapshot()).threads.find(
1035 + (row) => row.id === parentThreadId,
1036 + )!;
1037 + assert.isFalse((shell.pendingBackgroundTasks ?? []).some((row) => row.taskId === task.id));
1038 + const resumeSequence = yield* eventSink.latestSequence();
1039 + yield* orchestrator.dispatch({
1040 + type: "queue.resume",
1041 + threadId: child.childThreadId,
1042 + commandId: CommandId.make("command:held-followup:resume"),
1043 + });
1044 + yield* waitForStatus(resumeSequence, "running");
1045 + const resumed = yield* orchestrator.getThreadProjection(parentThreadId);
1046 + assert.equal(resumed.subagents.find((row) => row.id === task.id)?.status, "running");
1047 + assert.isNull(resumed.subagents.find((row) => row.id === task.id)?.result);
1048 + }),
1049 + );
1050 +
1051 const outcomes = [
1052 "completed",
1053 "failed",
apps/server/src/orchestration-v2/Orchestrator.ts
+90 -35
@@ -6981,7 +6981,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6981 title: child.title,
6982 completionWake: "always",
6983 completionDelivery: { state: "pending", observedByRunId: null },
6984 - status: run.status === "queued" ? "pending" : "running",
6984 + status: run.status === "queued" ? (run.queueHeld === true ? "idle" : "pending") : "running",
6985 progress: undefined,
6986 result: null,
6987 startedAt: now,
@@ -10196,7 +10196,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10196 >,
10197 options: {
10198 readonly settledContinuationOf?: RunId;
10199 - readonly taskId: NodeId;
10199 + readonly syncRunId?: RunId;
10200 + readonly task: OrchestrationV2Subagent;
10201 readonly resultRun?: OrchestrationV2Run;
10202 },
10203 ) =>
@@ -10210,10 +10211,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10211 ) {
10212 return;
10213 }
10213 - const taskRuns = childControls.runs.filter((run) => run.delegatedTaskId === options.taskId);
10214 + const taskRuns = childControls.runs.filter((run) => run.delegatedTaskId === options.task.id);
10215 const childRun =
10216 taskRuns.length === 0
10216 - ? options.taskId === forkedFrom.nodeId
10217 + ? options.task.id === forkedFrom.nodeId
10218 ? options.resultRun
10219 : undefined
10220 : taskRuns.toSorted((a, b) => b.ordinal - a.ordinal)[0];
@@ -10221,6 +10222,59 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10222 const outcome = runOutcome(childRun);
10223 const terminalStatus = delegatedTaskTerminalStatus(outcome);
10224 if (terminalStatus === null) {
10225 + if (childRun.delegatedTaskId === undefined || childRun.id !== options.syncRunId) return;
10226 + const task = options.task;
10227 + const status: OrchestrationV2Subagent["status"] =
10228 + childRun.status === "queued"
10229 + ? childRun.queueHeld === true
10230 + ? "idle"
10231 + : "pending"
10232 + : childRun.status === "waiting"
10233 + ? "waiting"
10234 + : "running";
10235 + if (task.result !== null || task.status === status) return;
10236 + const parent = yield* projectionStore.getThreadRecords(
10237 + childControls.thread.lineage.parentThreadId,
10238 + ["nodes", "turnItems"],
10239 + { turnItemTypes: ["subagent"] },
10240 + );
10241 + const now = yield* DateTime.now;
10242 + const scope = {
10243 + threadId: parent.thread.id,
10244 + ...(task.runId === null ? {} : { runId: task.runId }),
10245 + nodeId: task.id,
10246 + providerInstanceId: task.providerInstanceId,
10247 + occurredAt: now,
10248 + };
10249 + const node = parent.nodes.find((row) => row.id === task.id);
10250 + const item = parent.turnItems.find(
10251 + (row) => row.type === "subagent" && row.subagentId === task.id,
10252 + );
10253 + yield* writeSystemEvents([
10254 + {
10255 + ...scope,
10256 + type: "subagent.updated",
10257 + payload: { ...task, status, completedAt: null, updatedAt: now },
10258 + },
10259 + ...(node === undefined
10260 + ? []
10261 + : [
10262 + {
10263 + ...scope,
10264 + type: "node.updated" as const,
10265 + payload: { ...node, status, completedAt: null },
10266 + },
10267 + ]),
10268 + ...(item === undefined
10269 + ? []
10270 + : [
10271 + {
10272 + ...scope,
10273 + type: "turn-item.updated" as const,
10274 + payload: { ...item, status, completedAt: null, updatedAt: now },
10275 + },
10276 + ]),
10277 + ]);
10278 return;
10279 }
10280 if (
@@ -10265,7 +10319,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10319 );
10320 const task = parentProjection.subagents.find(
10321 (candidate) =>
10268 - candidate.id === options.taskId &&
10322 + candidate.id === options.task.id &&
10323 candidate.origin === "app_owned" &&
10324 candidate.childThreadId === childThreadId,
10325 );
@@ -10278,7 +10332,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10332 transfer.sourceThreadId === childThreadId &&
10333 transfer.targetThreadId === parentThreadId &&
10334 (transfer.sourcePoint.runId === childRun.id ||
10281 - (options.taskId === forkedFrom.nodeId && transfer.sourcePoint.runId === undefined)),
10335 + (options.task.id === forkedFrom.nodeId && transfer.sourcePoint.runId === undefined)),
10336 );
10337 if (existingResultTransfer !== undefined) {
10338 return;
@@ -10493,7 +10547,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10547
10548 const finalizeAppOwnedSubagent = (
10549 childThreadId: ThreadId,
10496 - options?: { readonly settledContinuationOf?: RunId },
10550 + options?: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId },
10551 ) =>
10552 Effect.gen(function* () {
10553 const childControls = yield* projectionStore.getThreadRecords(
@@ -10528,7 +10582,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10582 continue;
10583 yield* finalizeAppOwnedSubagentTask(childControls, {
10584 ...options,
10531 - taskId: task.id,
10585 + task,
10586 ...(progress.resultRun === undefined ? {} : { resultRun: progress.resultRun }),
10587 });
10588 }
@@ -11356,48 +11410,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11410 : threadDispatch.withLock(parentThreadId, dispatch);
11411 });
11412
11359 - const handleTerminalRun = (stored: OrchestrationV2StoredEvent) =>
11413 + const handleRunUpdate = (stored: OrchestrationV2StoredEvent) =>
11414 Effect.gen(function* () {
11415 + if (stored.event.type !== "run.updated") return;
11416 const threadId = stored.event.threadId;
11417 + const run = stored.event.payload;
11418 // finalize writes the parent thread and startNextQueuedRun writes this
11419 // thread, so each takes its own thread's lock, sequentially and never
11420 // nested: dispatchDelegatedTaskRequest already writes child events
11421 // while holding the parent lock, so nesting the parent lock inside the
11422 // child lock here would invert that order, and the keyed executor's
11423 // semaphores are neither reentrant nor deadlock-aware.
11368 - if (stored.event.type === "run.updated") {
11424 + if (delegatedTaskTerminalStatus(run.status) !== null) {
11425 yield* threadDispatch.withLock(
11426 threadId,
11371 - finalizeDelegatedCompletionDelivery(threadId, stored.event.payload.id),
11427 + finalizeDelegatedCompletionDelivery(threadId, run.id),
11428 );
11373 - }
11374 - yield* threadDispatch
11375 - .withLock(
11376 - threadId,
11377 - startNextQueuedRun(
11429 + yield* threadDispatch
11430 + .withLock(
11431 threadId,
11379 - stored.event.type === "run.updated"
11380 - ? {
11381 - endedRunId: stored.event.payload.id,
11382 - ...(stored.event.payload.status === "failed"
11383 - ? { failedRunId: stored.event.payload.id }
11384 - : {}),
11385 - }
11386 - : undefined,
11387 - ),
11388 - )
11389 - .pipe(
11390 - Effect.catchCause((cause) =>
11391 - Effect.logWarning("Failed to start the next queued V2 run", { threadId, cause }),
11392 - ),
11393 - );
11432 + startNextQueuedRun(threadId, {
11433 + endedRunId: run.id,
11434 + ...(run.status === "failed" ? { failedRunId: run.id } : {}),
11435 + }),
11436 + )
11437 + .pipe(
11438 + Effect.catchCause((cause) =>
11439 + Effect.logWarning("Failed to start the next queued V2 run", { threadId, cause }),
11440 + ),
11441 + );
11442 + }
11443 const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId);
11444 if (parentThreadId !== undefined) {
11396 - yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(threadId));
11445 + yield* threadDispatch.withLock(
11446 + parentThreadId,
11447 + finalizeAppOwnedSubagent(threadId, { syncRunId: run.id }),
11448 + );
11449 }
11450 }).pipe(
11451 Effect.catchCause((cause) =>
11400 - Effect.logWarning("Failed to react to terminal V2 run", {
11452 + Effect.logWarning("Failed to react to V2 run update", {
11453 threadId: stored.event.threadId,
11454 sequence: stored.sequence,
11455 cause,
@@ -11418,13 +11470,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11470 (stored) =>
11471 stored.event.type === "run.updated" &&
11472 !String(stored.commandId).startsWith("command:runtime-reconcile:") &&
11421 - (stored.event.payload.status === "completed" ||
11473 + ((stored.event.payload.delegatedTaskId !== undefined &&
11474 + (stored.event.payload.status === "queued" ||
11475 + stored.event.payload.status === "starting")) ||
11476 + stored.event.payload.status === "completed" ||
11477 stored.event.payload.status === "interrupted" ||
11478 stored.event.payload.status === "failed" ||
11479 stored.event.payload.status === "cancelled" ||
11480 stored.event.payload.status === "rolled_back"),
11481 ),
11427 - Stream.runForEach(handleTerminalRun),
11482 + Stream.runForEach(handleRunUpdate),
11483 Effect.forkDetach,
11484 );
11485
apps/server/src/orchestration-v2/SubagentProjection.test.ts
+7
@@ -205,6 +205,13 @@ it("waits for nested work and retains the report across monitor acknowledgements
205 "result_available",
206 );
207 for (const state of ["pending", "claimed"] as const) {
208 + assert.equal(
209 + delegatedTaskProgress({
210 + ...projection,
211 + subagents: [{ status: "idle", completionDelivery: { state, observedByRunId: null } }],
212 + }).state,
213 + "result_available",
214 + );
215 assert.equal(
216 delegatedTaskProgress({
217 ...projection,
packages/provider-core/src/server/subagentProjection.ts
+3 -2
@@ -250,8 +250,9 @@ export function delegatedTaskProgress(projection: {
250 isOrchestrationV2WorkActive(task.status) ||
251 // Publishing a child's result precedes scheduling its parent's wake.
252 // The parent still owes that follow-up even between those transactions.
253 - task.completionDelivery?.state === "pending" ||
254 - task.completionDelivery?.state === "claimed",
253 + (task.status !== "idle" &&
254 + (task.completionDelivery?.state === "pending" ||
255 + task.completionDelivery?.state === "claimed")),
256 ) ||
257 projection.providerThreads.some((thread) => (thread.pendingBackgroundTasks?.length ?? 0) > 0);
258 const resultRun = workRuns