Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
33 changes: 21 additions & 12 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,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" ||
Expand Down Expand Up @@ -7170,13 +7186,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
command: 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) =>
Expand All @@ -7200,7 +7210,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
if (
child.lineage.relationshipToParent !== "subagent" ||
parentThreadId === null ||
(command.createdBy !== "user" && command.senderThreadId !== parentThreadId)
(command.notification === undefined &&
command.createdBy !== "user" &&
command.senderThreadId !== parentThreadId)
)
return;
const run =
Expand Down Expand Up @@ -11784,10 +11796,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
commandThreadId(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(
Expand Down
Loading