fix(orchestration): deliver results from subagent follow-ups #15004
ClosedYash-Singh1(GitHub profile, opens in a new tab)wants to merge 30 commits into
main fromt3code/fix-followup-subagent-statusopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge closed this
Yash-Singh1(GitHub profile, opens in a new tab) reopened this
- packages/client-runtime/src/state/threadShell.ts lines 87 to 130Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -63,0 +105,21 @@105+ }106+ if (tasks.length === (thread.pendingBackgroundTasks?.length ?? 0)) return thread;107+ const previous = derived.get(thread);108+ if (109+ previous?.pendingBackgroundTasks?.length === tasks.length &&110+ tasks.every((task, index) => {111+ const old = previous.pendingBackgroundTasks?.[index];112+ return (113+ old?.taskId === task.taskId &&114+ old.kind === task.kind &&115+ old.description === task.description &&116+ (old.kind !== "subagent" ||117+ task.kind !== "subagent" ||118+ old.childThreadId === task.childThreadId)119+ );120+ })121+ )122+ return previous;123+ const next = { ...thread, pendingBackgroundTasks: tasks };124+ derived.set(thread, next);125+ return next;
juliusmarminge added labelsmacroscope-review
- packages/client-runtime/src/operations/commands.ts lines 849 to 868OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -798,0 +848,21 @@848+ const result = yield* dispatch({849+ type: "run.interrupt",850+ commandId: childCommandId,851+ threadId: childThreadId,852+ runId: childRun.id,853+ holdQueue: true,854+ });855+ childSequence = result.sequence;856+ } else {857+ // A queued follow-up has no provider turn to interrupt yet.858+ for (const queued of child.runs.filter((run) => run.status === "queued")) {859+ const result = yield* dispatch({860+ type: "queued-run.cancel",861+ commandId: CommandId.make(`${childCommandId}:${queued.id}`),862+ threadId: childThreadId,863+ runId: queued.id,864+ });865+ childSequence = result.sequence;866+ }867+ }868+ }
Yash-Singh1(GitHub profile, opens in a new tab) changed the title
- apps/server/src/orchestration-v2/Orchestrator.ts line 9771Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -8540,10 +8550,11 @@85408550 if (task === undefined) {85418551 return;85428552 }8543- const existingResultTransfer = parentProjection.contextTransfers.find(8553+ const resultTransfers = parentProjection.contextTransfers.filter(85448554 (transfer) =>85458555 transfer.type === "subagent_result" &&85468556 transfer.sourceThreadId === childThreadId &&85478557 transfer.targetThreadId === parentThreadId,85488558 );8549- if (existingResultTransfer !== undefined) {8559+ if (8560+ resultTransfers.some(packages/contracts/src/orchestrationV2.ts line 3031Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2805,3 +2805,5 @@28052805 commandId: CommandId,28062806 parentThreadId: ThreadId,28072807 taskId: NodeId,2808+ /** The child result read by the observer, to avoid consuming a newer delivery. */2809+ resultRunId: Schema.optional(RunId),
- apps/server/src/mcp/OrchestratorMcpService.ts line 1353Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1134,3 +1134,4 @@11341134 }),11351135 parentThreadId: scope.threadId,11361136 taskId,1137+ ...(terminalRun === undefined ? {} : { resultRunId: terminalRun.id }),
- apps/server/src/orchestration-v2/ProjectionStore.ts lines 515 to 521OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -501,12 +509,13 @@509+ .map((transfer) => transfer.sourcePoint.runId),510+ );501511 return (502512 projection.thread.lineage.relationshipToParent === "subagent" &&503513 parentThreadId !== null &&504514 projection.thread.forkedFrom?.type === "node" &&505- ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(506- projection.runs.at(-1)?.status ?? "idle",507- ) &&508- !projection.contextTransfers.some(509- (transfer) =>510- transfer.type === "subagent_result" &&511- transfer.sourceThreadId === projection.thread.id &&512- transfer.targetThreadId === parentThreadId,515+ projection.runs.some(516+ (run) =>517+ ["completed", "interrupted", "failed", "cancelled", "rolled_back"].includes(518+ run.status,519+ ) &&520+ !deliveredRunIds.has(run.id) &&521+ !(run.ordinal === 1 && deliveredRunIds.has(undefined)),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/Orchestrator.ts line 4804Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4388,0 +4430,21 @@4430+ const parent = yield* mapDispatchError(command)(4431+ projectionStore.getThreadRecords(parentThreadId, ["runs", "subagents"]),4432+ );4433+ const task = parent.subagents.find(4434+ (task) =>4435+ task.id === childOrigin.nodeId &&4436+ task.origin === "app_owned" &&4437+ task.childThreadId === command.threadId,4438+ );4439+ if (task !== undefined) {4440+ const latestRun = parent.runs.at(-1);4441+ const wake =4442+ latestRun === undefined4443+ ? undefined4444+ : (yield* mapDispatchError(command)(4445+ projectionStore.getThreadRecords(parentThreadId, ["messages"], {4446+ messageIds: [latestRun.userMessageId],4447+ }),4448+ )).messages[0];4449+ const originalParentRun = parent.runs.find((run) => run.id === task.runId);4450+ delegatedTaskParentRunId =packages/client-runtime/src/operations/commands.ts lines 776 to 785OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -771,8 +773,13 @@771773 input: InterruptThreadTurnInput,772774 ) {773775 let runId = input.runId ?? (input.turnId as RunId | undefined);776+ let parentProjection: OrchestrationV2ThreadProjection | undefined;774777 if (runId === undefined) {775- const projection = yield* getProjection(input.threadId);778+ const projection = yield* request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, {779+ threadId: input.threadId,780+ includeInterruptTargets: true,781+ });782+ parentProjection = projection;776783 runId = projection.runs.findLast(777784 (run) =>778785 run.status === "preparing" ||
- apps/server/src/orchestration-v2/Orchestrator.ts line 10795Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -9754,4 +9918,11 @@97549918 });9755991997569920 const dispatchWithReceipt = (command: OrchestrationV2ServerCommand) =>9757- threadDispatch.withLock(commandThreadId(command), dispatchWithReceiptEffect(command));9921+ Effect.gen(function* () {9922+ const dispatch = threadDispatch.withLock(9923+ commandThreadId(command),9924+ dispatchWithReceiptEffect(command),9925+ );9926+ if (command.type !== "message.dispatch" && command.type !== "queue.resume")9927+ return yield* dispatch;9928+ const parentId = yield* appOwnedSubagentParentThreadId(commandThreadId(command)).pipe(apps/server/src/orchestration-v2/Orchestrator.ts lines 10040 to 10049OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -9835,0 +10029,21 @@10029+ ]);10030+ const deliveredRunIds = new Set(10031+ parent.contextTransfers10032+ .filter(10033+ (transfer) =>10034+ transfer.type === "subagent_result" &&10035+ transfer.sourceThreadId === threadId &&10036+ transfer.targetThreadId === parentThreadId,10037+ )10038+ .map((transfer) => transfer.sourcePoint.runId),10039+ );10040+ for (const run of child.runs.toSorted(10041+ (left, right) => left.ordinal - right.ordinal,10042+ )) {10043+ if (10044+ ["completed", "interrupted", "failed", "cancelled"].includes(run.status) &&10045+ (run.startedAt !== null || run.ordinal === 1) &&10046+ !monitorRunIds.has(run.id) &&10047+ !deliveredRunIds.has(run.id) &&10048+ !(run.ordinal === 1 && deliveredRunIds.has(undefined))10049+ ) {
- apps/server/src/orchestration-v2/ProjectionStore.ts lines 4830 to 4833OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4755,0 +4813,21 @@4813+ const getChildInterruptTargets = (threadId: ThreadId) =>4814+ Effect.gen(function* () {4815+ // Filter by current work before decoding controls. An idle child's4816+ // transcript and historical runs never enter this read.4817+ const candidates = yield* sql<{ readonly thread_id: string }>`4818+ SELECT DISTINCT child.thread_id4819+ FROM orchestration_v2_projection_subagents task4820+ JOIN orchestration_v2_projection_threads child ON child.thread_id = task.child_thread_id4821+ WHERE task.thread_id = ${threadId} AND task.origin = 'app_owned'4822+ AND child.archived_at IS NULL AND child.deleted_at IS NULL4823+ AND json_extract(child.payload_json, '$.lineage.parentThreadId') = ${threadId}4824+ AND json_extract(child.payload_json, '$.lineage.relationshipToParent') = 'subagent'4825+ AND json_extract(child.payload_json, '$.forkedFrom.type') = 'node'4826+ AND json_extract(child.payload_json, '$.forkedFrom.nodeId') = task.subagent_id4827+ AND (4828+ EXISTS (SELECT 1 FROM orchestration_v2_projection_runs run4829+ WHERE run.thread_id = child.thread_id AND run.status IN ('queued','preparing','starting','running','waiting'))4830+ OR EXISTS (SELECT 1 FROM orchestration_v2_projection_provider_threads provider4831+ WHERE provider.thread_id = child.thread_id AND4832+ CASE WHEN json_valid(provider.payload_json) THEN json_array_length(provider.payload_json, '$.pendingBackgroundTasks') > 0 ELSE 0 END)4833+ OR EXISTS (SELECT 1 FROM orchestration_v2_projection_turn_items item
- apps/server/src/orchestration-v2/Orchestrator.ts lines 1895 to 1909OutdatedResolvedby Yash-Singh1(GitHub profile, opens in a new tab)@@ -1892,4 +1892,18 @@18921892 // valid observations can race after their read preflight. Re-emit the18931893 // existing task row so the second dispatch is a successful idempotent18941894 // no-op rather than "already acknowledged/disposed" or empty-events.1895+ const resultTransfers = projection.contextTransfers.filter(1896+ (transfer) =>1897+ transfer.type === "subagent_result" &&1898+ transfer.sourceThreadId === task.childThreadId &&1899+ transfer.targetThreadId === command.parentThreadId,1900+ );1901+ const latestResultTransfer = resultTransfers.at(-1);18951902 if (1903+ (command.type === "delegated_task.completion-delivery.acknowledge" &&1904+ (command.resultRunId === undefined1905+ ? // Older callers can acknowledge the original result, but cannot1906+ // identify which follow-up they read.1907+ resultTransfers.length > 11908+ : latestResultTransfer?.sourcePoint.runId !== undefined &&1909+ latestResultTransfer.sourcePoint.runId !== command.resultRunId)) ||apps/server/src/orchestration-v2/Orchestrator.ts lines 10043 to 10044OutdatedResolvedby Yash-Singh1(GitHub profile, opens in a new tab)@@ -9866,4 +10035,10 @@986610035 });986710036986810037 const dispatchWithReceipt = (command: OrchestrationV2ServerCommand) =>9869- threadDispatch.withLock(commandThreadId(command), dispatchWithReceiptEffect(command));10038+ Effect.gen(function* () {10039+ const dispatch = threadDispatch.withLock(10040+ commandThreadId(command),10041+ dispatchWithReceiptEffect(command),10042+ );10043+ if (command.type !== "message.dispatch" && command.type !== "queue.resume")10044+ return yield* dispatch;packages/client-runtime/src/state/threadSubagents.ts lines 66 to 76OutdatedResolvedby Yash-Singh1(GitHub profile, opens in a new tab)@@ -52,4 +63,14 @@5263 );5364 const runId = activeRun?.id ?? latestUpdated.runId;5465 const subagents = copySorted(55- projection.subagents.filter((subagent) => subagent.runId === runId),66+ projection.subagents.flatMap((subagent) => {67+ const live = withSubagentThreadActivity(68+ subagent,69+ subagent.childThreadId === null ? undefined : children?.get(subagent.childThreadId),70+ );71+ return subagent.runId === runId ||72+ (subagent.childThreadId !== null &&73+ activeSubagentThreadStatus(children?.get(subagent.childThreadId)) !== null)74+ ? [live]75+ : [];76+ }),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/mcp/OrchestratorMcpService.ts line 2332Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1940,4 +1946,4 @@19401946 task !== undefined &&19411947 (input.textOffset ?? 0) === 019421948 ) {1943- const transfer = parent.contextTransfers.find(1949+ const transfer = parent.contextTransfers.findLast(
- apps/web/src/components/ChatView.tsx line 3542OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3539,3 +3539,4 @@35393539 [activeThreadLiveTokenUsage, serverVisibleTurnItems, serverProjection],35403540 );35413541 const pendingBackgroundTasks = useMemo(() => {3542+ if (activeThreadShell !== null) return activeThreadShell.pendingBackgroundTasks;
- apps/server/src/mcp/OrchestratorMcpService.ts line 1165OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1168,5 +1161,5 @@11681161 messages: [...childControls.messages, ...resultRecords.messages],11691162 turnItems: resultRecords.turnItems,11701163 };1171- // A restart cut the child's run and its continuation has not settled, or1172- // the child started working again after this read.1164+ const currentRun =1165+ childControls.runs.findLast((run) =>
- apps/server/src/orchestration-v2/Orchestrator.ts line 4765Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4654,3 +4667,14 @@46544667 }46554668 }46564669 }4670+ // Capture ownership at request time. A later Stop/archive must still4671+ // dispose this run's delivery, while a fresh request can use a new cohort.4672+ const existingRequest = projection.runs.find(4673+ (run) => run.userMessageId === command.messageId,4674+ );4675+ let delegatedTaskParentRunId = existingRequest?.delegatedTaskParentRunId;4676+ const childOrigin = projection.thread.forkedFrom;4677+ const parentThreadId = projection.thread.lineage.parentThreadId;4678+ if (4679+ existingRequest === undefined &&4680+ dispatchMode.type !== "steer_active" &&
- apps/server/src/orchestration-v2/ProjectionStore.ts lines 3522 to 3564Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3501,3 +3510,18 @@3501- WHERE thread_id = child.thread_id3502- ORDER BY ordinal DESC LIMIT 13503- ) IN ('completed', 'interrupted', 'failed', 'cancelled', 'rolled_back')3510+ AND terminal.status IN ('completed', 'interrupted', 'failed', 'cancelled')3511+ AND CASE WHEN terminal.ordinal = 1 THEN 13512+ WHEN json_valid(terminal.payload_json) THEN3513+ json_extract(terminal.payload_json, '$.startedAt') IS NOT NULL3514+ ELSE 0 END3515+ AND NOT EXISTS (3516+ SELECT 1 FROM orchestration_v2_projection_messages AS message3517+ WHERE message.thread_id = child.thread_id3518+ AND message.message_id = json_extract(terminal.payload_json, '$.userMessageId')3519+ AND CASE WHEN json_valid(message.payload_json) THEN3520+ json_extract(message.payload_json, '$.notification') IS NOT NULL3521+ OR json_extract(message.payload_json, '$.scheduledTaskId') IS NOT NULL3522+ OR (json_extract(message.payload_json, '$.creationSource') = 'server'3523+ AND json_extract(message.payload_json, '$.createdBy') IS NOT 'user'3524+ AND NOT (3525+ (terminal.ordinal = 1 AND json_extract(message.payload_json, '$.notification') IS NULL)3526+ OR json_extract(terminal.payload_json, '$.restartContinuationOfRunId') IS NOT NULL3527+ ))
- @@ -145,3 +146,13 @@145146 } satisfies RuntimeSubagent;146147 });147148 }149+150+/** Live child work is separate from the retained result of its original delegation. */151+export function activeSubagentThreadStatus(152+ child: OrchestrationV2ThreadShell | undefined,153+): OrchestrationV2Subagent["status"] | null {154+ if (child === undefined || child.deletedAt !== null || child.archivedAt !== null) return null;155+ const status = child.activityRunStatus ?? child.status;156+ if (status === "queued" || status === "preparing" || status === "starting") return "pending";157+ if (status === "running" || status === "waiting") return status;158+ return backgroundWorkHoldsCompletion(child.pendingBackgroundTasks ?? []) ? "waiting" : null;@@ -4733,0 +4791,21 @@4791+ task.childThreadId === command.threadId,4792+ );4793+ if (task !== undefined) {4794+ const latestRun = parent.runs.at(-1);4795+ const wake =4796+ latestRun === undefined4797+ ? undefined4798+ : (yield* mapDispatchError(command)(4799+ projectionStore.getThreadRecords(parentThreadId, ["messages"], {4800+ messageIds: [latestRun.userMessageId],4801+ }),4802+ )).messages[0];4803+ const originalParentRun = parent.runs.find((run) => run.id === task.runId);4804+ delegatedTaskParentRunId =4805+ parent.thread.archivedAt !== null ||4806+ parent.thread.deletedAt !== null ||4807+ originalParentRun?.delegatedCompletion?.disposition === undefined ||4808+ originalParentRun.delegatedCompletion.disposition === "open"4809+ ? (task.runId ?? undefined)4810+ : (wake?.delegatedCompletion?.parentRunId ??4811+ latestRun?.id ??@@ -1275,5 +1264,8 @@12751264 messages: [...childControls.messages, ...resultRecords.messages],12761265 turnItems: resultRecords.turnItems,12771266 };1278- // A restart cut the child's run and its continuation has not settled, or1279- // the child started working again after this read.1267+ const currentRun =1268+ workRuns.findLast((run) =>1269+ ["preparing", "starting", "running", "waiting"].includes(run.status),1270+ ) ??1271+ workRuns.findLast((run) => run.status === "queued" && run.queueHeld !== true) ??@@ -4733,0 +4796,21 @@4796+ latestRun === undefined4797+ ? undefined4798+ : (yield* mapDispatchError(command)(4799+ projectionStore.getThreadRecords(parentThreadId, ["messages"], {4800+ messageIds: [latestRun.userMessageId],4801+ }),4802+ )).messages[0];4803+ const originalParentRun = parent.runs.find((run) => run.id === task.runId);4804+ delegatedTaskParentRunId =4805+ parent.thread.archivedAt !== null ||4806+ parent.thread.deletedAt !== null ||4807+ originalParentRun?.delegatedCompletion?.disposition === undefined ||4808+ originalParentRun.delegatedCompletion.disposition === "open"4809+ ? (task.runId ?? undefined)4810+ : (wake?.delegatedCompletion?.parentRunId ??4811+ latestRun?.id ??4812+ task.runId ??4813+ undefined);4814+ const owningRun = parent.runs.find((run) => run.id === delegatedTaskParentRunId);4815+ if (4816+ owningRun !== undefined &&
Sign in to join this conversation.
Approvability#
Verdict: Not approved
Macroscope's review found this PR not approvable — This XXL change introduces cross-layer subagent follow-up behavior, including new parent-child ownership, result delivery, recovery, status, and Stop semantics across server, clients, and contracts. Its broad stateful runtime impact and unresolved medium-severity delivery/recovery risks require human review.
Not approved because:
- 5 blocking correctness issues found at or above your repo's Minimum Blocking Severity
Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).