Skip to content

Commit 0f412d5

Browse files
committed
fix(server): deliver results and wake parents for subagent follow-ups
1 parent 00b1700 commit 0f412d5

7 files changed

Lines changed: 629 additions & 38 deletions

File tree

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,7 @@ function pageIncludesTerminalTaskResult(input: {
365365
>;
366366
readonly maxChars: number;
367367
}): boolean {
368-
const transfer = input.parent.contextTransfers.find(
368+
const transfer = input.parent.contextTransfers.findLast(
369369
(transfer) =>
370370
transfer.type === "subagent_result" &&
371371
transfer.sourceThreadId === input.target.thread.id &&
@@ -1134,6 +1134,7 @@ const make = Effect.gen(function* () {
11341134
}),
11351135
parentThreadId: scope.threadId,
11361136
taskId,
1137+
...(terminalRun === undefined ? {} : { resultRunId: terminalRun.id }),
11371138
observedByRunId:
11381139
observingRun?.providerInstanceId === scope.providerInstanceId
11391140
? observingRun.id
@@ -1782,7 +1783,7 @@ const make = Effect.gen(function* () {
17821783
const messagesByThreadId = new Map(sourceMessages);
17831784
const task = directAppOwnedChildTask(parent, target);
17841785
if (task !== undefined && (input.textOffset ?? 0) === 0) {
1785-
const transfer = parent.contextTransfers.find(
1786+
const transfer = parent.contextTransfers.findLast(
17861787
(transfer) =>
17871788
transfer.type === "subagent_result" &&
17881789
transfer.sourceThreadId === target.thread.id &&

‎apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts‎

Lines changed: 377 additions & 14 deletions
Large diffs are not rendered by default.

‎apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
33
import { assert, it } from "@effect/vitest";
44
import {
55
CommandId,
6+
ContextTransferId,
67
EventId,
78
MessageId,
89
type ModelSelection,
@@ -291,6 +292,88 @@ const seedParentWithTerminalTask = (input: {
291292
});
292293

293294
it.layer(TestLayer)("delegated completion delivery repairs", (it) => {
295+
it.effect("an older result acknowledgement does not consume a follow-up delivery", () =>
296+
Effect.gen(function* () {
297+
const orchestrator = yield* Orchestrator.OrchestratorV2;
298+
const sink = yield* EventSink.EventSinkV2;
299+
const now = yield* DateTime.now;
300+
const threadId = ThreadId.make("thread:follow-up-ack");
301+
const childId = ThreadId.make("child:follow-up-ack");
302+
const runId = RunId.make("run:follow-up-ack-parent");
303+
const resultRunId = RunId.make("run:follow-up-ack-child");
304+
const taskId = NodeId.make("task:follow-up-ack");
305+
yield* seedParentWithTerminalTask({
306+
threadId,
307+
runId,
308+
projectId: ProjectId.make("project:follow-up-ack"),
309+
rootNodeId: NodeId.make("root:follow-up-ack"),
310+
taskId,
311+
deliveryState: "claimed",
312+
completionWake: "always",
313+
deliveryTaskIds: [taskId],
314+
now,
315+
});
316+
const task = (yield* orchestrator.getThreadProjection(threadId)).subagents[0]!;
317+
yield* sink.write({
318+
events: [
319+
{
320+
id: EventId.make("event:follow-up-ack-task"),
321+
type: "subagent.updated",
322+
threadId,
323+
occurredAt: now,
324+
payload: { ...task, childThreadId: childId },
325+
},
326+
{
327+
id: EventId.make("event:follow-up-ack-transfer"),
328+
type: "context-transfer.created",
329+
threadId,
330+
occurredAt: now,
331+
payload: {
332+
id: ContextTransferId.make("transfer:follow-up-ack"),
333+
type: "subagent_result",
334+
sourceThreadId: childId,
335+
targetThreadId: threadId,
336+
sourcePoint: { threadId: childId, runId: resultRunId },
337+
basePoint: null,
338+
sourceProviderInstanceId: modelSelection.instanceId,
339+
targetProviderInstanceId: modelSelection.instanceId,
340+
targetRunId: runId,
341+
status: "consumed",
342+
resolution: null,
343+
createdBy: "system",
344+
error: null,
345+
createdAt: now,
346+
updatedAt: now,
347+
consumedAt: now,
348+
},
349+
},
350+
],
351+
});
352+
yield* orchestrator.dispatch({
353+
type: "delegated_task.completion-delivery.acknowledge",
354+
commandId: CommandId.make("command:follow-up-ack-stale"),
355+
parentThreadId: threadId,
356+
taskId,
357+
resultRunId: RunId.make("run:original-child"),
358+
observedByRunId: runId,
359+
});
360+
const unchanged = yield* orchestrator.getThreadProjection(threadId);
361+
assert.equal(unchanged.subagents[0]?.completionDelivery?.state, "claimed");
362+
assert.deepEqual(unchanged.runs[0]?.delegatedCompletion?.delivery?.taskIds, [taskId]);
363+
yield* orchestrator.dispatch({
364+
type: "delegated_task.completion-delivery.acknowledge",
365+
commandId: CommandId.make("command:follow-up-ack-current"),
366+
parentThreadId: threadId,
367+
taskId,
368+
resultRunId,
369+
observedByRunId: runId,
370+
});
371+
const acknowledged = yield* orchestrator.getThreadProjection(threadId);
372+
assert.equal(acknowledged.subagents[0]?.completionDelivery?.state, "acknowledged");
373+
assert.equal(acknowledged.runs[0]?.delegatedCompletion?.delivery, null);
374+
}),
375+
);
376+
294377
it.effect("acceptance batches pending siblings without acknowledging their results", () =>
295378
Effect.gen(function* () {
296379
const orchestrator = yield* Orchestrator.OrchestratorV2;

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 43 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1760,7 +1760,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
17601760
const projection = yield* projectionStore
17611761
.getThreadRecords(
17621762
command.parentThreadId,
1763-
["subagents", "runs", "messages", "nodes", "attempts", "turnItems"],
1763+
["subagents", "runs", "messages", "nodes", "attempts", "turnItems", "contextTransfers"],
17641764
{ turnItemTypes: [], messageRoles: ["user"] },
17651765
)
17661766
.pipe(
@@ -1792,7 +1792,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
17921792
// valid observations can race after their read preflight. Re-emit the
17931793
// existing task row so the second dispatch is a successful idempotent
17941794
// no-op rather than "already acknowledged/disposed" or empty-events.
1795+
const latestResultTransfer = projection.contextTransfers.findLast(
1796+
(transfer) =>
1797+
transfer.type === "subagent_result" &&
1798+
transfer.sourceThreadId === task.childThreadId &&
1799+
transfer.targetThreadId === command.parentThreadId,
1800+
);
17951801
if (
1802+
(command.type === "delegated_task.completion-delivery.acknowledge" &&
1803+
command.resultRunId !== undefined &&
1804+
latestResultTransfer?.sourcePoint.runId !== undefined &&
1805+
latestResultTransfer.sourcePoint.runId !== command.resultRunId) ||
17961806
task.completionDelivery?.state === state ||
17971807
(command.type === "delegated_task.completion-delivery.acknowledge" &&
17981808
task.completionDelivery?.state === "disposed")
@@ -8540,15 +8550,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
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(
8561+
(transfer) =>
8562+
transfer.sourcePoint.runId === childRun.id ||
8563+
// Legacy unscoped transfers belong to the original child turn.
8564+
(transfer.sourcePoint.runId === undefined && childRun.ordinal === 1),
8565+
)
8566+
)
85508567
return;
8551-
}
8568+
const isFollowUp = resultTransfers.length > 0;
85528569

85538570
const now = yield* DateTime.now;
85548571
const result = subagentResultForRun(childProjection, childRun);
@@ -8560,18 +8577,29 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
85608577
const parentTurnItem = parentProjection.turnItems.find(
85618578
(candidate) => candidate.type === "subagent" && candidate.subagentId === task.id,
85628579
);
8563-
const updatedTask: OrchestrationV2Subagent = {
8564-
...task,
8565-
providerThreadId: childRun.providerThreadId,
8566-
status: terminalStatus,
8567-
result: result.text,
8568-
completedAt: now,
8569-
updatedAt: now,
8570-
};
8580+
// Keep the original task result and history. A new child run only
8581+
// reopens completion delivery for its own result.
8582+
const updatedTask: OrchestrationV2Subagent = isFollowUp
8583+
? {
8584+
...task,
8585+
// Follow-ups return through notifications even when the original
8586+
// delegation returned through a blocking wait tool call.
8587+
completionWake: "always",
8588+
completionDelivery: { state: "pending", observedByRunId: null },
8589+
updatedAt: now,
8590+
}
8591+
: {
8592+
...task,
8593+
providerThreadId: childRun.providerThreadId,
8594+
status: terminalStatus,
8595+
result: result.text,
8596+
completedAt: now,
8597+
updatedAt: now,
8598+
};
85718599
const completionPlan = yield* planDelegatedCompletionDelivery({
85728600
parentProjection,
85738601
parentRun,
8574-
task,
8602+
task: updatedTask,
85758603
updatedTask,
85768604
now,
85778605
});
@@ -8693,7 +8721,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
86938721
payload: completionPlan.message,
86948722
},
86958723
]),
8696-
...(parentNode === undefined
8724+
...(isFollowUp || parentNode === undefined
86978725
? []
86988726
: [
86998727
{
@@ -8711,7 +8739,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
87118739
},
87128740
},
87138741
]),
8714-
...(parentTurnItem === undefined
8742+
...(isFollowUp || parentTurnItem === undefined
87158743
? []
87168744
: [
87178745
{

‎apps/server/src/orchestration-v2/ProjectionStore.test.ts‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
EnvironmentId,
44
EventId,
55
CommandId,
6+
ContextTransferId,
67
CheckpointId,
78
CheckpointRef,
89
CheckpointScopeId,
@@ -328,6 +329,110 @@ it.effect("memory recovery selection includes unfinished items from missing runs
328329
}).pipe(Effect.provide(ProjectionStore.layerMemory)),
329330
);
330331

332+
const followUpResultRecovery = Effect.gen(function* () {
333+
const store = yield* ProjectionStore.ProjectionStoreV2;
334+
const childId = yield* addRolledBackRecoveryCandidate("follow-up-result");
335+
const projection = yield* store.getThreadProjection(childId);
336+
const parentId = ThreadId.make("parent:follow-up-result");
337+
const original = { ...projection.runs[0]!, status: "completed" as const };
338+
const now = yield* DateTime.now;
339+
yield* store.apply({
340+
id: EventId.make("follow-up-result:lineage"),
341+
type: "thread.metadata-updated",
342+
threadId: childId,
343+
occurredAt: now,
344+
payload: {
345+
...projection.thread,
346+
lineage: {
347+
parentThreadId: parentId,
348+
rootThreadId: parentId,
349+
relationshipToParent: "subagent",
350+
},
351+
forkedFrom: {
352+
type: "node",
353+
nodeId: NodeId.make("task:follow-up-result"),
354+
},
355+
},
356+
});
357+
yield* store.apply({
358+
id: EventId.make("follow-up-result:original"),
359+
type: "run.updated",
360+
threadId: childId,
361+
runId: original.id,
362+
occurredAt: now,
363+
payload: original,
364+
});
365+
const transfer = {
366+
id: ContextTransferId.make("transfer:original"),
367+
type: "subagent_result" as const,
368+
sourceThreadId: childId,
369+
targetThreadId: parentId,
370+
sourcePoint: { threadId: childId },
371+
basePoint: null,
372+
sourceProviderInstanceId: providerInstanceId,
373+
targetProviderInstanceId: providerInstanceId,
374+
targetRunId: null,
375+
status: "consumed" as const,
376+
resolution: null,
377+
createdBy: "system" as const,
378+
error: null,
379+
createdAt: now,
380+
updatedAt: now,
381+
consumedAt: now,
382+
};
383+
yield* store.apply({
384+
id: EventId.make("follow-up-result:legacy-transfer"),
385+
type: "context-transfer.created",
386+
threadId: childId,
387+
occurredAt: now,
388+
payload: transfer,
389+
});
390+
assert.notInclude(yield* store.getRecoveryThreadIds("subagent-results"), childId);
391+
const followup = {
392+
...original,
393+
id: RunId.make("run:follow-up-result"),
394+
ordinal: 2,
395+
status: "running" as const,
396+
};
397+
yield* store.apply({
398+
id: EventId.make("follow-up-result:running"),
399+
type: "run.updated",
400+
threadId: childId,
401+
runId: followup.id,
402+
occurredAt: now,
403+
payload: followup,
404+
});
405+
assert.notInclude(yield* store.getRecoveryThreadIds("subagent-results"), childId);
406+
yield* store.apply({
407+
id: EventId.make("follow-up-result:completed"),
408+
type: "run.updated",
409+
threadId: childId,
410+
runId: followup.id,
411+
occurredAt: now,
412+
payload: { ...followup, status: "completed" },
413+
});
414+
assert.include(yield* store.getRecoveryThreadIds("subagent-results"), childId);
415+
yield* store.apply({
416+
id: EventId.make("follow-up-result:new-transfer"),
417+
type: "context-transfer.created",
418+
threadId: childId,
419+
occurredAt: now,
420+
payload: {
421+
...transfer,
422+
id: ContextTransferId.make("transfer:follow-up"),
423+
sourcePoint: { threadId: childId, runId: followup.id },
424+
},
425+
});
426+
assert.notInclude(yield* store.getRecoveryThreadIds("subagent-results"), childId);
427+
});
428+
429+
it.effect("recovers only undelivered follow-up results in memory", () =>
430+
followUpResultRecovery.pipe(Effect.provide(ProjectionStore.layerMemory)),
431+
);
432+
it.effect("recovers only undelivered follow-up results in SQLite", () =>
433+
followUpResultRecovery.pipe(Effect.provide(TestLayer)),
434+
);
435+
331436
it.layer(TestLayer)("ProjectionStoreV2", (it) => {
332437
it.effect(
333438
"keeps restart-cancelled work through a stale run.updated",

0 commit comments

Comments
 (0)