TypeScript
fix(server): notify parents after delegated background runs (#23542)
Julius Marminge0504c99205e4
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.tsindex ecea6544f15..3bf563c1f79 100644--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts@@ -1404,6 +1404,138 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(}),);+ it.effect("delivers the run a background command's wake starts after the original result", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const eventSink = yield* EventSink.EventSinkV2;+ const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;+ const now = yield* DateTime.now;+ const parentThreadId = ThreadId.make("thread:background-wake-parent");+ const projectId = ProjectId.make("project:background-wake");+ const parentRunId = RunId.make("run:background-wake-parent");+ const rootNodeId = NodeId.make("node:background-wake-parent");+ yield* seedParentWithTerminalTask({+ threadId: parentThreadId,+ projectId,+ runId: parentRunId,+ rootNodeId,+ taskId: NodeId.make("node:background-wake-seed"),+ deliveryState: "acknowledged",+ now,+ });+ const child = yield* seedRestartCancelledChild({+ parentThreadId,+ projectId,+ parentRunId,+ rootNodeId,+ name: "background-wake-child",+ completionWake: "always",+ continuationPending: false,+ runStatus: "completed",+ now,+ });+ yield* orchestrator.recoverDelegatedTasks;+ let firstWake = yield* requests.take;+ while (firstWake.threadId !== parentThreadId) firstWake = yield* requests.take;+ yield* orchestrator.dispatch({+ type: "delegated_task.completion-delivery.acknowledge",+ commandId: CommandId.make("command:background-wake-ack"),+ parentThreadId,+ taskId: child.taskId,+ observedByRunId: parentRunId,+ });+ const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.find(+ (run) => run.id === parentRunId,+ )!;+ yield* eventSink.write({+ commandId: reconcileCommandId("background-wake-parent-finished"),+ events: [+ {+ id: EventId.make("event:background-wake-parent-finished"),+ type: "run.updated",+ threadId: parentThreadId,+ runId: parentRunId,+ occurredAt: now,+ payload: { ...parentRun, status: "completed", completedAt: now },+ },+ ],+ });++ // The shape ProviderContinuationService dispatches when the provider+ // reports a background command (wire kind `background_command`) ended.+ const wakeMessageId = MessageId.make("message:background-wake");+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ createdBy: "agent",+ creationSource: "provider",+ commandId: CommandId.make("command:background-wake"),+ threadId: child.childThreadId,+ messageId: wakeMessageId,+ text: "Background activity updated",+ notification: {+ source: { kind: "command" },+ outcome: "completed",+ summary: 'Command "sleep 60" finished',+ },+ attachments: [],+ dispatchMode: { type: "queue_after_active" },+ });+ const run = (yield* orchestrator.getThreadProjection(child.childThreadId)).runs.find(+ (row) => row.userMessageId === wakeMessageId,+ )!;+ assert.isDefined(run.delegatedTaskId);+ yield* eventSink.write({+ commandId: reconcileCommandId("background-wake-finished"),+ events: [+ {+ id: EventId.make("event:background-wake-result"),+ type: "message.updated",+ threadId: child.childThreadId,+ runId: run.id,+ occurredAt: now,+ payload: {+ id: MessageId.make("message:background-wake-result"),+ threadId: child.childThreadId,+ runId: run.id,+ nodeId: null,+ role: "assistant",+ text: "The background command finished cleanly.",+ attachments: [],+ streaming: false,+ createdBy: "agent",+ creationSource: "server",+ createdAt: now,+ updatedAt: now,+ },+ },+ {+ id: EventId.make("event:background-wake-finished"),+ type: "run.updated",+ threadId: child.childThreadId,+ runId: run.id,+ occurredAt: now,+ payload: { ...run, status: "completed", startedAt: now, completedAt: now },+ },+ ],+ });+ yield* orchestrator.recoverDelegatedTasks;+ const followup = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find(+ (task) => task.id === run.delegatedTaskId,+ )!;+ assert.equal(followup.status, "completed");+ assert.equal(followup.result, "The background command finished cleanly.");+ assert.equal(followup.completionDelivery?.state, "claimed");+ let wake = yield* requests.take;+ while (+ wake.threadId !== parentThreadId ||+ wake.delegatedCompletion?.messageId === firstWake.delegatedCompletion?.messageId+ ) {+ wake = yield* requests.take;+ }+ assert.equal(wake.delegatedCompletion?.parentRunId, parentRunId);+ }),+ );+const outcomes = ["completed","failed",diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 1acc40a6a13..10a82682fc1 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -600,6 +600,22 @@ function cancelledAppOwnedTask(};}+/**+ * Whether a message sent into a delegated child may become a follow-up task the parent hears+ * back from. Besides a person or agent writing to the child, a provider wake counts, such as a+ * background command finishing: the child acts on it after its original result was delivered.+ * A monitor update does not, since it reports progress rather than asking for new work.+ * Dispatch takes the parent's lock for exactly these, because intake writes the parent.+ */+function mayStartSubagentFollowup(+ command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,+): boolean {+ if (command.scheduledTaskId !== undefined || command.restartContinuationOfRunId !== undefined)+ return false;+ if (command.notification !== undefined) return command.notification.source.kind !== "monitor";+ return command.createdBy === "user" || command.creationSource === "mcp";+}+function isBlockingRun(run: OrchestrationV2Run): boolean {return (run.status === "preparing" ||@@ -7313,13 +7329,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocommand: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,) {- if (- command.scheduledTaskId !== undefined ||- command.notification !== undefined ||- command.restartContinuationOfRunId !== undefined ||- (command.createdBy !== "user" && command.creationSource !== "mcp")- )- return;+ if (!mayStartSubagentFollowup(command)) return;const pending = yield* Ref.get(events);const message = pending.flatMap((event) =>@@ -7341,7 +7351,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioif (child.lineage.relationshipToParent !== "subagent" ||parentThreadId === null ||- (command.createdBy !== "user" && command.senderThreadId !== parentThreadId)+ (command.notification === undefined &&+ command.createdBy !== "user" &&+ command.senderThreadId !== parentThreadId))return;const run =@@ -12117,10 +12129,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocommandThreadId(command),dispatchWithReceiptEffect(command),);- if (- command.type !== "message.dispatch" ||- (command.createdBy !== "user" && command.creationSource !== "mcp")- )+ if (command.type !== "message.dispatch" || !mayStartSubagentFollowup(command))return yield* dispatch;const parentThreadId = yield* appOwnedSubagentParentThreadId(command.threadId).pipe(Effect.mapError(